Skip to content

The open alternative to Salesforce, designed for AI.

Run server integration tests on 24 shards and split the two slowest chat specs (#29594)

Charles Bochet0a9160d2948a
diff --git a/.github/workflows/ci-server-integration-test.yaml b/.github/workflows/ci-server-integration-test.yaml
index 1d78d65e32e..d9eac0bb08e 100644
--- a/.github/workflows/ci-server-integration-test.yaml
+++ b/.github/workflows/ci-server-integration-test.yaml
@@ -48,7 +48,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
+ shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
services:
postgres:
image: postgres:18
@@ -84,7 +84,7 @@ jobs:
ANALYTICS_ENABLED: true
CLICKHOUSE_URL: "http://default:clickhousePassword@localhost:8123/twenty"
CLICKHOUSE_PASSWORD: clickhousePassword
- SHARD_COUNTER: 16
+ SHARD_COUNTER: 24
INTEGRATION_TEST_DB_RESET_STATUS_FILE: ${{ github.workspace }}/.cache/integration-db-reset-status
steps:
- name: Fetch custom Github Actions and base branch history
diff --git a/packages/twenty-server/project.json b/packages/twenty-server/project.json
index 973880bf9d2..ab549057239 100644
--- a/packages/twenty-server/project.json
+++ b/packages/twenty-server/project.json
@@ -7,6 +7,7 @@
"build": {
"executor": "nx:run-commands",
"cache": true,
+ "inputs": ["^production", "production", "!{projectRoot}/test/**/*"],
"options": {
"cwd": "packages/twenty-server",
"parallel": false,
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-channel.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-channel.integration-spec.ts
deleted file mode 100644
index 64d8934a6cb..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/chat-channel.integration-spec.ts
+++ /dev/null
@@ -1,2099 +0,0 @@
-import { randomUUID } from 'node:crypto';
-
-import { parse } from 'graphql';
-import { type AgentChatInboxAction } from 'twenty-shared/ai';
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-import { NavigationMenuItemType } from 'twenty-shared/types';
-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
-import { type QueryRunner } from 'typeorm';
-
-import { assertGraphQLSuccessfulResponse } from 'test/integration/graphql/utils/graphql-test-assertions.util';
-import { createNavigationMenuItem } from 'test/integration/metadata/suites/navigation-menu-item/utils/create-navigation-menu-item.util';
-import { findNavigationMenuItems } from 'test/integration/metadata/suites/navigation-menu-item/utils/find-navigation-menu-items.util';
-import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
-import { updateOneRole } from 'test/integration/metadata/suites/role/utils/update-one-role.util';
-import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
-import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
-import { expectEventually } from 'test/integration/utils/expect-eventually.util';
-import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
-import { listChatThreadIds } from 'test/integration/utils/list-chat-thread-ids.util';
-import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
-
-import { type PostgresAdvisoryLockService } from 'src/database/typeorm/postgres-advisory-lock.service';
-import { type AgentChatChannelMetadataService } from 'src/engine/metadata-modules/agent-chat-channel/services/agent-chat-channel-metadata.service';
-import { type AgentChatChannelSummaryDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-channel-summary.dto';
-import { type UpdateAgentChatChannelInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/update-agent-chat-channel.input';
-import { type AgentChatChannelAccessService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-channel-access.service';
-import { type AgentChatChannelGrantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-channel-grant.service';
-import { type AgentChatThreadTriageService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-triage.service';
-import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
-import { acquireAgentChatChannelGrantLocks } from 'src/engine/metadata-modules/ai/ai-chat/utils/acquire-agent-chat-channel-grant-locks.util';
-import { buildAgentChatChannelDeletionLockKey } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-channel-deletion-lock-key.util';
-import { buildAgentChatChannelGrantLockKey } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-channel-grant-lock-key.util';
-import { detachAgentChatChannelThreadsFromWorkspaceMember } from 'src/engine/metadata-modules/ai/ai-chat/utils/detach-agent-chat-channel-threads-from-workspace-member.util';
-import { lockAgentChatChannelForThreadWriteOrThrow } from 'src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-channel-for-thread-write-or-throw.util';
-import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
-import { getAgentHistoryRepositoryToken } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
-import { type MetadataEventEmitter } from 'src/engine/subscriptions/metadata-event/metadata-event-emitter';
-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { type WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
-import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-
-const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
-
-const { JANE, JONY } = WORKSPACE_MEMBER_DATA_SEED_IDS;
-
-type ChannelAccess = { roleIds?: string[] };
-
-type ChannelThreadsFilter = {
- status?: 'OPEN' | 'SNOOZED' | 'DONE';
- assignment?: 'ANY' | 'ASSIGNED' | 'UNASSIGNED' | 'ASSIGNED_TO_ME';
- filter?: 'ANY' | 'NEEDS_INPUT' | 'MENTIONED';
-};
-
-type ChannelThreadMutationName =
- | 'markAgentChatThreadAsDoneInChannel'
- | 'reopenAgentChatThreadInChannel';
-
-const CREATE_CHANNEL = parse(
- `mutation CreateChannel($input: CreateAgentChatChannelInput!) { createAgentChatChannel(input: $input) { id name icon color roleIds applicationId } }`,
-);
-
-const UPDATE_CHANNEL = parse(
- `mutation UpdateChannel($channelId: UUID!, $input: UpdateAgentChatChannelInput!) { updateAgentChatChannel(channelId: $channelId, input: $input) { id name roleIds } }`,
-);
-
-const DELETE_CHANNEL = parse(
- `mutation DeleteChannel($channelId: UUID!, $destinationChannelId: UUID) { deleteAgentChatChannel(channelId: $channelId, destinationChannelId: $destinationChannelId) }`,
-);
-
-const CHANNEL_ROLES = parse(
- `query ChannelRoles { agentChatChannelRoles { id } }`,
-);
-
-const CHANNELS = parse(
- `query Channels { agentChatChannels { id name applicationId isCustom isAccessible } }`,
-);
-
-const CREATE_THREAD = parse(
- `mutation CreateThread($channelId: UUID) { createChatThread(channelId: $channelId) { id } }`,
-);
-
-const MOVE_THREAD = parse(
- `mutation Move($threadId: UUID!, $channelId: UUID) { moveAgentChatThreadToChannel(threadId: $threadId, channelId: $channelId) }`,
-);
-
-const THREAD_MUTATION = (name: ChannelThreadMutationName) =>
- parse(`mutation Run($threadId: UUID!) { ${name}(threadId: $threadId) }`);
-
-const UPDATE_INBOX_STATE = parse(
- `mutation Update($threadIds: [UUID!]!, $action: AgentChatInboxAction!, $snoozedUntil: DateTime) { updateAgentChatThreadInboxState(threadIds: $threadIds, action: $action, snoozedUntil: $snoozedUntil) { id } }`,
-);
-
-const SNOOZE_IN_CHANNEL = parse(
- `mutation Snooze($threadId: UUID!, $snoozedUntil: DateTime!) { snoozeAgentChatThreadInChannel(threadId: $threadId, snoozedUntil: $snoozedUntil) }`,
-);
-
-const ASSIGN = parse(
- `mutation Assign($threadId: UUID!, $assigneeWorkspaceMemberId: UUID) { assignAgentChatThread(threadId: $threadId, assigneeWorkspaceMemberId: $assigneeWorkspaceMemberId) }`,
-);
-
-const CHANNEL_THREAD_IDS = parse(
- `query Ids($channelId: UUID!, $status: AgentChatChannelThreadStatus, $assignment: AgentChatChannelAssignmentFilter, $filter: AgentChatChannelThreadFilter, $first: Int, $after: String) { agentChatChannelThreadIds(channelId: $channelId, status: $status, assignment: $assignment, filter: $filter, first: $first, after: $after) { threadIds hasNextPage endCursor } }`,
-);
-
-const CHANNEL_SUMMARIES = parse(
- `query Summaries { agentChatChannelSummaries { channelId openCount assignedToMeCount snoozedCount doneCount hasUnreadOpen hasUnreadAssignedToMe } }`,
-);
-
-const OPEN_THREADS_SUMMARY = parse(
- `query Summary { agentChatOpenThreadsSummary { openThreadCount hasUnreadOpenThread } }`,
-);
-
-// Outlasts any test, yet within the delay the test queue fast-forwards
-const buildFutureSnoozedUntil = () =>
- new Date(Date.now() + 30_000).toISOString();
-
-const runThreadMutation = (
- name: ChannelThreadMutationName,
- threadId: string,
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
-) =>
- makeMetadataApiRequest(
- { query: THREAD_MUTATION(name), variables: { threadId } },
- token,
- );
-
-const runInboxAction = (
- action: AgentChatInboxAction,
- threadId: string,
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
- snoozedUntil: string | null = null,
-) =>
- makeMetadataApiRequest(
- {
- query: UPDATE_INBOX_STATE,
- variables: { threadIds: [threadId], action, snoozedUntil },
- },
- token,
- );
-
-const findChannelThreadIds = async (
- channelId: string,
- filter: ChannelThreadsFilter = {},
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
- page: { first?: number; after?: string } = {},
-): Promise<{
- threadIds: string[];
- hasNextPage: boolean;
- endCursor: string | null;
-}> => {
- const response = await makeMetadataApiRequest(
- {
- query: CHANNEL_THREAD_IDS,
- variables: { channelId, ...filter, ...page, first: page.first ?? 200 },
- },
- token,
- );
-
- assertGraphQLSuccessfulResponse(response);
-
- return response.body.data.agentChatChannelThreadIds;
-};
-
-const getChannelSummaries = async (
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
-): Promise<AgentChatChannelSummaryDTO[]> => {
- const response = await makeMetadataApiRequest(
- { query: CHANNEL_SUMMARIES },
- token,
- );
-
- assertGraphQLSuccessfulResponse(response);
-
- return response.body.data.agentChatChannelSummaries;
-};
-
-const getOpenThreadCount = async (
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
-): Promise<number> => {
- const response = await makeMetadataApiRequest(
- { query: OPEN_THREADS_SUMMARY },
- token,
- );
-
- assertGraphQLSuccessfulResponse(response);
-
- return response.body.data.agentChatOpenThreadsSummary.openThreadCount;
-};
-
-const readMemberCopy = async (threadId: string, workspaceMemberId: string) => {
- const [row]: {
- isSubscribed: boolean;
- archivedAt: Date | null;
- snoozedUntil: Date | null;
- }[] = await global.testDataSource.query(
- `SELECT "isSubscribed", "archivedAt", "snoozedUntil"
- FROM ${SCHEMA}."agentChatThreadParticipant"
- WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
- [threadId, workspaceMemberId],
- );
-
- return row ?? null;
-};
-
-const readChannelState = async (threadId: string) => {
- const [row]: {
- channelId: string | null;
- channelArchivedAt: Date | null;
- channelSnoozedUntil: Date | null;
- }[] = await global.testDataSource.query(
- `SELECT "channelId", "channelArchivedAt", "channelSnoozedUntil"
- FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,
- [threadId],
- );
-
- return row;
-};
-
-const listChannels = async (
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
-): Promise<
- {
- id: string;
- name: string;
- applicationId: string;
- isCustom: boolean;
- isAccessible: boolean;
- }[]
-> => {
- const response = await makeMetadataApiRequest({ query: CHANNELS }, token);
-
- assertGraphQLSuccessfulResponse(response);
-
- return response.body.data.agentChatChannels;
-};
-
-const readChannelGrants = async (
- threadId: string,
-): Promise<{ principalType: string; sourceId: string }[]> =>
- global.testDataSource.query(
- `SELECT DISTINCT "principalType", "sourceId" FROM ${SCHEMA}."recordShare"
- WHERE "recordId" = $1 AND "rowCause" = 'RULE' AND "deletedAt" IS NULL
- ORDER BY "principalType"`,
- [threadId],
- );
-
-const readChannelGrantRoleIds = async (threadId: string): Promise<string[]> =>
- (
- await global.testDataSource.query(
- `SELECT "principalId" FROM ${SCHEMA}."recordShare"
- WHERE "recordId" = $1 AND "rowCause" = 'RULE' AND "deletedAt" IS NULL
- AND "principalType" = 'ROLE'`,
- [threadId],
- )
- ).map(({ principalId }: { principalId: string }) => principalId);
-
-const setRoleAllChannelsAccess = async (
- roleId: string,
- canAccessAllAgentChatChannels: boolean,
-) => {
- const { errors } = await updateOneRole({
- input: {
- idToUpdate: roleId,
- updatePayload: { canAccessAllAgentChatChannels },
- },
- gqlFields: 'id',
- });
-
- expect(errors).toBeUndefined();
-};
-
-const waitForChannelGrantRewrites = async () => {
- await getAppProviderByClassName<MetadataEventEmitter>(
- 'MetadataEventEmitter',
- ).drain();
- await waitForAllJobsToFinish();
-};
-
-const getChannelGrantService = () =>
- getAppProviderByClassName<AgentChatChannelGrantService>(
- 'AgentChatChannelGrantService',
- );
-
-const waitForBlockedChannelGrantLock = (channelId: string) =>
- expectEventually(async () => {
- const [{ count }]: { count: number }[] = await global.testDataSource.query(
- `WITH lock_key AS (SELECT hashtextextended($1, 0) AS value)
- SELECT count(*)::int AS count FROM pg_locks, lock_key
- WHERE pg_locks.locktype = 'advisory' AND NOT pg_locks.granted
- AND pg_locks.objsubid = 1
- AND pg_locks.database = (SELECT oid FROM pg_database WHERE datname = current_database())
- AND pg_locks.classid = ((lock_key.value >> 32) & 4294967295)::oid
- AND pg_locks.objid = (lock_key.value & 4294967295)::oid`,
- [
- buildAgentChatChannelGrantLockKey({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- channelId,
- }),
- ],
- );
-
- expect(count).toBeGreaterThanOrEqual(1);
- });
-
-const isChannelInCore = async (channelId: string): Promise<boolean> =>
- isNonEmptyArray(
- await global.testDataSource.query(
- `SELECT id FROM core."agentChatChannel" WHERE id = $1`,
- [channelId],
- ),
- );
-
-const countThreadsInChannel = async (channelId: string): Promise<number> => {
- const [{ count }]: { count: number }[] = await global.testDataSource.query(
- `SELECT count(*)::int AS count FROM ${SCHEMA}."agentChatThread" WHERE "channelId" = $1`,
- [channelId],
- );
-
- return count;
-};
-
-const countThreadsInDeletedChannels = async (
- channelIds: string[],
-): Promise<number> => {
- const [{ count }]: { count: number }[] = await global.testDataSource.query(
- `SELECT count(*)::int AS count FROM ${SCHEMA}."agentChatThread" thread
- WHERE thread."channelId" = ANY($1::uuid[])
- AND NOT EXISTS (
- SELECT 1 FROM core."agentChatChannel" channel
- WHERE channel.id = thread."channelId"
- )`,
- [channelIds],
- );
-
- return count;
-};
-
-const watchThreadEvents = () => {
- const eventSpy = jest.spyOn(
- getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter'),
- 'emitDatabaseBatchEvent',
- );
-
- return {
- hasEmittedThreadEvent: (threadId: string) =>
- eventSpy.mock.calls.some(
- ([batchEvent]) =>
- batchEvent?.objectMetadataNameSingular === 'agentChatThread' &&
- batchEvent.events.some(
- (event) => 'recordId' in event && event.recordId === threadId,
- ),
- ),
- };
-};
-
-const getChannelMetadataService = () =>
- getAppProviderByClassName<AgentChatChannelMetadataService>(
- 'AgentChatChannelMetadataService',
- );
-
-const deleteChannelBehindStaleCache = async (channelId: string) => {
- const staleChannel = await getChannelMetadataService().findChannelOrThrow({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- channelId,
- });
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId },
- }),
- );
-
- jest
- .spyOn(
- getAppProviderByClassName<AgentChatChannelAccessService>(
- 'AgentChatChannelAccessService',
- ),
- 'assertChannelAccess',
- )
- .mockResolvedValue(staleChannel);
-};
-
-const insertChannelGrant = ({
- queryRunner,
- threadId,
- roleId,
- channelId,
-}: {
- queryRunner: QueryRunner;
- threadId: string;
- roleId: string;
- channelId: string;
-}) =>
- queryRunner.query(
- `INSERT INTO ${SCHEMA}."recordShare"
- ("objectMetadataId", "recordId", "principalId", "principalType", "accessLevel", "rowCause", "sourceId")
- SELECT metadata.id, $1, $2, 'ROLE', 'READ_WRITE', 'RULE', $3
- FROM core."objectMetadata" metadata
- WHERE metadata."workspaceId" = $4 AND metadata."universalIdentifier" = $5`,
- [
- threadId,
- roleId,
- channelId,
- SEED_APPLE_WORKSPACE_ID,
- STANDARD_OBJECTS.agentChatThread.universalIdentifier,
- ],
- );
-
-const simulateNewMessageActivity = (threadId: string) =>
- global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "lastActivityAt" = clock_timestamp() WHERE id = $1`,
- [threadId],
- );
-
-describe('Chat channels through the authenticated API', () => {
- const createdThreadIds: string[] = [];
- const createdChannelIds: string[] = [];
-
- const createChannel = async (
- { roleIds = [] }: ChannelAccess = {},
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
- ): Promise<string> => {
- const response = await makeMetadataApiRequest(
- {
- query: CREATE_CHANNEL,
- variables: {
- input: {
- name: ` Channel ${randomUUID()} `,
- roleIds,
- },
- },
- },
- token,
- );
-
- assertGraphQLSuccessfulResponse(response);
-
- const channelId = response.body.data.createAgentChatChannel.id;
-
- createdChannelIds.push(channelId);
-
- return channelId;
- };
-
- const updateChannel = (
- channelId: string,
- input: UpdateAgentChatChannelInput,
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
- ) =>
- makeMetadataApiRequest(
- { query: UPDATE_CHANNEL, variables: { channelId, input } },
- token,
- );
-
- const createThreadInChannel = async (
- channelId: string | null,
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
- ): Promise<string> => {
- const response = await makeMetadataApiRequest(
- { query: CREATE_THREAD, variables: { channelId } },
- token,
- );
-
- assertGraphQLSuccessfulResponse(response);
-
- const threadId = response.body.data.createChatThread.id;
-
- createdThreadIds.push(threadId);
-
- return threadId;
- };
-
- const roleIdsToReopenToAllChannels = new Set<string>();
- const heldQueryRunners: QueryRunner[] = [];
- let isChannelCacheStale = false;
-
- const startHeldTransaction = async (): Promise<QueryRunner> => {
- const queryRunner = global.testDataSource.createQueryRunner();
-
- await queryRunner.connect();
- heldQueryRunners.push(queryRunner);
- await queryRunner.startTransaction();
-
- return queryRunner;
- };
-
- const holdChannelGrantLock = async ({
- channelId,
- mode,
- }: {
- channelId: string;
- mode: 'shared' | 'exclusive';
- }): Promise<QueryRunner> => {
- const queryRunner = await startHeldTransaction();
-
- await acquireAgentChatChannelGrantLocks({
- manager: queryRunner.manager,
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- channelIds: [channelId],
- mode,
- });
-
- return queryRunner;
- };
-
- const holdChannelDeletionLock = async (
- channelId: string,
- ): Promise<QueryRunner> => {
- const queryRunner = await startHeldTransaction();
-
- await queryRunner.query(
- 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',
- [
- buildAgentChatChannelDeletionLockKey({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- channelId,
- }),
- ],
- );
-
- return queryRunner;
- };
-
- const fileThreadIntoHeldChannel = async ({
- threadId,
- channelId,
- }: {
- threadId: string;
- channelId: string;
- }): Promise<QueryRunner> => {
- const queryRunner = await startHeldTransaction();
-
- await lockAgentChatChannelForThreadWriteOrThrow({
- manager: queryRunner.manager,
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- channelId,
- });
- await queryRunner.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "channelId" = $1 WHERE id = $2`,
- [channelId, threadId],
- );
-
- return queryRunner;
- };
-
- // Jony holds Member, which reaches every channel unless a test closes it
- const closeMemberAllChannelsAccess = async (): Promise<string> => {
- const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
-
- await setRoleAllChannelsAccess(memberRoleId, false);
- roleIdsToReopenToAllChannels.add(memberRoleId);
- await waitForChannelGrantRewrites();
-
- return memberRoleId;
- };
-
- afterEach(async () => {
- jest.restoreAllMocks();
-
- const orphanedThreadCount =
- await countThreadsInDeletedChannels(createdChannelIds);
-
- for (const queryRunner of heldQueryRunners.splice(0)) {
- if (queryRunner.isTransactionActive) {
- await queryRunner.rollbackTransaction();
- }
- await queryRunner.release();
- }
-
- if (isChannelCacheStale) {
- await getAppProviderByClassName<WorkspaceCacheService>(
- 'WorkspaceCacheService',
- ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, [
- 'flatAgentChatChannelMaps',
- 'flatAgentChatChannelRoleMaps',
- 'flatRoleMaps',
- ]);
- isChannelCacheStale = false;
- }
-
- const hasRolesToReopen = roleIdsToReopenToAllChannels.size > 0;
-
- for (const roleId of roleIdsToReopenToAllChannels) {
- await setRoleAllChannelsAccess(roleId, true);
- }
- roleIdsToReopenToAllChannels.clear();
-
- if (hasRolesToReopen) {
- await waitForChannelGrantRewrites();
- }
-
- for (const threadId of createdThreadIds.splice(0)) {
- await destroyAgentChatThread({ threadId });
- }
- for (const channelId of createdChannelIds.splice(0)) {
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId },
- });
- }
-
- expect(orphanedThreadCount).toBe(0);
- });
-
- it('creates a channel under a trimmed name, after General', async () => {
- const channelId = await createChannel();
-
- const [channel]: { name: string }[] = await global.testDataSource.query(
- `SELECT name FROM core."agentChatChannel" WHERE id = $1`,
- [channelId],
- );
-
- expect(channel.name.startsWith('Channel ')).toBe(true);
- expect(channel.name.endsWith(' ')).toBe(false);
-
- const channels = await listChannels(APPLE_JONY_MEMBER_ACCESS_TOKEN);
-
- const createdChannel = channels[channels.length - 1];
-
- expect(channels[0]).toMatchObject({ name: 'General', isCustom: false });
- expect(createdChannel).toMatchObject({
- id: channelId,
- isCustom: true,
- isAccessible: true,
- });
- expect(createdChannel.applicationId).not.toBe(channels[0].applicationId);
- });
-
- it('refuses a channel without a name, or with the name of another one', async () => {
- const response = await makeMetadataApiRequest({
- query: CREATE_CHANNEL,
- variables: { input: { name: ' ' } },
- });
-
- expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
-
- const duplicateResponse = await makeMetadataApiRequest({
- query: CREATE_CHANNEL,
- variables: { input: { name: 'General' } },
- });
-
- expect(duplicateResponse.body.errors[0].extensions.code).toBe(
- 'METADATA_VALIDATION_FAILED',
- );
- });
-
- it('leaves setting channels up to who manages AI settings', async () => {
- const channelId = await createChannel();
-
- const createResponse = await makeMetadataApiRequest(
- { query: CREATE_CHANNEL, variables: { input: { name: 'By a member' } } },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const updateResponse = await updateChannel(
- channelId,
- { name: 'Renamed by a member' },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const deleteResponse = await makeMetadataApiRequest(
- { query: DELETE_CHANNEL, variables: { channelId } },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const rolesResponse = await makeMetadataApiRequest(
- { query: CHANNEL_ROLES },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- for (const response of [
- createResponse,
- updateResponse,
- deleteResponse,
- rolesResponse,
- ]) {
- expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');
- }
- });
-
- it('keeps General and its chats, as the standard sync would bring it back', async () => {
- const [general] = await listChannels();
-
- expect(general).toMatchObject({ name: 'General' });
-
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(general.id);
-
- const response = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId: general.id, destinationChannelId },
- });
-
- expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');
- expect((await readChannelState(threadId)).channelId).toBe(general.id);
- });
-
- it('lets the roles with access to all channels read and reply in its chats', async () => {
- const { id: adminRoleId } = await findOneRoleByLabel({ label: 'Admin' });
- const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: channelId },
- ]);
- expect(await readChannelGrantRoleIds(threadId)).toEqual(
- expect.arrayContaining([adminRoleId, memberRoleId]),
- );
- expect(await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toContain(
- threadId,
- );
- expect(
- (
- await findChannelThreadIds(
- channelId,
- {},
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- )
- ).threadIds,
- ).toEqual([threadId]);
-
- assertGraphQLSuccessfulResponse(
- await runInboxAction(
- 'SUBSCRIBE',
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- );
- });
-
- it('keeps a channel open to roles, and its chats, to who holds them', async () => {
- const { id: adminRoleId } = await findOneRoleByLabel({ label: 'Admin' });
- const memberRoleId = await closeMemberAllChannelsAccess();
- const channelId = await createChannel({ roleIds: [adminRoleId] });
- const threadId = await createThreadInChannel(channelId);
-
- expect(
- await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).not.toContain(threadId);
- expect(
- (await listChannels(APPLE_JONY_MEMBER_ACCESS_TOKEN)).map(({ id }) => id),
- ).not.toContain(channelId);
-
- for (const response of [
- await makeMetadataApiRequest(
- { query: CHANNEL_THREAD_IDS, variables: { channelId } },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- await makeMetadataApiRequest(
- { query: CREATE_THREAD, variables: { channelId } },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- ]) {
- expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
- }
-
- const openResponse = await updateChannel(channelId, {
- roleIds: [adminRoleId, memberRoleId],
- });
-
- assertGraphQLSuccessfulResponse(openResponse);
- expect(
- [...openResponse.body.data.updateAgentChatChannel.roleIds].sort(),
- ).toEqual([adminRoleId, memberRoleId].sort());
- expect(await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toContain(
- threadId,
- );
- expect(
- (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- openCount: 1,
- assignedToMeCount: 0,
- snoozedCount: 0,
- doneCount: 0,
- hasUnreadOpen: true,
- hasUnreadAssignedToMe: false,
- });
-
- assertGraphQLSuccessfulResponse(
- await updateChannel(channelId, { roleIds: [adminRoleId] }),
- );
-
- expect(
- await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).not.toContain(threadId);
- expect(
- (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).map(
- (summary) => summary.channelId,
- ),
- ).not.toContain(channelId);
- });
-
- it('opens every channel to a role given access to all channels, and back', async () => {
- const memberRoleId = await closeMemberAllChannelsAccess();
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- await expectEventually(async () =>
- expect(
- await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).not.toContain(threadId),
- );
-
- await setRoleAllChannelsAccess(memberRoleId, true);
-
- await expectEventually(async () =>
- expect(await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toContain(
- threadId,
- ),
- );
- expect(
- (await listChannels(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
- ({ id }) => id === channelId,
- ),
- ).toMatchObject({ isAccessible: true });
-
- await setRoleAllChannelsAccess(memberRoleId, false);
-
- await expectEventually(async () =>
- expect(
- await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).not.toContain(threadId),
- );
- });
-
- it('removes a role taken off a channel from a chat filed into it meanwhile', async () => {
- const memberRoleId = await closeMemberAllChannelsAccess();
- const channelId = await createChannel({ roleIds: [memberRoleId] });
- const threadId = await createThreadInChannel(null);
- const queryRunner = await holdChannelGrantLock({
- channelId,
- mode: 'shared',
- });
-
- await queryRunner.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "channelId" = $1 WHERE id = $2`,
- [channelId, threadId],
- );
- await insertChannelGrant({
- queryRunner,
- threadId,
- roleId: memberRoleId,
- channelId,
- });
-
- const pendingUpdateResponse = Promise.resolve(
- updateChannel(channelId, { roleIds: [] }),
- );
-
- await waitForBlockedChannelGrantLock(channelId);
- await queryRunner.commitTransaction();
-
- assertGraphQLSuccessfulResponse(await pendingUpdateResponse);
- expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
- });
-
- it('grants a chat created in a channel the roles the channel has once it may write them', async () => {
- const memberRoleId = await closeMemberAllChannelsAccess();
- const channelId = await createChannel({ roleIds: [memberRoleId] });
- const queryRunner = await holdChannelGrantLock({
- channelId,
- mode: 'exclusive',
- });
-
- await queryRunner.query(
- `DELETE FROM core."agentChatChannelRole" WHERE "channelId" = $1 AND "roleId" = $2`,
- [channelId, memberRoleId],
- );
- isChannelCacheStale = true;
-
- const pendingCreateResponse = Promise.resolve(
- makeMetadataApiRequest({
- query: CREATE_THREAD,
- variables: { channelId },
- }),
- );
-
- await waitForBlockedChannelGrantLock(channelId);
- await queryRunner.commitTransaction();
-
- const createResponse = await pendingCreateResponse;
-
- assertGraphQLSuccessfulResponse(createResponse);
-
- const threadId = createResponse.body.data.createChatThread.id;
-
- createdThreadIds.push(threadId);
-
- expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: channelId },
- ]);
- });
-
- it('drops the roles of the channel a chat leaves while that channel is rewritten', async () => {
- const memberRoleId = await closeMemberAllChannelsAccess();
- const sourceChannelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(sourceChannelId);
- const queryRunner = await holdChannelGrantLock({
- channelId: sourceChannelId,
- mode: 'exclusive',
- });
-
- const pendingMoveResponse = Promise.resolve(
- makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId: destinationChannelId },
- }),
- );
-
- await waitForBlockedChannelGrantLock(sourceChannelId);
- await insertChannelGrant({
- queryRunner,
- threadId,
- roleId: memberRoleId,
- channelId: sourceChannelId,
- });
- await queryRunner.commitTransaction();
-
- assertGraphQLSuccessfulResponse(await pendingMoveResponse);
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
- });
-
- it("makes a chat moved into a channel wait for that channel's rewrite", async () => {
- const sourceChannelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(sourceChannelId);
- const queryRunner = await holdChannelGrantLock({
- channelId: destinationChannelId,
- mode: 'exclusive',
- });
-
- const pendingMoveResponse = Promise.resolve(
- makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId: destinationChannelId },
- }),
- );
-
- await waitForBlockedChannelGrantLock(destinationChannelId);
- await queryRunner.commitTransaction();
-
- assertGraphQLSuccessfulResponse(await pendingMoveResponse);
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- });
-
- it("removes a role's access to all channels from a chat filed under the old access", async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(null);
- const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
- const queryRunner = await holdChannelGrantLock({
- channelId,
- mode: 'shared',
- });
-
- await queryRunner.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "channelId" = $1 WHERE id = $2`,
- [channelId, threadId],
- );
- await insertChannelGrant({
- queryRunner,
- threadId,
- roleId: memberRoleId,
- channelId,
- });
-
- roleIdsToReopenToAllChannels.add(memberRoleId);
- await setRoleAllChannelsAccess(memberRoleId, false);
-
- await waitForBlockedChannelGrantLock(channelId);
- await queryRunner.commitTransaction();
- await waitForChannelGrantRewrites();
-
- expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
- });
-
- it('refuses chats filed into a channel whose grants stay locked too long', async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(null);
-
- await holdChannelGrantLock({ channelId, mode: 'exclusive' });
-
- const [createResponse, moveResponse] = await Promise.all([
- makeMetadataApiRequest({
- query: CREATE_THREAD,
- variables: { channelId },
- }),
- makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId },
- }),
- ]);
-
- expect(createResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect(moveResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect((await readChannelState(threadId)).channelId).toBeNull();
- expect(await countThreadsInChannel(channelId)).toBe(0);
- });
-
- it("removes a role's access to all channels once a failed rewrite is retried", async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
- const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
-
- expect(await readChannelGrantRoleIds(threadId)).toContain(memberRoleId);
-
- const rewriteAllChannelGrants = jest
- .spyOn(getChannelGrantService(), 'rewriteAllChannelGrants')
- .mockRejectedValueOnce(new Error('Grant rewrite failed'));
-
- roleIdsToReopenToAllChannels.add(memberRoleId);
- await setRoleAllChannelsAccess(memberRoleId, false);
- await waitForChannelGrantRewrites();
-
- expect(rewriteAllChannelGrants).toHaveBeenCalledTimes(2);
- expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
- });
-
- it("applies a channel's new access once a failed rewrite is retried", async () => {
- const memberRoleId = await closeMemberAllChannelsAccess();
- const channelId = await createChannel({ roleIds: [memberRoleId] });
- const threadId = await createThreadInChannel(channelId);
-
- expect(await readChannelGrantRoleIds(threadId)).toContain(memberRoleId);
-
- jest
- .spyOn(getChannelGrantService(), 'rewriteChannelGrants')
- .mockRejectedValueOnce(new Error('Grant rewrite failed'));
-
- const response = await updateChannel(channelId, { roleIds: [] });
-
- expect(response.body.errors).toBeDefined();
-
- await waitForChannelGrantRewrites();
-
- expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
- });
-
- it("restores a channel's grants when its unchanged access is saved again", async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- await global.testDataSource.query(
- `DELETE FROM ${SCHEMA}."recordShare" WHERE "recordId" = $1 AND "rowCause" = 'RULE'`,
- [threadId],
- );
-
- assertGraphQLSuccessfulResponse(
- await updateChannel(channelId, { roleIds: [] }),
- );
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: channelId },
- ]);
- });
-
- it("creates a chat under a destroyed chat's id while its channel is rewritten", async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- createdThreadIds.splice(createdThreadIds.indexOf(threadId), 1);
- await destroyAgentChatThread({ threadId });
-
- const queryRunner = await holdChannelGrantLock({
- channelId,
- mode: 'exclusive',
- });
-
- const pendingCreate = getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- ).createThreadIfMissing({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: JANE,
- threadId,
- channelId,
- });
-
- await waitForBlockedChannelGrantLock(channelId);
- await queryRunner.query(
- `DELETE FROM ${SCHEMA}."recordShare" WHERE "rowCause" = 'RULE' AND "sourceId" = $1`,
- [channelId],
- );
- await queryRunner.commitTransaction();
- await pendingCreate;
- createdThreadIds.push(threadId);
-
- expect((await readChannelState(threadId)).channelId).toBe(channelId);
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: channelId },
- ]);
- });
-
- it('refuses a role from outside the workspace', async () => {
- const response = await makeMetadataApiRequest({
- query: CREATE_CHANNEL,
- variables: {
- input: {
- name: 'Channel with an unknown role',
- roleIds: [randomUUID()],
- },
- },
- });
-
- expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
- });
-
- it('keeps chats a member only reads in a channel out of their own inbox', async () => {
- const channelId = await createChannel();
- const jonyOpenThreadCount = await getOpenThreadCount(
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const threadId = await createThreadInChannel(channelId);
-
- assertGraphQLSuccessfulResponse(
- await runInboxAction('READ', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- );
-
- expect(await readMemberCopy(threadId, JONY)).toMatchObject({
- isSubscribed: false,
- });
- expect(await getOpenThreadCount(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toBe(
- jonyOpenThreadCount,
- );
-
- // Filing it follows it, so new activity brings it back to his inbox
- assertGraphQLSuccessfulResponse(
- await runInboxAction('ARCHIVE', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- );
-
- expect(await readMemberCopy(threadId, JONY)).toMatchObject({
- isSubscribed: true,
- });
-
- assertGraphQLSuccessfulResponse(
- await runInboxAction(
- 'MOVE_TO_INBOX',
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- );
-
- expect(await getOpenThreadCount(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toBe(
- jonyOpenThreadCount + 1,
- );
- // The creator follows the chat they started
- expect(await readMemberCopy(threadId, JANE)).toMatchObject({
- isSubscribed: true,
- archivedAt: null,
- });
- });
-
- it('files a chat for the channel, and for whoever files it if they follow it', async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- assertGraphQLSuccessfulResponse(
- await runThreadMutation(
- 'markAgentChatThreadAsDoneInChannel',
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- );
-
- expect(
- (await findChannelThreadIds(channelId, { status: 'DONE' })).threadIds,
- ).toEqual([threadId]);
- expect(
- (await findChannelThreadIds(channelId, { status: 'OPEN' })).threadIds,
- ).toEqual([]);
- // Jane follows it but did not file it, so it stays open for her
- expect((await readMemberCopy(threadId, JANE))?.archivedAt).toBeNull();
- // Jony did not follow it, so filing it for the channel leaves him out
- expect(
- (await readMemberCopy(threadId, JONY))?.archivedAt ?? null,
- ).toBeNull();
-
- assertGraphQLSuccessfulResponse(
- await runThreadMutation('reopenAgentChatThreadInChannel', threadId),
- );
- assertGraphQLSuccessfulResponse(
- await runThreadMutation('markAgentChatThreadAsDoneInChannel', threadId),
- );
-
- expect(await readMemberCopy(threadId, JANE)).toMatchObject({
- archivedAt: expect.anything(),
- });
-
- await simulateNewMessageActivity(threadId);
-
- expect(
- (await findChannelThreadIds(channelId, { status: 'OPEN' })).threadIds,
- ).toEqual([threadId]);
- });
-
- it('refuses channel triage on a chat outside any channel', async () => {
- const threadId = await createThreadInChannel(null);
- const response = await runThreadMutation(
- 'markAgentChatThreadAsDoneInChannel',
- threadId,
- );
-
- expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
- });
-
- it("files the channel's copy when the assignee files their own", async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: ASSIGN,
- variables: { threadId, assigneeWorkspaceMemberId: JONY },
- }),
- );
-
- expect(
- (await findChannelThreadIds(channelId, { assignment: 'UNASSIGNED' }))
- .threadIds,
- ).toEqual([]);
- expect(
- (
- await findChannelThreadIds(
- channelId,
- { assignment: 'ASSIGNED_TO_ME' },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- )
- ).threadIds,
- ).toEqual([threadId]);
-
- assertGraphQLSuccessfulResponse(
- await runInboxAction('ARCHIVE', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- );
-
- expect((await readChannelState(threadId)).channelArchivedAt).not.toBeNull();
-
- assertGraphQLSuccessfulResponse(
- await runInboxAction(
- 'SNOOZE',
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- buildFutureSnoozedUntil(),
- ),
- );
-
- expect(
- (await readChannelState(threadId)).channelSnoozedUntil,
- ).not.toBeNull();
-
- assertGraphQLSuccessfulResponse(
- await runInboxAction(
- 'MOVE_TO_INBOX',
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- );
-
- expect(await readChannelState(threadId)).toMatchObject({
- channelArchivedAt: null,
- channelSnoozedUntil: null,
- });
- assertGraphQLSuccessfulResponse(
- await runInboxAction('ARCHIVE', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- );
-
- // Anyone else filing their own copy leaves the channel's alone
- assertGraphQLSuccessfulResponse(
- await runThreadMutation(
- 'reopenAgentChatThreadInChannel',
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ),
- );
- assertGraphQLSuccessfulResponse(await runInboxAction('ARCHIVE', threadId));
-
- expect((await readChannelState(threadId)).channelArchivedAt).toBeNull();
- });
-
- it('snoozes a chat for the channel until its snooze ends', async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- const pastResponse = await makeMetadataApiRequest({
- query: SNOOZE_IN_CHANNEL,
- variables: {
- threadId,
- snoozedUntil: new Date(Date.now() - 60_000).toISOString(),
- },
- });
-
- expect(pastResponse.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: SNOOZE_IN_CHANNEL,
- variables: { threadId, snoozedUntil: buildFutureSnoozedUntil() },
- }),
- );
-
- expect(
- (await findChannelThreadIds(channelId, { status: 'SNOOZED' })).threadIds,
- ).toEqual([threadId]);
- // The creator follows it, so their own copy is snoozed too
- expect(await readMemberCopy(threadId, JANE)).toMatchObject({
- snoozedUntil: expect.anything(),
- });
-
- const snoozedUntil = new Date(Date.now() - 1000);
-
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "channelSnoozedUntil" = $2 WHERE id = $1`,
- [threadId, snoozedUntil],
- );
-
- const triageService =
- getAppProviderByClassName<AgentChatThreadTriageService>(
- 'AgentChatThreadTriageService',
- );
-
- const replacedSnoozedUntil = new Date(Date.now() - 5000).toISOString();
-
- await triageService.endChannelSnooze({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- threadId,
- snoozedUntil: replacedSnoozedUntil,
- });
-
- expect((await readChannelState(threadId)).channelArchivedAt).not.toBeNull();
-
- await triageService.endChannelSnooze({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- threadId,
- snoozedUntil: snoozedUntil.toISOString(),
- });
-
- const channelState = await readChannelState(threadId);
-
- expect(channelState.channelArchivedAt).toBeNull();
- expect(channelState.channelSnoozedUntil?.getTime()).toBe(
- snoozedUntil.getTime(),
- );
- });
-
- it('moves a chat between channels and back out, starting it open', async () => {
- const { id: adminRoleId } = await findOneRoleByLabel({ label: 'Admin' });
-
- const memberRoleId = await closeMemberAllChannelsAccess();
- const sourceChannelId = await createChannel({ roleIds: [memberRoleId] });
- const destinationChannelId = await createChannel({
- roleIds: [adminRoleId],
- });
- const threadId = await createThreadInChannel(sourceChannelId);
-
- assertGraphQLSuccessfulResponse(
- await runThreadMutation('markAgentChatThreadAsDoneInChannel', threadId),
- );
-
- // Jony cannot reach the destination
- const refusedResponse = await makeMetadataApiRequest(
- {
- query: MOVE_THREAD,
- variables: { threadId, channelId: destinationChannelId },
- },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(refusedResponse.body.errors[0].extensions.code).toBe('NOT_FOUND');
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId: destinationChannelId },
- }),
- );
-
- expect(await readChannelState(threadId)).toEqual({
- channelId: destinationChannelId,
- channelArchivedAt: null,
- channelSnoozedUntil: null,
- });
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- expect(
- await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).not.toContain(threadId);
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId: null },
- }),
- );
-
- expect((await readChannelState(threadId)).channelId).toBeNull();
- expect(await readChannelGrants(threadId)).toEqual([]);
- });
-
- it('deletes a channel only once its chats have somewhere to go', async () => {
- const channelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- const refusedResponse = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId },
- });
-
- expect(refusedResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_NOT_EMPTY,
- });
-
- const selfResponse = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId: channelId },
- });
-
- expect(selfResponse.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
-
- const { hasEmittedThreadEvent } = watchThreadEvents();
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- }),
- );
-
- expect((await readChannelState(threadId)).channelId).toBe(
- destinationChannelId,
- );
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- expect((await listChannels()).map(({ id }) => id)).not.toContain(channelId);
- // Moved in SQL, so the move is sent for clients watching the chat
- expect(hasEmittedThreadEvent(threadId)).toBe(true);
- });
-
- it('refuses chats in a channel while it is being deleted', async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(null);
- const channelMetadataService = getChannelMetadataService();
- const deleteChannelMetadata = channelMetadataService.deleteChannel.bind(
- channelMetadataService,
- );
- const writeIntoChannel = jest.fn(() =>
- Promise.all([
- makeMetadataApiRequest({
- query: CREATE_THREAD,
- variables: { channelId },
- }),
- makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId },
- }),
- getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- )
- .createThreadIfMissing({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: JANE,
- threadId: randomUUID(),
- channelId,
- })
- .catch((error: unknown) => error),
- ]),
- );
-
- jest
- .spyOn(channelMetadataService, 'deleteChannel')
- .mockImplementationOnce(async (args) => {
- await writeIntoChannel();
-
- return deleteChannelMetadata(args);
- });
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId },
- }),
- );
-
- const [createResponse, moveResponse, createThreadIfMissingError] =
- await writeIntoChannel.mock.results[0].value;
-
- expect(createResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect(moveResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect(createThreadIfMissingError).toMatchObject({
- code: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect((await readChannelState(threadId)).channelId).toBeNull();
- expect(await countThreadsInChannel(channelId)).toBe(0);
- expect(await isChannelInCore(channelId)).toBe(false);
- });
-
- it('moves a chat filed into a channel just before its deletion takes the lock', async () => {
- const channelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(null);
- const queryRunner = await fileThreadIntoHeldChannel({
- threadId,
- channelId,
- });
- const advisoryLockService =
- getAppProviderByClassName<PostgresAdvisoryLockService>(
- 'PostgresAdvisoryLockService',
- );
- const tryWithLock =
- advisoryLockService.tryWithLock.bind(advisoryLockService);
-
- jest
- .spyOn(advisoryLockService, 'tryWithLock')
- .mockImplementationOnce(async (lockName, callback) => {
- await queryRunner.commitTransaction();
-
- return tryWithLock(lockName, callback);
- });
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- }),
- );
- expect((await readChannelState(threadId)).channelId).toBe(
- destinationChannelId,
- );
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- expect(await isChannelInCore(channelId)).toBe(false);
- });
-
- it('refuses to delete a channel while a chat is being filed into it', async () => {
- const channelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(null);
- const queryRunner = await fileThreadIntoHeldChannel({
- threadId,
- channelId,
- });
-
- const refusedResponse = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- });
-
- expect(refusedResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect(await isChannelInCore(channelId)).toBe(true);
-
- await queryRunner.commitTransaction();
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- }),
- );
- expect((await readChannelState(threadId)).channelId).toBe(
- destinationChannelId,
- );
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- expect(await isChannelInCore(channelId)).toBe(false);
- });
-
- it('refuses chats in a deleted channel that a stale cache still lists', async () => {
- const channelId = await createChannel();
- const threadId = await createThreadInChannel(null);
-
- await deleteChannelBehindStaleCache(channelId);
-
- const createResponse = await makeMetadataApiRequest({
- query: CREATE_THREAD,
- variables: { channelId },
- });
- const moveResponse = await makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId, channelId },
- });
-
- expect(createResponse.body.errors[0].extensions).toMatchObject({
- code: 'NOT_FOUND',
- subCode: AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
- });
- expect(moveResponse.body.errors[0].extensions).toMatchObject({
- code: 'NOT_FOUND',
- subCode: AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
- });
- expect(await countThreadsInChannel(channelId)).toBe(0);
- expect((await readChannelState(threadId)).channelId).toBeNull();
- });
-
- it('keeps chats out of a deleted destination that a stale cache still lists', async () => {
- const channelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- await deleteChannelBehindStaleCache(destinationChannelId);
-
- const deleteResponse = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- });
-
- expect(deleteResponse.body.errors[0].extensions).toMatchObject({
- code: 'NOT_FOUND',
- subCode: AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
- });
- expect(await isChannelInCore(channelId)).toBe(true);
- expect((await readChannelState(threadId)).channelId).toBe(channelId);
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: channelId },
- ]);
- });
-
- it('refuses to move chats into a channel that is being deleted', async () => {
- const channelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
-
- await holdChannelDeletionLock(destinationChannelId);
-
- const deleteResponse = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- });
-
- expect(deleteResponse.body.errors[0].extensions).toMatchObject({
- code: 'CONFLICT',
- subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
- });
- expect(await isChannelInCore(channelId)).toBe(true);
- expect((await readChannelState(threadId)).channelId).toBe(channelId);
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: channelId },
- ]);
- });
-
- it('announces the chats it moved when the channel cannot be deleted afterwards', async () => {
- const channelId = await createChannel();
- const destinationChannelId = await createChannel();
- const threadId = await createThreadInChannel(channelId);
- const { hasEmittedThreadEvent } = watchThreadEvents();
-
- jest
- .spyOn(getChannelMetadataService(), 'deleteChannel')
- .mockRejectedValueOnce(new Error('Metadata delete failed'));
-
- const deleteResponse = await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId, destinationChannelId },
- });
-
- expect(deleteResponse.body.errors).toBeDefined();
- expect((await readChannelState(threadId)).channelId).toBe(
- destinationChannelId,
- );
- expect(await readChannelGrants(threadId)).toEqual([
- { principalType: 'ROLE', sourceId: destinationChannelId },
- ]);
- expect(await isChannelInCore(channelId)).toBe(true);
- expect(hasEmittedThreadEvent(threadId)).toBe(true);
-
- await createThreadInChannel(channelId);
- });
-
- it('deletes two channels into each other without leaving a chat behind', async () => {
- const firstChannelId = await createChannel();
- const secondChannelId = await createChannel();
- const firstThreadId = await createThreadInChannel(firstChannelId);
- const secondThreadId = await createThreadInChannel(secondChannelId);
-
- const deleteResponses = await Promise.all([
- makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: {
- channelId: firstChannelId,
- destinationChannelId: secondChannelId,
- },
- }),
- makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: {
- channelId: secondChannelId,
- destinationChannelId: firstChannelId,
- },
- }),
- ]);
- const failedDeleteResponses = deleteResponses.filter(({ body }) =>
- isDefined(body.errors),
- );
-
- expect(failedDeleteResponses.length).toBeGreaterThanOrEqual(1);
- for (const { body } of failedDeleteResponses) {
- expect([
- AiExceptionCode.CHAT_CHANNEL_BUSY,
- AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
- ]).toContain(body.errors[0].extensions.subCode);
- }
- for (const threadId of [firstThreadId, secondThreadId]) {
- const { channelId } = await readChannelState(threadId);
-
- expect(isDefined(channelId) && (await isChannelInCore(channelId))).toBe(
- true,
- );
- }
- });
-
- it('pins a channel to the sidebar until the channel is deleted', async () => {
- const channelId = await createChannel();
-
- const { errors: missingChannelErrors } = await createNavigationMenuItem({
- input: { type: NavigationMenuItemType.AGENT_CHAT_CHANNEL },
- expectToFail: true,
- });
-
- expect(missingChannelErrors).toBeDefined();
-
- const { data } = await createNavigationMenuItem({
- input: {
- type: NavigationMenuItemType.AGENT_CHAT_CHANNEL,
- agentChatChannelId: channelId,
- },
- gqlFields: 'id agentChatChannelId',
- });
- const navigationMenuItemId = data.createNavigationMenuItem.id;
-
- expect(data.createNavigationMenuItem.agentChatChannelId).toBe(channelId);
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: DELETE_CHANNEL,
- variables: { channelId },
- }),
- );
-
- const { data: afterDeleteData } = await findNavigationMenuItems({
- input: undefined,
- gqlFields: 'id',
- });
-
- expect(
- afterDeleteData.navigationMenuItems.map(({ id }) => id),
- ).not.toContain(navigationMenuItemId);
- });
-
- it('counts open chats for each channel the member reaches, and their own only once they follow', async () => {
- const channelId = await createChannel();
- const janeOpenThreadCount = await getOpenThreadCount();
- const jonyOpenThreadCount = await getOpenThreadCount(
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const threadId = await createThreadInChannel(channelId);
- const doneThreadId = await createThreadInChannel(channelId);
-
- assertGraphQLSuccessfulResponse(
- await runThreadMutation(
- 'markAgentChatThreadAsDoneInChannel',
- doneThreadId,
- ),
- );
- await simulateNewMessageActivity(threadId);
-
- for (const token of [
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- ]) {
- expect(
- (await getChannelSummaries(token)).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- openCount: 1,
- assignedToMeCount: 0,
- snoozedCount: 0,
- doneCount: 1,
- hasUnreadOpen: true,
- hasUnreadAssignedToMe: false,
- });
- }
-
- // Jane follows both chats she started, so filing one for the channel
- // files her own copy too
- expect(await getOpenThreadCount()).toBe(janeOpenThreadCount + 1);
- expect(await getOpenThreadCount(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toBe(
- jonyOpenThreadCount,
- );
- });
-
- it('counts each channel status and unread open chats assigned to the requesting member', async () => {
- const channelId = await createChannel();
-
- expect(
- (await getChannelSummaries()).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- openCount: 0,
- assignedToMeCount: 0,
- snoozedCount: 0,
- doneCount: 0,
- hasUnreadOpen: false,
- hasUnreadAssignedToMe: false,
- });
-
- const threadId = await createThreadInChannel(channelId);
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: ASSIGN,
- variables: { threadId, assigneeWorkspaceMemberId: JONY },
- }),
- );
- await simulateNewMessageActivity(threadId);
-
- expect(
- (await getChannelSummaries()).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toMatchObject({
- openCount: 1,
- assignedToMeCount: 0,
- hasUnreadAssignedToMe: false,
- });
- expect(
- (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- openCount: 1,
- assignedToMeCount: 1,
- snoozedCount: 0,
- doneCount: 0,
- hasUnreadOpen: true,
- hasUnreadAssignedToMe: true,
- });
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: SNOOZE_IN_CHANNEL,
- variables: { threadId, snoozedUntil: buildFutureSnoozedUntil() },
- }),
- );
-
- expect(
- (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- openCount: 0,
- assignedToMeCount: 0,
- snoozedCount: 1,
- doneCount: 0,
- hasUnreadOpen: false,
- hasUnreadAssignedToMe: false,
- });
-
- assertGraphQLSuccessfulResponse(
- await runThreadMutation('markAgentChatThreadAsDoneInChannel', threadId),
- );
-
- expect(
- (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
- (summary) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- openCount: 0,
- assignedToMeCount: 0,
- snoozedCount: 0,
- doneCount: 1,
- hasUnreadOpen: false,
- hasUnreadAssignedToMe: false,
- });
- });
-
- it('narrows open channel chats to those waiting on an answer or mentioning the member', async () => {
- const channelId = await createChannel();
- const needsInputThreadId = await createThreadInChannel(channelId);
- const mentionedThreadId = await createThreadInChannel(channelId);
-
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "pendingQuestionMessageId" = $1 WHERE id = $2`,
- [randomUUID(), needsInputThreadId],
- );
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThreadParticipant" SET "lastMentionedAt" = now()
- WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
- [mentionedThreadId, JANE],
- );
-
- expect(
- (await findChannelThreadIds(channelId, { filter: 'NEEDS_INPUT' }))
- .threadIds,
- ).toEqual([needsInputThreadId]);
- expect(
- (await findChannelThreadIds(channelId, { filter: 'MENTIONED' }))
- .threadIds,
- ).toEqual([mentionedThreadId]);
- expect(
- (
- await findChannelThreadIds(
- channelId,
- { filter: 'MENTIONED' },
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- )
- ).threadIds,
- ).toEqual([]);
-
- const response = await makeMetadataApiRequest({
- query: parse(
- `query Summaries { agentChatChannelSummaries { channelId needsInputCount mentionedCount assignedCount unassignedCount } }`,
- ),
- });
-
- assertGraphQLSuccessfulResponse(response);
- expect(
- response.body.data.agentChatChannelSummaries.find(
- (summary: { channelId: string }) => summary.channelId === channelId,
- ),
- ).toEqual({
- channelId,
- needsInputCount: 1,
- mentionedCount: 1,
- assignedCount: 0,
- unassignedCount: 2,
- });
- });
-
- it('narrows open channel chats to assigned ones and keeps resolved mentions out', async () => {
- const channelId = await createChannel();
- const assignedThreadId = await createThreadInChannel(channelId);
- const unassignedThreadId = await createThreadInChannel(channelId);
-
- assertGraphQLSuccessfulResponse(
- await makeMetadataApiRequest({
- query: ASSIGN,
- variables: {
- threadId: assignedThreadId,
- assigneeWorkspaceMemberId: JONY,
- },
- }),
- );
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThreadParticipant"
- SET "lastMentionedAt" = now(), "mentionsResolvedAt" = now()
- WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
- [unassignedThreadId, JANE],
- );
-
- expect(
- (await findChannelThreadIds(channelId, { assignment: 'ASSIGNED' }))
- .threadIds,
- ).toEqual([assignedThreadId]);
- expect(
- (await findChannelThreadIds(channelId, { assignment: 'UNASSIGNED' }))
- .threadIds,
- ).toEqual([unassignedThreadId]);
- expect(
- (await findChannelThreadIds(channelId, { filter: 'MENTIONED' }))
- .threadIds,
- ).toEqual([]);
- });
-
- it('keeps the channel chats of a removed member in their channel', async () => {
- const channelId = await createChannel();
- const channelThreadId = await createThreadInChannel(
- channelId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const ownThreadId = await createThreadInChannel(
- null,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const { flatFieldMetadataMaps } =
- await getAppProviderByClassName<WorkspaceCacheService>(
- 'WorkspaceCacheService',
- ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, ['flatFieldMetadataMaps']);
-
- await detachAgentChatChannelThreadsFromWorkspaceMember({
- threadRepository: global.app.get<
- string,
- AgentHistoryRepository<AgentChatThreadWorkspaceEntity>
- >(getAgentHistoryRepositoryToken('agentChatThread'), { strict: false }),
- flatFieldMetadataMaps,
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: JONY,
- });
-
- const owners: { id: string; workspaceMemberId: string | null }[] =
- await global.testDataSource.query(
- `SELECT id, "workspaceMemberId" FROM ${SCHEMA}."agentChatThread"
- WHERE id = ANY($1::uuid[]) ORDER BY id`,
- [[channelThreadId, ownThreadId]],
- );
-
- expect(owners).toEqual(
- [
- { id: channelThreadId, workspaceMemberId: null },
- { id: ownThreadId, workspaceMemberId: JONY },
- ].sort((threadA, threadB) => threadA.id.localeCompare(threadB.id)),
- );
-
- const leaveResponse = await makeMetadataApiRequest({
- query: MOVE_THREAD,
- variables: { threadId: channelThreadId, channelId: null },
- });
-
- expect(leaveResponse.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
-
- // Neither chat is Jane's to destroy any more
- await global.testDataSource.query(
- `DELETE FROM ${SCHEMA}."agentChatThread" WHERE id = ANY($1::uuid[])`,
- [[channelThreadId, ownThreadId]],
- );
- createdThreadIds.splice(
- 0,
- createdThreadIds.length,
- ...createdThreadIds.filter(
- (threadId) => ![channelThreadId, ownThreadId].includes(threadId),
- ),
- );
- });
-
- it('pages a channel by last activity', async () => {
- const channelId = await createChannel();
- const olderThreadId = await createThreadInChannel(channelId);
- const newerThreadId = await createThreadInChannel(channelId);
-
- await simulateNewMessageActivity(newerThreadId);
-
- const firstPage = await findChannelThreadIds(
- channelId,
- {},
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- { first: 1 },
- );
-
- expect(firstPage).toMatchObject({
- threadIds: [newerThreadId],
- hasNextPage: true,
- });
-
- const secondPage = await findChannelThreadIds(
- channelId,
- {},
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- { first: 1, after: firstPage.endCursor! },
- );
-
- expect(secondPage).toMatchObject({
- threadIds: [olderThreadId],
- hasNextPage: false,
- });
-
- const invalidResponse = await makeMetadataApiRequest({
- query: CHANNEL_THREAD_IDS,
- variables: { channelId, after: 'not-a-cursor' },
- });
-
- expect(invalidResponse.body.errors[0].extensions.code).toBe(
- 'BAD_USER_INPUT',
- );
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-channel/chat-channel-access-and-triage.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-channel/chat-channel-access-and-triage.integration-spec.ts
new file mode 100644
index 00000000000..a05c66be797
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-channel/chat-channel-access-and-triage.integration-spec.ts
@@ -0,0 +1,863 @@
+import { randomUUID } from 'node:crypto';
+import { assertGraphQLSuccessfulResponse } from 'test/integration/graphql/utils/graphql-test-assertions.util';
+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { listChatThreadIds } from 'test/integration/utils/list-chat-thread-ids.util';
+import { type AgentChatThreadTriageService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-triage.service';
+import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import {
+ setUpChatChannelTests,
+ SCHEMA,
+ CREATE_CHANNEL,
+ DELETE_CHANNEL,
+ CHANNEL_ROLES,
+ CREATE_THREAD,
+ MOVE_THREAD,
+ SNOOZE_IN_CHANNEL,
+ ASSIGN,
+ CHANNEL_THREAD_IDS,
+ buildFutureSnoozedUntil,
+ runThreadMutation,
+ runInboxAction,
+ findChannelThreadIds,
+ getChannelSummaries,
+ getOpenThreadCount,
+ readMemberCopy,
+ readChannelState,
+ listChannels,
+ readChannelGrants,
+ readChannelGrantRoleIds,
+ setRoleAllChannelsAccess,
+ waitForChannelGrantRewrites,
+ getChannelGrantService,
+ waitForBlockedChannelGrantLock,
+ countThreadsInChannel,
+ insertChannelGrant,
+ simulateNewMessageActivity,
+} from 'test/integration/graphql/suites/chat-channel/utils/chat-channel-test.util';
+
+const { JANE, JONY } = WORKSPACE_MEMBER_DATA_SEED_IDS;
+
+describe('Chat channel access and triage through the authenticated API', () => {
+ const {
+ createdThreadIds,
+ createChannel,
+ updateChannel,
+ createThreadInChannel,
+ roleIdsToReopenToAllChannels,
+ markChannelCacheStale,
+ holdChannelGrantLock,
+ closeMemberAllChannelsAccess,
+ } = setUpChatChannelTests();
+
+ it('creates a channel under a trimmed name, after General', async () => {
+ const channelId = await createChannel();
+
+ const [channel]: { name: string }[] = await global.testDataSource.query(
+ `SELECT name FROM core."agentChatChannel" WHERE id = $1`,
+ [channelId],
+ );
+
+ expect(channel.name.startsWith('Channel ')).toBe(true);
+ expect(channel.name.endsWith(' ')).toBe(false);
+
+ const channels = await listChannels(APPLE_JONY_MEMBER_ACCESS_TOKEN);
+
+ const createdChannel = channels[channels.length - 1];
+
+ expect(channels[0]).toMatchObject({ name: 'General', isCustom: false });
+ expect(createdChannel).toMatchObject({
+ id: channelId,
+ isCustom: true,
+ isAccessible: true,
+ });
+ expect(createdChannel.applicationId).not.toBe(channels[0].applicationId);
+ });
+
+ it('refuses a channel without a name, or with the name of another one', async () => {
+ const response = await makeMetadataApiRequest({
+ query: CREATE_CHANNEL,
+ variables: { input: { name: ' ' } },
+ });
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+
+ const duplicateResponse = await makeMetadataApiRequest({
+ query: CREATE_CHANNEL,
+ variables: { input: { name: 'General' } },
+ });
+
+ expect(duplicateResponse.body.errors[0].extensions.code).toBe(
+ 'METADATA_VALIDATION_FAILED',
+ );
+ });
+
+ it('leaves setting channels up to who manages AI settings', async () => {
+ const channelId = await createChannel();
+
+ const createResponse = await makeMetadataApiRequest(
+ { query: CREATE_CHANNEL, variables: { input: { name: 'By a member' } } },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const updateResponse = await updateChannel(
+ channelId,
+ { name: 'Renamed by a member' },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const deleteResponse = await makeMetadataApiRequest(
+ { query: DELETE_CHANNEL, variables: { channelId } },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const rolesResponse = await makeMetadataApiRequest(
+ { query: CHANNEL_ROLES },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ for (const response of [
+ createResponse,
+ updateResponse,
+ deleteResponse,
+ rolesResponse,
+ ]) {
+ expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');
+ }
+ });
+
+ it('keeps General and its chats, as the standard sync would bring it back', async () => {
+ const [general] = await listChannels();
+
+ expect(general).toMatchObject({ name: 'General' });
+
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(general.id);
+
+ const response = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId: general.id, destinationChannelId },
+ });
+
+ expect(response.body.errors[0].extensions.code).toBe('FORBIDDEN');
+ expect((await readChannelState(threadId)).channelId).toBe(general.id);
+ });
+
+ it('lets the roles with access to all channels read and reply in its chats', async () => {
+ const { id: adminRoleId } = await findOneRoleByLabel({ label: 'Admin' });
+ const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: channelId },
+ ]);
+ expect(await readChannelGrantRoleIds(threadId)).toEqual(
+ expect.arrayContaining([adminRoleId, memberRoleId]),
+ );
+ expect(await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toContain(
+ threadId,
+ );
+ expect(
+ (
+ await findChannelThreadIds(
+ channelId,
+ {},
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ )
+ ).threadIds,
+ ).toEqual([threadId]);
+
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction(
+ 'SUBSCRIBE',
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ );
+ });
+
+ it('keeps a channel open to roles, and its chats, to who holds them', async () => {
+ const { id: adminRoleId } = await findOneRoleByLabel({ label: 'Admin' });
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const channelId = await createChannel({ roleIds: [adminRoleId] });
+ const threadId = await createThreadInChannel(channelId);
+
+ expect(
+ await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).not.toContain(threadId);
+ expect(
+ (await listChannels(APPLE_JONY_MEMBER_ACCESS_TOKEN)).map(({ id }) => id),
+ ).not.toContain(channelId);
+
+ for (const response of [
+ await makeMetadataApiRequest(
+ { query: CHANNEL_THREAD_IDS, variables: { channelId } },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ await makeMetadataApiRequest(
+ { query: CREATE_THREAD, variables: { channelId } },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ ]) {
+ expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
+ }
+
+ const openResponse = await updateChannel(channelId, {
+ roleIds: [adminRoleId, memberRoleId],
+ });
+
+ assertGraphQLSuccessfulResponse(openResponse);
+ expect(
+ [...openResponse.body.data.updateAgentChatChannel.roleIds].sort(),
+ ).toEqual([adminRoleId, memberRoleId].sort());
+ expect(await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toContain(
+ threadId,
+ );
+ expect(
+ (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ openCount: 1,
+ assignedToMeCount: 0,
+ snoozedCount: 0,
+ doneCount: 0,
+ hasUnreadOpen: true,
+ hasUnreadAssignedToMe: false,
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await updateChannel(channelId, { roleIds: [adminRoleId] }),
+ );
+
+ expect(
+ await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).not.toContain(threadId);
+ expect(
+ (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).map(
+ (summary) => summary.channelId,
+ ),
+ ).not.toContain(channelId);
+ });
+
+ it('opens every channel to a role given access to all channels, and back', async () => {
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ await expectEventually(async () =>
+ expect(
+ await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).not.toContain(threadId),
+ );
+
+ await setRoleAllChannelsAccess(memberRoleId, true);
+
+ await expectEventually(async () =>
+ expect(await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toContain(
+ threadId,
+ ),
+ );
+ expect(
+ (await listChannels(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
+ ({ id }) => id === channelId,
+ ),
+ ).toMatchObject({ isAccessible: true });
+
+ await setRoleAllChannelsAccess(memberRoleId, false);
+
+ await expectEventually(async () =>
+ expect(
+ await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).not.toContain(threadId),
+ );
+ });
+
+ it('removes a role taken off a channel from a chat filed into it meanwhile', async () => {
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const channelId = await createChannel({ roleIds: [memberRoleId] });
+ const threadId = await createThreadInChannel(null);
+ const queryRunner = await holdChannelGrantLock({
+ channelId,
+ mode: 'shared',
+ });
+
+ await queryRunner.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "channelId" = $1 WHERE id = $2`,
+ [channelId, threadId],
+ );
+ await insertChannelGrant({
+ queryRunner,
+ threadId,
+ roleId: memberRoleId,
+ channelId,
+ });
+
+ const pendingUpdateResponse = Promise.resolve(
+ updateChannel(channelId, { roleIds: [] }),
+ );
+
+ await waitForBlockedChannelGrantLock(channelId);
+ await queryRunner.commitTransaction();
+
+ assertGraphQLSuccessfulResponse(await pendingUpdateResponse);
+ expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
+ });
+
+ it('grants a chat created in a channel the roles the channel has once it may write them', async () => {
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const channelId = await createChannel({ roleIds: [memberRoleId] });
+ const queryRunner = await holdChannelGrantLock({
+ channelId,
+ mode: 'exclusive',
+ });
+
+ await queryRunner.query(
+ `DELETE FROM core."agentChatChannelRole" WHERE "channelId" = $1 AND "roleId" = $2`,
+ [channelId, memberRoleId],
+ );
+ markChannelCacheStale();
+
+ const pendingCreateResponse = Promise.resolve(
+ makeMetadataApiRequest({
+ query: CREATE_THREAD,
+ variables: { channelId },
+ }),
+ );
+
+ await waitForBlockedChannelGrantLock(channelId);
+ await queryRunner.commitTransaction();
+
+ const createResponse = await pendingCreateResponse;
+
+ assertGraphQLSuccessfulResponse(createResponse);
+
+ const threadId = createResponse.body.data.createChatThread.id;
+
+ createdThreadIds.push(threadId);
+
+ expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: channelId },
+ ]);
+ });
+
+ it('drops the roles of the channel a chat leaves while that channel is rewritten', async () => {
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const sourceChannelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(sourceChannelId);
+ const queryRunner = await holdChannelGrantLock({
+ channelId: sourceChannelId,
+ mode: 'exclusive',
+ });
+
+ const pendingMoveResponse = Promise.resolve(
+ makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId: destinationChannelId },
+ }),
+ );
+
+ await waitForBlockedChannelGrantLock(sourceChannelId);
+ await insertChannelGrant({
+ queryRunner,
+ threadId,
+ roleId: memberRoleId,
+ channelId: sourceChannelId,
+ });
+ await queryRunner.commitTransaction();
+
+ assertGraphQLSuccessfulResponse(await pendingMoveResponse);
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
+ });
+
+ it("makes a chat moved into a channel wait for that channel's rewrite", async () => {
+ const sourceChannelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(sourceChannelId);
+ const queryRunner = await holdChannelGrantLock({
+ channelId: destinationChannelId,
+ mode: 'exclusive',
+ });
+
+ const pendingMoveResponse = Promise.resolve(
+ makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId: destinationChannelId },
+ }),
+ );
+
+ await waitForBlockedChannelGrantLock(destinationChannelId);
+ await queryRunner.commitTransaction();
+
+ assertGraphQLSuccessfulResponse(await pendingMoveResponse);
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ });
+
+ it("removes a role's access to all channels from a chat filed under the old access", async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(null);
+ const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
+ const queryRunner = await holdChannelGrantLock({
+ channelId,
+ mode: 'shared',
+ });
+
+ await queryRunner.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "channelId" = $1 WHERE id = $2`,
+ [channelId, threadId],
+ );
+ await insertChannelGrant({
+ queryRunner,
+ threadId,
+ roleId: memberRoleId,
+ channelId,
+ });
+
+ roleIdsToReopenToAllChannels.add(memberRoleId);
+ await setRoleAllChannelsAccess(memberRoleId, false);
+
+ await waitForBlockedChannelGrantLock(channelId);
+ await queryRunner.commitTransaction();
+ await waitForChannelGrantRewrites();
+
+ expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
+ });
+
+ it('refuses chats filed into a channel whose grants stay locked too long', async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(null);
+
+ await holdChannelGrantLock({ channelId, mode: 'exclusive' });
+
+ const [createResponse, moveResponse] = await Promise.all([
+ makeMetadataApiRequest({
+ query: CREATE_THREAD,
+ variables: { channelId },
+ }),
+ makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId },
+ }),
+ ]);
+
+ expect(createResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect(moveResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect((await readChannelState(threadId)).channelId).toBeNull();
+ expect(await countThreadsInChannel(channelId)).toBe(0);
+ });
+
+ it("removes a role's access to all channels once a failed rewrite is retried", async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+ const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
+
+ expect(await readChannelGrantRoleIds(threadId)).toContain(memberRoleId);
+
+ const rewriteAllChannelGrants = jest
+ .spyOn(getChannelGrantService(), 'rewriteAllChannelGrants')
+ .mockRejectedValueOnce(new Error('Grant rewrite failed'));
+
+ roleIdsToReopenToAllChannels.add(memberRoleId);
+ await setRoleAllChannelsAccess(memberRoleId, false);
+ await waitForChannelGrantRewrites();
+
+ expect(rewriteAllChannelGrants).toHaveBeenCalledTimes(2);
+ expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
+ });
+
+ it("applies a channel's new access once a failed rewrite is retried", async () => {
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const channelId = await createChannel({ roleIds: [memberRoleId] });
+ const threadId = await createThreadInChannel(channelId);
+
+ expect(await readChannelGrantRoleIds(threadId)).toContain(memberRoleId);
+
+ jest
+ .spyOn(getChannelGrantService(), 'rewriteChannelGrants')
+ .mockRejectedValueOnce(new Error('Grant rewrite failed'));
+
+ const response = await updateChannel(channelId, { roleIds: [] });
+
+ expect(response.body.errors).toBeDefined();
+
+ await waitForChannelGrantRewrites();
+
+ expect(await readChannelGrantRoleIds(threadId)).not.toContain(memberRoleId);
+ });
+
+ it("restores a channel's grants when its unchanged access is saved again", async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ await global.testDataSource.query(
+ `DELETE FROM ${SCHEMA}."recordShare" WHERE "recordId" = $1 AND "rowCause" = 'RULE'`,
+ [threadId],
+ );
+
+ assertGraphQLSuccessfulResponse(
+ await updateChannel(channelId, { roleIds: [] }),
+ );
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: channelId },
+ ]);
+ });
+
+ it("creates a chat under a destroyed chat's id while its channel is rewritten", async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ createdThreadIds.splice(createdThreadIds.indexOf(threadId), 1);
+ await destroyAgentChatThread({ threadId });
+
+ const queryRunner = await holdChannelGrantLock({
+ channelId,
+ mode: 'exclusive',
+ });
+
+ const pendingCreate = getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ).createThreadIfMissing({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: JANE,
+ threadId,
+ channelId,
+ });
+
+ await waitForBlockedChannelGrantLock(channelId);
+ await queryRunner.query(
+ `DELETE FROM ${SCHEMA}."recordShare" WHERE "rowCause" = 'RULE' AND "sourceId" = $1`,
+ [channelId],
+ );
+ await queryRunner.commitTransaction();
+ await pendingCreate;
+ createdThreadIds.push(threadId);
+
+ expect((await readChannelState(threadId)).channelId).toBe(channelId);
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: channelId },
+ ]);
+ });
+
+ it('refuses a role from outside the workspace', async () => {
+ const response = await makeMetadataApiRequest({
+ query: CREATE_CHANNEL,
+ variables: {
+ input: {
+ name: 'Channel with an unknown role',
+ roleIds: [randomUUID()],
+ },
+ },
+ });
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+ });
+
+ it('keeps chats a member only reads in a channel out of their own inbox', async () => {
+ const channelId = await createChannel();
+ const jonyOpenThreadCount = await getOpenThreadCount(
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const threadId = await createThreadInChannel(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction('READ', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ );
+
+ expect(await readMemberCopy(threadId, JONY)).toMatchObject({
+ isSubscribed: false,
+ });
+ expect(await getOpenThreadCount(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toBe(
+ jonyOpenThreadCount,
+ );
+
+ // Filing it follows it, so new activity brings it back to his inbox
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction('ARCHIVE', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ );
+
+ expect(await readMemberCopy(threadId, JONY)).toMatchObject({
+ isSubscribed: true,
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction(
+ 'MOVE_TO_INBOX',
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ );
+
+ expect(await getOpenThreadCount(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toBe(
+ jonyOpenThreadCount + 1,
+ );
+ // The creator follows the chat they started
+ expect(await readMemberCopy(threadId, JANE)).toMatchObject({
+ isSubscribed: true,
+ archivedAt: null,
+ });
+ });
+
+ it('files a chat for the channel, and for whoever files it if they follow it', async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation(
+ 'markAgentChatThreadAsDoneInChannel',
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ );
+
+ expect(
+ (await findChannelThreadIds(channelId, { status: 'DONE' })).threadIds,
+ ).toEqual([threadId]);
+ expect(
+ (await findChannelThreadIds(channelId, { status: 'OPEN' })).threadIds,
+ ).toEqual([]);
+ // Jane follows it but did not file it, so it stays open for her
+ expect((await readMemberCopy(threadId, JANE))?.archivedAt).toBeNull();
+ // Jony did not follow it, so filing it for the channel leaves him out
+ expect(
+ (await readMemberCopy(threadId, JONY))?.archivedAt ?? null,
+ ).toBeNull();
+
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation('reopenAgentChatThreadInChannel', threadId),
+ );
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation('markAgentChatThreadAsDoneInChannel', threadId),
+ );
+
+ expect(await readMemberCopy(threadId, JANE)).toMatchObject({
+ archivedAt: expect.anything(),
+ });
+
+ await simulateNewMessageActivity(threadId);
+
+ expect(
+ (await findChannelThreadIds(channelId, { status: 'OPEN' })).threadIds,
+ ).toEqual([threadId]);
+ });
+
+ it('refuses channel triage on a chat outside any channel', async () => {
+ const threadId = await createThreadInChannel(null);
+ const response = await runThreadMutation(
+ 'markAgentChatThreadAsDoneInChannel',
+ threadId,
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+ });
+
+ it("files the channel's copy when the assignee files their own", async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: ASSIGN,
+ variables: { threadId, assigneeWorkspaceMemberId: JONY },
+ }),
+ );
+
+ expect(
+ (await findChannelThreadIds(channelId, { assignment: 'UNASSIGNED' }))
+ .threadIds,
+ ).toEqual([]);
+ expect(
+ (
+ await findChannelThreadIds(
+ channelId,
+ { assignment: 'ASSIGNED_TO_ME' },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ )
+ ).threadIds,
+ ).toEqual([threadId]);
+
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction('ARCHIVE', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ );
+
+ expect((await readChannelState(threadId)).channelArchivedAt).not.toBeNull();
+
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction(
+ 'SNOOZE',
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ buildFutureSnoozedUntil(),
+ ),
+ );
+
+ expect(
+ (await readChannelState(threadId)).channelSnoozedUntil,
+ ).not.toBeNull();
+
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction(
+ 'MOVE_TO_INBOX',
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ );
+
+ expect(await readChannelState(threadId)).toMatchObject({
+ channelArchivedAt: null,
+ channelSnoozedUntil: null,
+ });
+ assertGraphQLSuccessfulResponse(
+ await runInboxAction('ARCHIVE', threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ );
+
+ // Anyone else filing their own copy leaves the channel's alone
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation(
+ 'reopenAgentChatThreadInChannel',
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ),
+ );
+ assertGraphQLSuccessfulResponse(await runInboxAction('ARCHIVE', threadId));
+
+ expect((await readChannelState(threadId)).channelArchivedAt).toBeNull();
+ });
+
+ it('snoozes a chat for the channel until its snooze ends', async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ const pastResponse = await makeMetadataApiRequest({
+ query: SNOOZE_IN_CHANNEL,
+ variables: {
+ threadId,
+ snoozedUntil: new Date(Date.now() - 60_000).toISOString(),
+ },
+ });
+
+ expect(pastResponse.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: SNOOZE_IN_CHANNEL,
+ variables: { threadId, snoozedUntil: buildFutureSnoozedUntil() },
+ }),
+ );
+
+ expect(
+ (await findChannelThreadIds(channelId, { status: 'SNOOZED' })).threadIds,
+ ).toEqual([threadId]);
+ // The creator follows it, so their own copy is snoozed too
+ expect(await readMemberCopy(threadId, JANE)).toMatchObject({
+ snoozedUntil: expect.anything(),
+ });
+
+ const snoozedUntil = new Date(Date.now() - 1000);
+
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "channelSnoozedUntil" = $2 WHERE id = $1`,
+ [threadId, snoozedUntil],
+ );
+
+ const triageService =
+ getAppProviderByClassName<AgentChatThreadTriageService>(
+ 'AgentChatThreadTriageService',
+ );
+
+ const replacedSnoozedUntil = new Date(Date.now() - 5000).toISOString();
+
+ await triageService.endChannelSnooze({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ threadId,
+ snoozedUntil: replacedSnoozedUntil,
+ });
+
+ expect((await readChannelState(threadId)).channelArchivedAt).not.toBeNull();
+
+ await triageService.endChannelSnooze({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ threadId,
+ snoozedUntil: snoozedUntil.toISOString(),
+ });
+
+ const channelState = await readChannelState(threadId);
+
+ expect(channelState.channelArchivedAt).toBeNull();
+ expect(channelState.channelSnoozedUntil?.getTime()).toBe(
+ snoozedUntil.getTime(),
+ );
+ });
+
+ it('moves a chat between channels and back out, starting it open', async () => {
+ const { id: adminRoleId } = await findOneRoleByLabel({ label: 'Admin' });
+
+ const memberRoleId = await closeMemberAllChannelsAccess();
+ const sourceChannelId = await createChannel({ roleIds: [memberRoleId] });
+ const destinationChannelId = await createChannel({
+ roleIds: [adminRoleId],
+ });
+ const threadId = await createThreadInChannel(sourceChannelId);
+
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation('markAgentChatThreadAsDoneInChannel', threadId),
+ );
+
+ // Jony cannot reach the destination
+ const refusedResponse = await makeMetadataApiRequest(
+ {
+ query: MOVE_THREAD,
+ variables: { threadId, channelId: destinationChannelId },
+ },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(refusedResponse.body.errors[0].extensions.code).toBe('NOT_FOUND');
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId: destinationChannelId },
+ }),
+ );
+
+ expect(await readChannelState(threadId)).toEqual({
+ channelId: destinationChannelId,
+ channelArchivedAt: null,
+ channelSnoozedUntil: null,
+ });
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ expect(
+ await listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).not.toContain(threadId);
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId: null },
+ }),
+ );
+
+ expect((await readChannelState(threadId)).channelId).toBeNull();
+ expect(await readChannelGrants(threadId)).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-channel/chat-channel-deletion-and-summaries.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-channel/chat-channel-deletion-and-summaries.integration-spec.ts
new file mode 100644
index 00000000000..52140a9a99f
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-channel/chat-channel-deletion-and-summaries.integration-spec.ts
@@ -0,0 +1,740 @@
+import { randomUUID } from 'node:crypto';
+import { parse } from 'graphql';
+import { NavigationMenuItemType } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { assertGraphQLSuccessfulResponse } from 'test/integration/graphql/utils/graphql-test-assertions.util';
+import { createNavigationMenuItem } from 'test/integration/metadata/suites/navigation-menu-item/utils/create-navigation-menu-item.util';
+import { findNavigationMenuItems } from 'test/integration/metadata/suites/navigation-menu-item/utils/find-navigation-menu-items.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type PostgresAdvisoryLockService } from 'src/database/typeorm/postgres-advisory-lock.service';
+import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { detachAgentChatChannelThreadsFromWorkspaceMember } from 'src/engine/metadata-modules/ai/ai-chat/utils/detach-agent-chat-channel-threads-from-workspace-member.util';
+import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { getAgentHistoryRepositoryToken } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import {
+ setUpChatChannelTests,
+ SCHEMA,
+ DELETE_CHANNEL,
+ CREATE_THREAD,
+ MOVE_THREAD,
+ SNOOZE_IN_CHANNEL,
+ ASSIGN,
+ CHANNEL_THREAD_IDS,
+ buildFutureSnoozedUntil,
+ runThreadMutation,
+ findChannelThreadIds,
+ getChannelSummaries,
+ getOpenThreadCount,
+ readChannelState,
+ listChannels,
+ readChannelGrants,
+ isChannelInCore,
+ countThreadsInChannel,
+ watchThreadEvents,
+ getChannelMetadataService,
+ deleteChannelBehindStaleCache,
+ simulateNewMessageActivity,
+} from 'test/integration/graphql/suites/chat-channel/utils/chat-channel-test.util';
+
+const { JANE, JONY } = WORKSPACE_MEMBER_DATA_SEED_IDS;
+
+describe('Chat channel deletion and summaries through the authenticated API', () => {
+ const {
+ createdThreadIds,
+ createChannel,
+ createThreadInChannel,
+ holdChannelDeletionLock,
+ fileThreadIntoHeldChannel,
+ } = setUpChatChannelTests();
+
+ it('deletes a channel only once its chats have somewhere to go', async () => {
+ const channelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ const refusedResponse = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId },
+ });
+
+ expect(refusedResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_NOT_EMPTY,
+ });
+
+ const selfResponse = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId: channelId },
+ });
+
+ expect(selfResponse.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+
+ const { hasEmittedThreadEvent } = watchThreadEvents();
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ }),
+ );
+
+ expect((await readChannelState(threadId)).channelId).toBe(
+ destinationChannelId,
+ );
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ expect((await listChannels()).map(({ id }) => id)).not.toContain(channelId);
+ // Moved in SQL, so the move is sent for clients watching the chat
+ expect(hasEmittedThreadEvent(threadId)).toBe(true);
+ });
+
+ it('refuses chats in a channel while it is being deleted', async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(null);
+ const channelMetadataService = getChannelMetadataService();
+ const deleteChannelMetadata = channelMetadataService.deleteChannel.bind(
+ channelMetadataService,
+ );
+ const writeIntoChannel = jest.fn(() =>
+ Promise.all([
+ makeMetadataApiRequest({
+ query: CREATE_THREAD,
+ variables: { channelId },
+ }),
+ makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId },
+ }),
+ getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ )
+ .createThreadIfMissing({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: JANE,
+ threadId: randomUUID(),
+ channelId,
+ })
+ .catch((error: unknown) => error),
+ ]),
+ );
+
+ jest
+ .spyOn(channelMetadataService, 'deleteChannel')
+ .mockImplementationOnce(async (args) => {
+ await writeIntoChannel();
+
+ return deleteChannelMetadata(args);
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId },
+ }),
+ );
+
+ const [createResponse, moveResponse, createThreadIfMissingError] =
+ await writeIntoChannel.mock.results[0].value;
+
+ expect(createResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect(moveResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect(createThreadIfMissingError).toMatchObject({
+ code: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect((await readChannelState(threadId)).channelId).toBeNull();
+ expect(await countThreadsInChannel(channelId)).toBe(0);
+ expect(await isChannelInCore(channelId)).toBe(false);
+ });
+
+ it('moves a chat filed into a channel just before its deletion takes the lock', async () => {
+ const channelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(null);
+ const queryRunner = await fileThreadIntoHeldChannel({
+ threadId,
+ channelId,
+ });
+ const advisoryLockService =
+ getAppProviderByClassName<PostgresAdvisoryLockService>(
+ 'PostgresAdvisoryLockService',
+ );
+ const tryWithLock =
+ advisoryLockService.tryWithLock.bind(advisoryLockService);
+
+ jest
+ .spyOn(advisoryLockService, 'tryWithLock')
+ .mockImplementationOnce(async (lockName, callback) => {
+ await queryRunner.commitTransaction();
+
+ return tryWithLock(lockName, callback);
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ }),
+ );
+ expect((await readChannelState(threadId)).channelId).toBe(
+ destinationChannelId,
+ );
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ expect(await isChannelInCore(channelId)).toBe(false);
+ });
+
+ it('refuses to delete a channel while a chat is being filed into it', async () => {
+ const channelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(null);
+ const queryRunner = await fileThreadIntoHeldChannel({
+ threadId,
+ channelId,
+ });
+
+ const refusedResponse = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ });
+
+ expect(refusedResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect(await isChannelInCore(channelId)).toBe(true);
+
+ await queryRunner.commitTransaction();
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ }),
+ );
+ expect((await readChannelState(threadId)).channelId).toBe(
+ destinationChannelId,
+ );
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ expect(await isChannelInCore(channelId)).toBe(false);
+ });
+
+ it('refuses chats in a deleted channel that a stale cache still lists', async () => {
+ const channelId = await createChannel();
+ const threadId = await createThreadInChannel(null);
+
+ await deleteChannelBehindStaleCache(channelId);
+
+ const createResponse = await makeMetadataApiRequest({
+ query: CREATE_THREAD,
+ variables: { channelId },
+ });
+ const moveResponse = await makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId, channelId },
+ });
+
+ expect(createResponse.body.errors[0].extensions).toMatchObject({
+ code: 'NOT_FOUND',
+ subCode: AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
+ });
+ expect(moveResponse.body.errors[0].extensions).toMatchObject({
+ code: 'NOT_FOUND',
+ subCode: AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
+ });
+ expect(await countThreadsInChannel(channelId)).toBe(0);
+ expect((await readChannelState(threadId)).channelId).toBeNull();
+ });
+
+ it('keeps chats out of a deleted destination that a stale cache still lists', async () => {
+ const channelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ await deleteChannelBehindStaleCache(destinationChannelId);
+
+ const deleteResponse = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ });
+
+ expect(deleteResponse.body.errors[0].extensions).toMatchObject({
+ code: 'NOT_FOUND',
+ subCode: AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
+ });
+ expect(await isChannelInCore(channelId)).toBe(true);
+ expect((await readChannelState(threadId)).channelId).toBe(channelId);
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: channelId },
+ ]);
+ });
+
+ it('refuses to move chats into a channel that is being deleted', async () => {
+ const channelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+
+ await holdChannelDeletionLock(destinationChannelId);
+
+ const deleteResponse = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ });
+
+ expect(deleteResponse.body.errors[0].extensions).toMatchObject({
+ code: 'CONFLICT',
+ subCode: AiExceptionCode.CHAT_CHANNEL_BUSY,
+ });
+ expect(await isChannelInCore(channelId)).toBe(true);
+ expect((await readChannelState(threadId)).channelId).toBe(channelId);
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: channelId },
+ ]);
+ });
+
+ it('announces the chats it moved when the channel cannot be deleted afterwards', async () => {
+ const channelId = await createChannel();
+ const destinationChannelId = await createChannel();
+ const threadId = await createThreadInChannel(channelId);
+ const { hasEmittedThreadEvent } = watchThreadEvents();
+
+ jest
+ .spyOn(getChannelMetadataService(), 'deleteChannel')
+ .mockRejectedValueOnce(new Error('Metadata delete failed'));
+
+ const deleteResponse = await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId, destinationChannelId },
+ });
+
+ expect(deleteResponse.body.errors).toBeDefined();
+ expect((await readChannelState(threadId)).channelId).toBe(
+ destinationChannelId,
+ );
+ expect(await readChannelGrants(threadId)).toEqual([
+ { principalType: 'ROLE', sourceId: destinationChannelId },
+ ]);
+ expect(await isChannelInCore(channelId)).toBe(true);
+ expect(hasEmittedThreadEvent(threadId)).toBe(true);
+
+ await createThreadInChannel(channelId);
+ });
+
+ it('deletes two channels into each other without leaving a chat behind', async () => {
+ const firstChannelId = await createChannel();
+ const secondChannelId = await createChannel();
+ const firstThreadId = await createThreadInChannel(firstChannelId);
+ const secondThreadId = await createThreadInChannel(secondChannelId);
+
+ const deleteResponses = await Promise.all([
+ makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: {
+ channelId: firstChannelId,
+ destinationChannelId: secondChannelId,
+ },
+ }),
+ makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: {
+ channelId: secondChannelId,
+ destinationChannelId: firstChannelId,
+ },
+ }),
+ ]);
+ const failedDeleteResponses = deleteResponses.filter(({ body }) =>
+ isDefined(body.errors),
+ );
+
+ expect(failedDeleteResponses.length).toBeGreaterThanOrEqual(1);
+ for (const { body } of failedDeleteResponses) {
+ expect([
+ AiExceptionCode.CHAT_CHANNEL_BUSY,
+ AiExceptionCode.CHAT_CHANNEL_NOT_FOUND,
+ ]).toContain(body.errors[0].extensions.subCode);
+ }
+ for (const threadId of [firstThreadId, secondThreadId]) {
+ const { channelId } = await readChannelState(threadId);
+
+ expect(isDefined(channelId) && (await isChannelInCore(channelId))).toBe(
+ true,
+ );
+ }
+ });
+
+ it('pins a channel to the sidebar until the channel is deleted', async () => {
+ const channelId = await createChannel();
+
+ const { errors: missingChannelErrors } = await createNavigationMenuItem({
+ input: { type: NavigationMenuItemType.AGENT_CHAT_CHANNEL },
+ expectToFail: true,
+ });
+
+ expect(missingChannelErrors).toBeDefined();
+
+ const { data } = await createNavigationMenuItem({
+ input: {
+ type: NavigationMenuItemType.AGENT_CHAT_CHANNEL,
+ agentChatChannelId: channelId,
+ },
+ gqlFields: 'id agentChatChannelId',
+ });
+ const navigationMenuItemId = data.createNavigationMenuItem.id;
+
+ expect(data.createNavigationMenuItem.agentChatChannelId).toBe(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId },
+ }),
+ );
+
+ const { data: afterDeleteData } = await findNavigationMenuItems({
+ input: undefined,
+ gqlFields: 'id',
+ });
+
+ expect(
+ afterDeleteData.navigationMenuItems.map(({ id }) => id),
+ ).not.toContain(navigationMenuItemId);
+ });
+
+ it('counts open chats for each channel the member reaches, and their own only once they follow', async () => {
+ const channelId = await createChannel();
+ const janeOpenThreadCount = await getOpenThreadCount();
+ const jonyOpenThreadCount = await getOpenThreadCount(
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const threadId = await createThreadInChannel(channelId);
+ const doneThreadId = await createThreadInChannel(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation(
+ 'markAgentChatThreadAsDoneInChannel',
+ doneThreadId,
+ ),
+ );
+ await simulateNewMessageActivity(threadId);
+
+ for (const token of [
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ ]) {
+ expect(
+ (await getChannelSummaries(token)).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ openCount: 1,
+ assignedToMeCount: 0,
+ snoozedCount: 0,
+ doneCount: 1,
+ hasUnreadOpen: true,
+ hasUnreadAssignedToMe: false,
+ });
+ }
+
+ // Jane follows both chats she started, so filing one for the channel
+ // files her own copy too
+ expect(await getOpenThreadCount()).toBe(janeOpenThreadCount + 1);
+ expect(await getOpenThreadCount(APPLE_JONY_MEMBER_ACCESS_TOKEN)).toBe(
+ jonyOpenThreadCount,
+ );
+ });
+
+ it('counts each channel status and unread open chats assigned to the requesting member', async () => {
+ const channelId = await createChannel();
+
+ expect(
+ (await getChannelSummaries()).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ openCount: 0,
+ assignedToMeCount: 0,
+ snoozedCount: 0,
+ doneCount: 0,
+ hasUnreadOpen: false,
+ hasUnreadAssignedToMe: false,
+ });
+
+ const threadId = await createThreadInChannel(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: ASSIGN,
+ variables: { threadId, assigneeWorkspaceMemberId: JONY },
+ }),
+ );
+ await simulateNewMessageActivity(threadId);
+
+ expect(
+ (await getChannelSummaries()).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toMatchObject({
+ openCount: 1,
+ assignedToMeCount: 0,
+ hasUnreadAssignedToMe: false,
+ });
+ expect(
+ (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ openCount: 1,
+ assignedToMeCount: 1,
+ snoozedCount: 0,
+ doneCount: 0,
+ hasUnreadOpen: true,
+ hasUnreadAssignedToMe: true,
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: SNOOZE_IN_CHANNEL,
+ variables: { threadId, snoozedUntil: buildFutureSnoozedUntil() },
+ }),
+ );
+
+ expect(
+ (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ openCount: 0,
+ assignedToMeCount: 0,
+ snoozedCount: 1,
+ doneCount: 0,
+ hasUnreadOpen: false,
+ hasUnreadAssignedToMe: false,
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await runThreadMutation('markAgentChatThreadAsDoneInChannel', threadId),
+ );
+
+ expect(
+ (await getChannelSummaries(APPLE_JONY_MEMBER_ACCESS_TOKEN)).find(
+ (summary) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ openCount: 0,
+ assignedToMeCount: 0,
+ snoozedCount: 0,
+ doneCount: 1,
+ hasUnreadOpen: false,
+ hasUnreadAssignedToMe: false,
+ });
+ });
+
+ it('narrows open channel chats to those waiting on an answer or mentioning the member', async () => {
+ const channelId = await createChannel();
+ const needsInputThreadId = await createThreadInChannel(channelId);
+ const mentionedThreadId = await createThreadInChannel(channelId);
+
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "pendingQuestionMessageId" = $1 WHERE id = $2`,
+ [randomUUID(), needsInputThreadId],
+ );
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThreadParticipant" SET "lastMentionedAt" = now()
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [mentionedThreadId, JANE],
+ );
+
+ expect(
+ (await findChannelThreadIds(channelId, { filter: 'NEEDS_INPUT' }))
+ .threadIds,
+ ).toEqual([needsInputThreadId]);
+ expect(
+ (await findChannelThreadIds(channelId, { filter: 'MENTIONED' }))
+ .threadIds,
+ ).toEqual([mentionedThreadId]);
+ expect(
+ (
+ await findChannelThreadIds(
+ channelId,
+ { filter: 'MENTIONED' },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ )
+ ).threadIds,
+ ).toEqual([]);
+
+ const response = await makeMetadataApiRequest({
+ query: parse(
+ `query Summaries { agentChatChannelSummaries { channelId needsInputCount mentionedCount assignedCount unassignedCount } }`,
+ ),
+ });
+
+ assertGraphQLSuccessfulResponse(response);
+ expect(
+ response.body.data.agentChatChannelSummaries.find(
+ (summary: { channelId: string }) => summary.channelId === channelId,
+ ),
+ ).toEqual({
+ channelId,
+ needsInputCount: 1,
+ mentionedCount: 1,
+ assignedCount: 0,
+ unassignedCount: 2,
+ });
+ });
+
+ it('narrows open channel chats to assigned ones and keeps resolved mentions out', async () => {
+ const channelId = await createChannel();
+ const assignedThreadId = await createThreadInChannel(channelId);
+ const unassignedThreadId = await createThreadInChannel(channelId);
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: ASSIGN,
+ variables: {
+ threadId: assignedThreadId,
+ assigneeWorkspaceMemberId: JONY,
+ },
+ }),
+ );
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThreadParticipant"
+ SET "lastMentionedAt" = now(), "mentionsResolvedAt" = now()
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [unassignedThreadId, JANE],
+ );
+
+ expect(
+ (await findChannelThreadIds(channelId, { assignment: 'ASSIGNED' }))
+ .threadIds,
+ ).toEqual([assignedThreadId]);
+ expect(
+ (await findChannelThreadIds(channelId, { assignment: 'UNASSIGNED' }))
+ .threadIds,
+ ).toEqual([unassignedThreadId]);
+ expect(
+ (await findChannelThreadIds(channelId, { filter: 'MENTIONED' }))
+ .threadIds,
+ ).toEqual([]);
+ });
+
+ it('keeps the channel chats of a removed member in their channel', async () => {
+ const channelId = await createChannel();
+ const channelThreadId = await createThreadInChannel(
+ channelId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const ownThreadId = await createThreadInChannel(
+ null,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const { flatFieldMetadataMaps } =
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, ['flatFieldMetadataMaps']);
+
+ await detachAgentChatChannelThreadsFromWorkspaceMember({
+ threadRepository: global.app.get<
+ string,
+ AgentHistoryRepository<AgentChatThreadWorkspaceEntity>
+ >(getAgentHistoryRepositoryToken('agentChatThread'), { strict: false }),
+ flatFieldMetadataMaps,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: JONY,
+ });
+
+ const owners: { id: string; workspaceMemberId: string | null }[] =
+ await global.testDataSource.query(
+ `SELECT id, "workspaceMemberId" FROM ${SCHEMA}."agentChatThread"
+ WHERE id = ANY($1::uuid[]) ORDER BY id`,
+ [[channelThreadId, ownThreadId]],
+ );
+
+ expect(owners).toEqual(
+ [
+ { id: channelThreadId, workspaceMemberId: null },
+ { id: ownThreadId, workspaceMemberId: JONY },
+ ].sort((threadA, threadB) => threadA.id.localeCompare(threadB.id)),
+ );
+
+ const leaveResponse = await makeMetadataApiRequest({
+ query: MOVE_THREAD,
+ variables: { threadId: channelThreadId, channelId: null },
+ });
+
+ expect(leaveResponse.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+
+ // Neither chat is Jane's to destroy any more
+ await global.testDataSource.query(
+ `DELETE FROM ${SCHEMA}."agentChatThread" WHERE id = ANY($1::uuid[])`,
+ [[channelThreadId, ownThreadId]],
+ );
+ createdThreadIds.splice(
+ 0,
+ createdThreadIds.length,
+ ...createdThreadIds.filter(
+ (threadId) => ![channelThreadId, ownThreadId].includes(threadId),
+ ),
+ );
+ });
+
+ it('pages a channel by last activity', async () => {
+ const channelId = await createChannel();
+ const olderThreadId = await createThreadInChannel(channelId);
+ const newerThreadId = await createThreadInChannel(channelId);
+
+ await simulateNewMessageActivity(newerThreadId);
+
+ const firstPage = await findChannelThreadIds(
+ channelId,
+ {},
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ { first: 1 },
+ );
+
+ expect(firstPage).toMatchObject({
+ threadIds: [newerThreadId],
+ hasNextPage: true,
+ });
+
+ const secondPage = await findChannelThreadIds(
+ channelId,
+ {},
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ { first: 1, after: firstPage.endCursor! },
+ );
+
+ expect(secondPage).toMatchObject({
+ threadIds: [olderThreadId],
+ hasNextPage: false,
+ });
+
+ const invalidResponse = await makeMetadataApiRequest({
+ query: CHANNEL_THREAD_IDS,
+ variables: { channelId, after: 'not-a-cursor' },
+ });
+
+ expect(invalidResponse.body.errors[0].extensions.code).toBe(
+ 'BAD_USER_INPUT',
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-channel/utils/chat-channel-test.util.ts b/packages/twenty-server/test/integration/graphql/suites/chat-channel/utils/chat-channel-test.util.ts
new file mode 100644
index 00000000000..45faaef04db
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-channel/utils/chat-channel-test.util.ts
@@ -0,0 +1,618 @@
+import { randomUUID } from 'node:crypto';
+import { parse } from 'graphql';
+import { type AgentChatInboxAction } from 'twenty-shared/ai';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { isNonEmptyArray } from 'twenty-shared/utils';
+import { type QueryRunner } from 'typeorm';
+import { assertGraphQLSuccessfulResponse } from 'test/integration/graphql/utils/graphql-test-assertions.util';
+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
+import { updateOneRole } from 'test/integration/metadata/suites/role/utils/update-one-role.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
+import { expectEventually } from 'test/integration/utils/expect-eventually.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
+import { type AgentChatChannelMetadataService } from 'src/engine/metadata-modules/agent-chat-channel/services/agent-chat-channel-metadata.service';
+import { type AgentChatChannelSummaryDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-channel-summary.dto';
+import { type UpdateAgentChatChannelInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/update-agent-chat-channel.input';
+import { type AgentChatChannelAccessService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-channel-access.service';
+import { type AgentChatChannelGrantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-channel-grant.service';
+import { acquireAgentChatChannelGrantLocks } from 'src/engine/metadata-modules/ai/ai-chat/utils/acquire-agent-chat-channel-grant-locks.util';
+import { buildAgentChatChannelDeletionLockKey } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-channel-deletion-lock-key.util';
+import { buildAgentChatChannelGrantLockKey } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-channel-grant-lock-key.util';
+import { lockAgentChatChannelForThreadWriteOrThrow } from 'src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-channel-for-thread-write-or-throw.util';
+import { type MetadataEventEmitter } from 'src/engine/subscriptions/metadata-event/metadata-event-emitter';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+export const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+type ChannelAccess = { roleIds?: string[] };
+
+type ChannelThreadsFilter = {
+ status?: 'OPEN' | 'SNOOZED' | 'DONE';
+ assignment?: 'ANY' | 'ASSIGNED' | 'UNASSIGNED' | 'ASSIGNED_TO_ME';
+ filter?: 'ANY' | 'NEEDS_INPUT' | 'MENTIONED';
+};
+
+type ChannelThreadMutationName =
+ | 'markAgentChatThreadAsDoneInChannel'
+ | 'reopenAgentChatThreadInChannel';
+
+export const CREATE_CHANNEL = parse(
+ `mutation CreateChannel($input: CreateAgentChatChannelInput!) { createAgentChatChannel(input: $input) { id name icon color roleIds applicationId } }`,
+);
+
+const UPDATE_CHANNEL = parse(
+ `mutation UpdateChannel($channelId: UUID!, $input: UpdateAgentChatChannelInput!) { updateAgentChatChannel(channelId: $channelId, input: $input) { id name roleIds } }`,
+);
+
+export const DELETE_CHANNEL = parse(
+ `mutation DeleteChannel($channelId: UUID!, $destinationChannelId: UUID) { deleteAgentChatChannel(channelId: $channelId, destinationChannelId: $destinationChannelId) }`,
+);
+
+export const CHANNEL_ROLES = parse(
+ `query ChannelRoles { agentChatChannelRoles { id } }`,
+);
+
+const CHANNELS = parse(
+ `query Channels { agentChatChannels { id name applicationId isCustom isAccessible } }`,
+);
+
+export const CREATE_THREAD = parse(
+ `mutation CreateThread($channelId: UUID) { createChatThread(channelId: $channelId) { id } }`,
+);
+
+export const MOVE_THREAD = parse(
+ `mutation Move($threadId: UUID!, $channelId: UUID) { moveAgentChatThreadToChannel(threadId: $threadId, channelId: $channelId) }`,
+);
+
+const THREAD_MUTATION = (name: ChannelThreadMutationName) =>
+ parse(`mutation Run($threadId: UUID!) { ${name}(threadId: $threadId) }`);
+
+const UPDATE_INBOX_STATE = parse(
+ `mutation Update($threadIds: [UUID!]!, $action: AgentChatInboxAction!, $snoozedUntil: DateTime) { updateAgentChatThreadInboxState(threadIds: $threadIds, action: $action, snoozedUntil: $snoozedUntil) { id } }`,
+);
+
+export const SNOOZE_IN_CHANNEL = parse(
+ `mutation Snooze($threadId: UUID!, $snoozedUntil: DateTime!) { snoozeAgentChatThreadInChannel(threadId: $threadId, snoozedUntil: $snoozedUntil) }`,
+);
+
+export const ASSIGN = parse(
+ `mutation Assign($threadId: UUID!, $assigneeWorkspaceMemberId: UUID) { assignAgentChatThread(threadId: $threadId, assigneeWorkspaceMemberId: $assigneeWorkspaceMemberId) }`,
+);
+
+export const CHANNEL_THREAD_IDS = parse(
+ `query Ids($channelId: UUID!, $status: AgentChatChannelThreadStatus, $assignment: AgentChatChannelAssignmentFilter, $filter: AgentChatChannelThreadFilter, $first: Int, $after: String) { agentChatChannelThreadIds(channelId: $channelId, status: $status, assignment: $assignment, filter: $filter, first: $first, after: $after) { threadIds hasNextPage endCursor } }`,
+);
+
+const CHANNEL_SUMMARIES = parse(
+ `query Summaries { agentChatChannelSummaries { channelId openCount assignedToMeCount snoozedCount doneCount hasUnreadOpen hasUnreadAssignedToMe } }`,
+);
+
+const OPEN_THREADS_SUMMARY = parse(
+ `query Summary { agentChatOpenThreadsSummary { openThreadCount hasUnreadOpenThread } }`,
+);
+
+// Outlasts any test, yet within the delay the test queue fast-forwards
+export const buildFutureSnoozedUntil = () =>
+ new Date(Date.now() + 30_000).toISOString();
+
+export const runThreadMutation = (
+ name: ChannelThreadMutationName,
+ threadId: string,
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+) =>
+ makeMetadataApiRequest(
+ { query: THREAD_MUTATION(name), variables: { threadId } },
+ token,
+ );
+
+export const runInboxAction = (
+ action: AgentChatInboxAction,
+ threadId: string,
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ snoozedUntil: string | null = null,
+) =>
+ makeMetadataApiRequest(
+ {
+ query: UPDATE_INBOX_STATE,
+ variables: { threadIds: [threadId], action, snoozedUntil },
+ },
+ token,
+ );
+
+export const findChannelThreadIds = async (
+ channelId: string,
+ filter: ChannelThreadsFilter = {},
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ page: { first?: number; after?: string } = {},
+): Promise<{
+ threadIds: string[];
+ hasNextPage: boolean;
+ endCursor: string | null;
+}> => {
+ const response = await makeMetadataApiRequest(
+ {
+ query: CHANNEL_THREAD_IDS,
+ variables: { channelId, ...filter, ...page, first: page.first ?? 200 },
+ },
+ token,
+ );
+
+ assertGraphQLSuccessfulResponse(response);
+
+ return response.body.data.agentChatChannelThreadIds;
+};
+
+export const getChannelSummaries = async (
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+): Promise<AgentChatChannelSummaryDTO[]> => {
+ const response = await makeMetadataApiRequest(
+ { query: CHANNEL_SUMMARIES },
+ token,
+ );
+
+ assertGraphQLSuccessfulResponse(response);
+
+ return response.body.data.agentChatChannelSummaries;
+};
+
+export const getOpenThreadCount = async (
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+): Promise<number> => {
+ const response = await makeMetadataApiRequest(
+ { query: OPEN_THREADS_SUMMARY },
+ token,
+ );
+
+ assertGraphQLSuccessfulResponse(response);
+
+ return response.body.data.agentChatOpenThreadsSummary.openThreadCount;
+};
+
+export const readMemberCopy = async (
+ threadId: string,
+ workspaceMemberId: string,
+) => {
+ const [row]: {
+ isSubscribed: boolean;
+ archivedAt: Date | null;
+ snoozedUntil: Date | null;
+ }[] = await global.testDataSource.query(
+ `SELECT "isSubscribed", "archivedAt", "snoozedUntil"
+ FROM ${SCHEMA}."agentChatThreadParticipant"
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [threadId, workspaceMemberId],
+ );
+
+ return row ?? null;
+};
+
+export const readChannelState = async (threadId: string) => {
+ const [row]: {
+ channelId: string | null;
+ channelArchivedAt: Date | null;
+ channelSnoozedUntil: Date | null;
+ }[] = await global.testDataSource.query(
+ `SELECT "channelId", "channelArchivedAt", "channelSnoozedUntil"
+ FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,
+ [threadId],
+ );
+
+ return row;
+};
+
+export const listChannels = async (
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+): Promise<
+ {
+ id: string;
+ name: string;
+ applicationId: string;
+ isCustom: boolean;
+ isAccessible: boolean;
+ }[]
+> => {
+ const response = await makeMetadataApiRequest({ query: CHANNELS }, token);
+
+ assertGraphQLSuccessfulResponse(response);
+
+ return response.body.data.agentChatChannels;
+};
+
+export const readChannelGrants = async (
+ threadId: string,
+): Promise<{ principalType: string; sourceId: string }[]> =>
+ global.testDataSource.query(
+ `SELECT DISTINCT "principalType", "sourceId" FROM ${SCHEMA}."recordShare"
+ WHERE "recordId" = $1 AND "rowCause" = 'RULE' AND "deletedAt" IS NULL
+ ORDER BY "principalType"`,
+ [threadId],
+ );
+
+export const readChannelGrantRoleIds = async (
+ threadId: string,
+): Promise<string[]> =>
+ (
+ await global.testDataSource.query(
+ `SELECT "principalId" FROM ${SCHEMA}."recordShare"
+ WHERE "recordId" = $1 AND "rowCause" = 'RULE' AND "deletedAt" IS NULL
+ AND "principalType" = 'ROLE'`,
+ [threadId],
+ )
+ ).map(({ principalId }: { principalId: string }) => principalId);
+
+export const setRoleAllChannelsAccess = async (
+ roleId: string,
+ canAccessAllAgentChatChannels: boolean,
+) => {
+ const { errors } = await updateOneRole({
+ input: {
+ idToUpdate: roleId,
+ updatePayload: { canAccessAllAgentChatChannels },
+ },
+ gqlFields: 'id',
+ });
+
+ expect(errors).toBeUndefined();
+};
+
+export const waitForChannelGrantRewrites = async () => {
+ await getAppProviderByClassName<MetadataEventEmitter>(
+ 'MetadataEventEmitter',
+ ).drain();
+ await waitForAllJobsToFinish();
+};
+
+export const getChannelGrantService = () =>
+ getAppProviderByClassName<AgentChatChannelGrantService>(
+ 'AgentChatChannelGrantService',
+ );
+
+export const waitForBlockedChannelGrantLock = (channelId: string) =>
+ expectEventually(async () => {
+ const [{ count }]: { count: number }[] = await global.testDataSource.query(
+ `WITH lock_key AS (SELECT hashtextextended($1, 0) AS value)
+ SELECT count(*)::int AS count FROM pg_locks, lock_key
+ WHERE pg_locks.locktype = 'advisory' AND NOT pg_locks.granted
+ AND pg_locks.objsubid = 1
+ AND pg_locks.database = (SELECT oid FROM pg_database WHERE datname = current_database())
+ AND pg_locks.classid = ((lock_key.value >> 32) & 4294967295)::oid
+ AND pg_locks.objid = (lock_key.value & 4294967295)::oid`,
+ [
+ buildAgentChatChannelGrantLockKey({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ channelId,
+ }),
+ ],
+ );
+
+ expect(count).toBeGreaterThanOrEqual(1);
+ });
+
+export const isChannelInCore = async (channelId: string): Promise<boolean> =>
+ isNonEmptyArray(
+ await global.testDataSource.query(
+ `SELECT id FROM core."agentChatChannel" WHERE id = $1`,
+ [channelId],
+ ),
+ );
+
+export const countThreadsInChannel = async (
+ channelId: string,
+): Promise<number> => {
+ const [{ count }]: { count: number }[] = await global.testDataSource.query(
+ `SELECT count(*)::int AS count FROM ${SCHEMA}."agentChatThread" WHERE "channelId" = $1`,
+ [channelId],
+ );
+
+ return count;
+};
+
+const countThreadsInDeletedChannels = async (
+ channelIds: string[],
+): Promise<number> => {
+ const [{ count }]: { count: number }[] = await global.testDataSource.query(
+ `SELECT count(*)::int AS count FROM ${SCHEMA}."agentChatThread" thread
+ WHERE thread."channelId" = ANY($1::uuid[])
+ AND NOT EXISTS (
+ SELECT 1 FROM core."agentChatChannel" channel
+ WHERE channel.id = thread."channelId"
+ )`,
+ [channelIds],
+ );
+
+ return count;
+};
+
+export const watchThreadEvents = () => {
+ const eventSpy = jest.spyOn(
+ getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter'),
+ 'emitDatabaseBatchEvent',
+ );
+
+ return {
+ hasEmittedThreadEvent: (threadId: string) =>
+ eventSpy.mock.calls.some(
+ ([batchEvent]) =>
+ batchEvent?.objectMetadataNameSingular === 'agentChatThread' &&
+ batchEvent.events.some(
+ (event) => 'recordId' in event && event.recordId === threadId,
+ ),
+ ),
+ };
+};
+
+export const getChannelMetadataService = () =>
+ getAppProviderByClassName<AgentChatChannelMetadataService>(
+ 'AgentChatChannelMetadataService',
+ );
+
+export const deleteChannelBehindStaleCache = async (channelId: string) => {
+ const staleChannel = await getChannelMetadataService().findChannelOrThrow({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ channelId,
+ });
+
+ assertGraphQLSuccessfulResponse(
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId },
+ }),
+ );
+
+ jest
+ .spyOn(
+ getAppProviderByClassName<AgentChatChannelAccessService>(
+ 'AgentChatChannelAccessService',
+ ),
+ 'assertChannelAccess',
+ )
+ .mockResolvedValue(staleChannel);
+};
+
+export const insertChannelGrant = ({
+ queryRunner,
+ threadId,
+ roleId,
+ channelId,
+}: {
+ queryRunner: QueryRunner;
+ threadId: string;
+ roleId: string;
+ channelId: string;
+}) =>
+ queryRunner.query(
+ `INSERT INTO ${SCHEMA}."recordShare"
+ ("objectMetadataId", "recordId", "principalId", "principalType", "accessLevel", "rowCause", "sourceId")
+ SELECT metadata.id, $1, $2, 'ROLE', 'READ_WRITE', 'RULE', $3
+ FROM core."objectMetadata" metadata
+ WHERE metadata."workspaceId" = $4 AND metadata."universalIdentifier" = $5`,
+ [
+ threadId,
+ roleId,
+ channelId,
+ SEED_APPLE_WORKSPACE_ID,
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier,
+ ],
+ );
+
+export const simulateNewMessageActivity = (threadId: string) =>
+ global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "lastActivityAt" = clock_timestamp() WHERE id = $1`,
+ [threadId],
+ );
+
+export const setUpChatChannelTests = () => {
+ const createdThreadIds: string[] = [];
+ const createdChannelIds: string[] = [];
+
+ const createChannel = async (
+ { roleIds = [] }: ChannelAccess = {},
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ ): Promise<string> => {
+ const response = await makeMetadataApiRequest(
+ {
+ query: CREATE_CHANNEL,
+ variables: {
+ input: {
+ name: ` Channel ${randomUUID()} `,
+ roleIds,
+ },
+ },
+ },
+ token,
+ );
+
+ assertGraphQLSuccessfulResponse(response);
+
+ const channelId = response.body.data.createAgentChatChannel.id;
+
+ createdChannelIds.push(channelId);
+
+ return channelId;
+ };
+
+ const updateChannel = (
+ channelId: string,
+ input: UpdateAgentChatChannelInput,
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ ) =>
+ makeMetadataApiRequest(
+ { query: UPDATE_CHANNEL, variables: { channelId, input } },
+ token,
+ );
+
+ const createThreadInChannel = async (
+ channelId: string | null,
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ ): Promise<string> => {
+ const response = await makeMetadataApiRequest(
+ { query: CREATE_THREAD, variables: { channelId } },
+ token,
+ );
+
+ assertGraphQLSuccessfulResponse(response);
+
+ const threadId = response.body.data.createChatThread.id;
+
+ createdThreadIds.push(threadId);
+
+ return threadId;
+ };
+
+ const roleIdsToReopenToAllChannels = new Set<string>();
+ const heldQueryRunners: QueryRunner[] = [];
+ let isChannelCacheStale = false;
+
+ const markChannelCacheStale = () => {
+ isChannelCacheStale = true;
+ };
+
+ const startHeldTransaction = async (): Promise<QueryRunner> => {
+ const queryRunner = global.testDataSource.createQueryRunner();
+
+ await queryRunner.connect();
+ heldQueryRunners.push(queryRunner);
+ await queryRunner.startTransaction();
+
+ return queryRunner;
+ };
+
+ const holdChannelGrantLock = async ({
+ channelId,
+ mode,
+ }: {
+ channelId: string;
+ mode: 'shared' | 'exclusive';
+ }): Promise<QueryRunner> => {
+ const queryRunner = await startHeldTransaction();
+
+ await acquireAgentChatChannelGrantLocks({
+ manager: queryRunner.manager,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ channelIds: [channelId],
+ mode,
+ });
+
+ return queryRunner;
+ };
+
+ const holdChannelDeletionLock = async (
+ channelId: string,
+ ): Promise<QueryRunner> => {
+ const queryRunner = await startHeldTransaction();
+
+ await queryRunner.query(
+ 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',
+ [
+ buildAgentChatChannelDeletionLockKey({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ channelId,
+ }),
+ ],
+ );
+
+ return queryRunner;
+ };
+
+ const fileThreadIntoHeldChannel = async ({
+ threadId,
+ channelId,
+ }: {
+ threadId: string;
+ channelId: string;
+ }): Promise<QueryRunner> => {
+ const queryRunner = await startHeldTransaction();
+
+ await lockAgentChatChannelForThreadWriteOrThrow({
+ manager: queryRunner.manager,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ channelId,
+ });
+ await queryRunner.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "channelId" = $1 WHERE id = $2`,
+ [channelId, threadId],
+ );
+
+ return queryRunner;
+ };
+
+ // Jony holds Member, which reaches every channel unless a test closes it
+ const closeMemberAllChannelsAccess = async (): Promise<string> => {
+ const { id: memberRoleId } = await findOneRoleByLabel({ label: 'Member' });
+
+ await setRoleAllChannelsAccess(memberRoleId, false);
+ roleIdsToReopenToAllChannels.add(memberRoleId);
+ await waitForChannelGrantRewrites();
+
+ return memberRoleId;
+ };
+
+ afterEach(async () => {
+ jest.restoreAllMocks();
+
+ const orphanedThreadCount =
+ await countThreadsInDeletedChannels(createdChannelIds);
+
+ for (const queryRunner of heldQueryRunners.splice(0)) {
+ if (queryRunner.isTransactionActive) {
+ await queryRunner.rollbackTransaction();
+ }
+ await queryRunner.release();
+ }
+
+ if (isChannelCacheStale) {
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).invalidateAndRecompute(SEED_APPLE_WORKSPACE_ID, [
+ 'flatAgentChatChannelMaps',
+ 'flatAgentChatChannelRoleMaps',
+ 'flatRoleMaps',
+ ]);
+ isChannelCacheStale = false;
+ }
+
+ const hasRolesToReopen = roleIdsToReopenToAllChannels.size > 0;
+
+ for (const roleId of roleIdsToReopenToAllChannels) {
+ await setRoleAllChannelsAccess(roleId, true);
+ }
+ roleIdsToReopenToAllChannels.clear();
+
+ if (hasRolesToReopen) {
+ await waitForChannelGrantRewrites();
+ }
+
+ for (const threadId of createdThreadIds.splice(0)) {
+ await destroyAgentChatThread({ threadId });
+ }
+ for (const channelId of createdChannelIds.splice(0)) {
+ await makeMetadataApiRequest({
+ query: DELETE_CHANNEL,
+ variables: { channelId },
+ });
+ }
+
+ expect(orphanedThreadCount).toBe(0);
+ });
+
+ return {
+ createdThreadIds,
+ createdChannelIds,
+ createChannel,
+ updateChannel,
+ createThreadInChannel,
+ roleIdsToReopenToAllChannels,
+ heldQueryRunners,
+ markChannelCacheStale,
+ startHeldTransaction,
+ holdChannelGrantLock,
+ holdChannelDeletionLock,
+ fileThreadIntoHeldChannel,
+ closeMemberAllChannelsAccess,
+ };
+};
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts
deleted file mode 100644
index f4f2daae83e..00000000000
--- a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts
+++ /dev/null
@@ -1,1593 +0,0 @@
-import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
-import { randomUUID } from 'node:crypto';
-import { EventEmitter, once } from 'node:events';
-
-import { parse } from 'graphql';
-import {
- type ObjectRecordCreateEvent,
- type ObjectRecordUpdateEvent,
-} from 'twenty-shared/database-events';
-import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-import {
- FeatureFlagKey,
- RecordShareAccessLevel,
- RecordSharePrincipalType,
-} from 'twenty-shared/types';
-
-import { waitForBlockedDatabaseQueryOrThrow } from 'test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util';
-import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
-import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
-import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
-import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
-import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
-import { setManualRecordShare } from 'test/integration/utils/set-manual-record-share.util';
-
-import { AgentChatInboxAction } from 'src/engine/metadata-modules/ai/ai-chat/enums/agent-chat-inbox-action.enum';
-import { type AgentChatQueueService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service';
-import { type AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
-import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
-import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
-import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
-import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
-import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
-import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
-import { type WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
-import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
-import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-
-const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
-
-const buildJonyThreadAccess = (threadId: string) => ({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- threadId,
-});
-
-const PARTICIPANT_FIELDS =
- 'id threadId lastReadAt archivedAt snoozedUntil isSubscribed lastMentionedAt mentionsResolvedAt updatedAt';
-
-const UPDATE_INBOX_STATE = parse(
- `mutation UpdateInboxState($threadIds: [UUID!]!, $action: AgentChatInboxAction!, $snoozedUntil: DateTime) { updateAgentChatThreadInboxState(threadIds: $threadIds, action: $action, snoozedUntil: $snoozedUntil) { ${PARTICIPANT_FIELDS} } }`,
-);
-
-// Outlasts any test, yet within the delay the test queue fast-forwards
-const buildFutureSnoozedUntil = () =>
- new Date(Date.now() + 30_000).toISOString();
-
-const ASSIGN = parse(
- `mutation Assign($threadId: UUID!, $assigneeWorkspaceMemberId: UUID) { assignAgentChatThread(threadId: $threadId, assigneeWorkspaceMemberId: $assigneeWorkspaceMemberId) }`,
-);
-
-const assign = (
- threadId: string,
- assigneeWorkspaceMemberId: string | null,
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
-) =>
- makeMetadataApiRequest(
- { query: ASSIGN, variables: { threadId, assigneeWorkspaceMemberId } },
- token,
- );
-
-const readAssigneeId = async (threadId: string): Promise<string | null> => {
- const [{ assigneeId }]: { assigneeId: string | null }[] =
- await global.testDataSource.query(
- `SELECT "assigneeId" FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,
- [threadId],
- );
-
- return assigneeId;
-};
-
-const addParticipants = (
- threadId: string,
- participantWorkspaceMemberIds: string[],
- workspaceMemberId: string = WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
-) =>
- getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- ).mentionParticipants({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId,
- threadId,
- participantWorkspaceMemberIds,
- });
-
-type Participant = {
- id: string;
- threadId: string;
- lastReadAt: string | null;
- archivedAt: string | null;
- snoozedUntil: string | null;
- isSubscribed: boolean;
- lastMentionedAt: string | null;
- mentionsResolvedAt: string | null;
-};
-
-const OPEN_THREADS_SUMMARY = parse(
- `query OpenThreadsSummary { agentChatOpenThreadsSummary { openThreadCount unreadOpenThreadCount needsInputThreadCount hasUnreadOpenThread hasUnreadMentionThread hasUnreadAssignedThread } }`,
-);
-
-type OpenThreadsSummary = {
- openThreadCount: number;
- unreadOpenThreadCount: number;
- needsInputThreadCount: number;
- hasUnreadOpenThread: boolean;
- hasUnreadMentionThread: boolean;
- hasUnreadAssignedThread: boolean;
-};
-
-const findOpenThreadsSummary = async (
- token: string = APPLE_JONY_MEMBER_ACCESS_TOKEN,
-): Promise<OpenThreadsSummary> => {
- const response = await makeMetadataApiRequest(
- { query: OPEN_THREADS_SUMMARY },
- token,
- );
-
- expect(response.body.errors).toBeUndefined();
-
- return response.body.data.agentChatOpenThreadsSummary;
-};
-
-const runInboxAction = (
- action: string,
- threadIds: string | string[],
- {
- token = APPLE_JANE_ADMIN_ACCESS_TOKEN,
- snoozedUntil,
- }: { token?: string; snoozedUntil?: string } = {},
-) =>
- makeMetadataApiRequest(
- {
- query: UPDATE_INBOX_STATE,
- variables: { threadIds: [threadIds].flat(), action, snoozedUntil },
- },
- token,
- );
-
-// Read the way the inbox does: rows come with the threads the caller can read
-const findThreadParticipants = async (
- threadId: string,
- token: string,
-): Promise<(Participant & { workspaceMemberId: string })[] | undefined> => {
- const response = await makeGraphqlApiRequest(
- findManyOperationFactory({
- objectMetadataSingularName: 'agentChatThread',
- objectMetadataPluralName: 'agentChatThreads',
- gqlFields: `id participants { edges { node { ${PARTICIPANT_FIELDS} workspaceMemberId } } }`,
- filter: { id: { eq: threadId } },
- }),
- token,
- );
-
- expect(response.body.errors).toBeUndefined();
-
- const [thread] = response.body.data.agentChatThreads.edges;
-
- return thread?.node.participants.edges.map(
- ({ node }: { node: Participant & { workspaceMemberId: string } }) => node,
- );
-};
-
-const findMyParticipant = async (
- threadId: string,
- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
-): Promise<Participant | undefined> => {
- const workspaceMemberId =
- token === APPLE_JONY_MEMBER_ACCESS_TOKEN
- ? WORKSPACE_MEMBER_DATA_SEED_IDS.JONY
- : WORKSPACE_MEMBER_DATA_SEED_IDS.JANE;
-
- return (await findThreadParticipants(threadId, token))?.find(
- (participant) => participant.workspaceMemberId === workspaceMemberId,
- );
-};
-
-const readThreadActivity = async (threadId: string) => {
- const [row]: {
- lastActivityAt: Date;
- lastMessageText: string | null;
- lastMessageSenderWorkspaceMemberId: string | null;
- writerWorkspaceMemberIds: string[] | null;
- }[] = await global.testDataSource.query(
- `SELECT "lastActivityAt", "lastMessageText", "lastMessageSenderWorkspaceMemberId", "writerWorkspaceMemberIds"
- FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,
- [threadId],
- );
-
- return row;
-};
-
-const readLastActivityAt = async (threadId: string): Promise<Date> =>
- (await readThreadActivity(threadId)).lastActivityAt;
-
-const createThread = async (): Promise<string> => {
- const threadId = randomUUID();
-
- await getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- ).createThread({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- id: threadId,
- title: 'Participant state',
- });
-
- return threadId;
-};
-
-const spyOnParticipantEvents = () =>
- jest.spyOn(
- getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter'),
- 'emitDatabaseBatchEvent',
- );
-
-const findParticipantEvents = (
- eventSpy: ReturnType<typeof spyOnParticipantEvents>,
- threadId: string,
-) =>
- eventSpy.mock.calls
- .map(([batchEvent]) => batchEvent)
- .filter(
- (batchEvent) =>
- batchEvent?.objectMetadataNameSingular === 'agentChatThreadParticipant',
- )
- .flatMap((batchEvent) =>
- (
- batchEvent!.events as (
- | ObjectRecordCreateEvent<Participant>
- | ObjectRecordUpdateEvent<Participant>
- )[]
- )
- .filter(({ properties }) => properties.after.threadId === threadId)
- .map(({ properties }) => ({
- action: batchEvent!.action,
- updatedFields:
- 'updatedFields' in properties ? properties.updatedFields : [],
- })),
- );
-
-const listParticipantRecordIds = async (token: string): Promise<string[]> => {
- const response = await makeGraphqlApiRequest(
- findManyOperationFactory({
- objectMetadataSingularName: 'agentChatThreadParticipant',
- objectMetadataPluralName: 'agentChatThreadParticipants',
- gqlFields: 'id',
- first: 200,
- }),
- token,
- );
-
- expect(response.body.errors).toBeUndefined();
-
- return response.body.data.agentChatThreadParticipants.edges.map(
- ({ node }: { node: { id: string } }) => node.id,
- );
-};
-
-type ManualShare = {
- threadId: string;
- workspaceMemberId: string;
- accessLevel: RecordShareAccessLevel;
-};
-
-// Destroying a chat keeps its grants, so every grant a test enables is
-// disabled again after it
-const enabledManualShares: ManualShare[] = [];
-
-const setShareWithMember = async ({
- threadId,
- workspaceMemberId,
- accessLevel,
- enabled,
-}: {
- threadId: string;
- workspaceMemberId: string;
- accessLevel: RecordShareAccessLevel;
- enabled: boolean;
-}) => {
- if (enabled) {
- enabledManualShares.push({ threadId, workspaceMemberId, accessLevel });
- }
-
- const { flatObjectMetadataMaps } =
- await getAppProviderByClassName<WorkspaceCacheService>(
- 'WorkspaceCacheService',
- ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, ['flatObjectMetadataMaps']);
-
- await setManualRecordShare({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- share: {
- objectMetadataId:
- flatObjectMetadataMaps.byUniversalIdentifier[
- STANDARD_OBJECTS.agentChatThread.universalIdentifier
- ]!.id,
- recordId: threadId,
- principalId: workspaceMemberId,
- principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
- accessLevel,
- sourceId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- },
- enabled,
- });
-};
-
-const setShareWithJony = (threadId: string, enabled: boolean) =>
- setShareWithMember({
- threadId,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- accessLevel: RecordShareAccessLevel.READ,
- enabled,
- });
-
-const setRecordSharingEnabled = (value: boolean) =>
- updateFeatureFlag({
- featureFlag: FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED,
- value,
- expectToFail: false,
- });
-
-beforeAll(() => setRecordSharingEnabled(true));
-
-afterAll(() => setRecordSharingEnabled(false));
-
-describe('Chat thread participant state through the authenticated API', () => {
- const createdThreadIds: string[] = [];
-
- const createTestThread = async () => {
- const threadId = await createThread();
-
- createdThreadIds.push(threadId);
-
- return threadId;
- };
-
- afterEach(async () => {
- jest.restoreAllMocks();
-
- for (const manualShare of enabledManualShares.splice(0)) {
- await setShareWithMember({ ...manualShare, enabled: false });
- }
- // Mentions share chats with Jony from the code under test
- for (const threadId of createdThreadIds.splice(0)) {
- await setShareWithJony(threadId, false);
- await destroyAgentChatThread({ threadId });
- }
- });
-
- it('starts the owner with the new thread read and in the inbox', async () => {
- const threadId = await createTestThread();
- const participant = await findMyParticipant(threadId);
- const lastActivityAt = await readLastActivityAt(threadId);
-
- expect(participant).toMatchObject({
- archivedAt: null,
- snoozedUntil: null,
- });
- expect(new Date(participant!.lastReadAt!).getTime()).toBe(
- lastActivityAt.getTime(),
- );
- });
-
- it('refuses a member who cannot read the thread', async () => {
- const threadId = await createTestThread();
- const response = await runInboxAction('READ', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toBeUndefined();
- });
-
- it('writes every selected thread in one call, or none when one cannot be read', async () => {
- const threadIds = [await createTestThread(), await createTestThread()];
-
- await setShareWithJony(threadIds[0], true);
-
- const refused = await runInboxAction('ARCHIVE', threadIds, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(refused.body.errors[0].extensions.code).toBe('NOT_FOUND');
- expect(
- await findMyParticipant(threadIds[0], APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toBeUndefined();
-
- await setShareWithJony(threadIds[1], true);
-
- const archived = await runInboxAction('ARCHIVE', threadIds, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(archived.body.errors).toBeUndefined();
- expect(archived.body.data.updateAgentChatThreadInboxState).toHaveLength(2);
- expect(archived.body.data.updateAgentChatThreadInboxState).toEqual(
- expect.arrayContaining(
- threadIds.map((threadId) =>
- expect.objectContaining({ threadId, archivedAt: expect.any(String) }),
- ),
- ),
- );
- });
-
- it('keeps a shared member state apart from the owner state', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
-
- // A thread shared with a member they never opened has no state yet,
- // which reads as one they do not follow
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toBeUndefined();
-
- const archived = await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(archived.body.errors).toBeUndefined();
- expect(
- archived.body.data.updateAgentChatThreadInboxState[0].archivedAt,
- ).not.toBeNull();
- expect(await findMyParticipant(threadId)).toMatchObject({
- archivedAt: null,
- });
- });
-
- it('never moves the read cursor past the latest activity or back', async () => {
- const threadId = await createTestThread();
- const lastActivityAt = await readLastActivityAt(threadId);
-
- const unread = await runInboxAction('UNREAD', threadId);
-
- expect(
- unread.body.data.updateAgentChatThreadInboxState[0].lastReadAt,
- ).toBeNull();
-
- const read = await runInboxAction('READ', threadId);
-
- expect(
- new Date(
- read.body.data.updateAgentChatThreadInboxState[0].lastReadAt,
- ).getTime(),
- ).toBe(lastActivityAt.getTime());
-
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "lastActivityAt" = $2 WHERE id = $1`,
- [threadId, new Date(lastActivityAt.getTime() - 60_000)],
- );
-
- const readAgain = await runInboxAction('READ', threadId);
-
- expect(
- new Date(
- readAgain.body.data.updateAgentChatThreadInboxState[0].lastReadAt,
- ).getTime(),
- ).toBe(lastActivityAt.getTime());
- });
-
- it('snoozes only into the future and moves the thread back to the inbox', async () => {
- const threadId = await createTestThread();
- const pastSnooze = await runInboxAction('SNOOZE', threadId, {
- snoozedUntil: new Date(Date.now() - 60_000).toISOString(),
- });
-
- expect(pastSnooze.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
-
- const snoozedUntil = buildFutureSnoozedUntil();
- const snoozed = await runInboxAction('SNOOZE', threadId, { snoozedUntil });
-
- expect(snoozed.body.errors).toBeUndefined();
- expect(
- snoozed.body.data.updateAgentChatThreadInboxState[0].archivedAt,
- ).not.toBeNull();
- expect(
- new Date(
- snoozed.body.data.updateAgentChatThreadInboxState[0].snoozedUntil,
- ).getTime(),
- ).toBe(new Date(snoozedUntil).getTime());
-
- const moved = await runInboxAction('MOVE_TO_INBOX', threadId);
-
- expect(moved.body.data.updateAgentChatThreadInboxState[0]).toMatchObject({
- archivedAt: null,
- snoozedUntil: null,
- });
- });
-
- it('sends each change as a record event carrying what changed', async () => {
- const eventSpy = spyOnParticipantEvents();
- const threadId = await createTestThread();
-
- await runInboxAction('UNREAD', threadId);
- await runInboxAction('UNREAD', threadId);
- await runInboxAction('ARCHIVE', threadId);
-
- expect(findParticipantEvents(eventSpy, threadId)).toEqual([
- { action: 'created', updatedFields: [] },
- { action: 'updated', updatedFields: ['lastReadAt', 'updatedAt'] },
- { action: 'updated', updatedFields: ['archivedAt', 'updatedAt'] },
- ]);
- });
-
- it('lets only its member read a row, through the grant it is given', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- const janeParticipant = await findMyParticipant(threadId);
- const jonyParticipant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
- const ownerShares: { recordId: string; principalId: string }[] =
- await global.testDataSource.query(
- `SELECT "recordId", "principalId" FROM ${SCHEMA}."recordShare"
- WHERE "recordId" = ANY($1) AND "rowCause" = 'OWNER'
- ORDER BY "principalId"`,
- [[janeParticipant!.id, jonyParticipant!.id]],
- );
- const jonyRecordIds = await listParticipantRecordIds(
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(ownerShares).toEqual(
- expect.arrayContaining([
- {
- recordId: janeParticipant!.id,
- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- },
- {
- recordId: jonyParticipant!.id,
- principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- },
- ]),
- );
- expect(ownerShares).toHaveLength(2);
- expect(jonyRecordIds).toContain(jonyParticipant!.id);
- expect(jonyRecordIds).not.toContain(janeParticipant!.id);
- });
-
- it('ends a snooze once its time passes by moving the chat back to the inbox', async () => {
- const threadId = await createTestThread();
-
- await runInboxAction('SNOOZE', threadId, {
- snoozedUntil: buildFutureSnoozedUntil(),
- });
-
- const snoozedUntil = new Date(Date.now() - 1000);
-
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThreadParticipant" SET "snoozedUntil" = $3
- WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
- [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE, snoozedUntil],
- );
-
- const eventSpy = spyOnParticipantEvents();
-
- await getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).endSnooze({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadId,
- snoozedUntil: snoozedUntil.toISOString(),
- });
-
- const [row]: { archivedAt: Date | null; snoozedUntil: Date | null }[] =
- await global.testDataSource.query(
- `SELECT "archivedAt", "snoozedUntil" FROM ${SCHEMA}."agentChatThreadParticipant"
- WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
- [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
- );
-
- // The snooze stays recorded, so the chat shows what brought it back
- expect(row.archivedAt).toBeNull();
- expect(row.snoozedUntil?.getTime()).toBe(snoozedUntil.getTime());
- expect(findParticipantEvents(eventSpy, threadId)).toEqual([
- { action: 'updated', updatedFields: ['archivedAt', 'updatedAt'] },
- ]);
- });
-
- it('saves as ended a snooze whose time passed before it was saved', async () => {
- const threadId = await createTestThread();
- const snoozedUntil = new Date(Date.now() - 1000);
-
- // The snooze was accepted while its time was still ahead, and its
- // queued end already ran and found nothing to end
- const [participant] =
- await getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).updateInboxState({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadIds: [threadId],
- action: AgentChatInboxAction.SNOOZE,
- snoozedUntil,
- });
-
- expect(participant.archivedAt).toBeNull();
- expect(new Date(participant.snoozedUntil!).getTime()).toBe(
- snoozedUntil.getTime(),
- );
- });
-
- it('waits for the database clock before ending a snooze', async () => {
- const threadId = await createTestThread();
- const snoozedUntil = buildFutureSnoozedUntil();
-
- await runInboxAction('SNOOZE', threadId, { snoozedUntil });
-
- const eventSpy = spyOnParticipantEvents();
-
- await getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).endSnooze({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadId,
- snoozedUntil,
- });
-
- expect(findParticipantEvents(eventSpy, threadId)).toEqual([]);
- expect(await findMyParticipant(threadId)).toMatchObject({
- archivedAt: expect.any(String),
- });
- });
-
- it('leaves alone a snooze the member replaced since', async () => {
- const threadId = await createTestThread();
-
- await runInboxAction('SNOOZE', threadId, {
- snoozedUntil: buildFutureSnoozedUntil(),
- });
-
- const eventSpy = spyOnParticipantEvents();
-
- await getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).endSnooze({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadId,
- snoozedUntil: new Date(Date.now() - 1000).toISOString(),
- });
-
- expect(findParticipantEvents(eventSpy, threadId)).toEqual([]);
- expect(await findMyParticipant(threadId)).toMatchObject({
- archivedAt: expect.any(String),
- });
- });
-
- it('brings the thread back and marks it read for the member who writes in it', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
- await runInboxAction('ARCHIVE', threadId);
- await runInboxAction('UNREAD', threadId);
-
- const { lastActivityAt } =
- await getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).recordMemberActivity({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadId,
- text: 'Can you check the Stripe renewal?',
- });
-
- const owner = await findMyParticipant(threadId);
-
- expect(lastActivityAt).not.toBeNull();
- expect(await readThreadActivity(threadId)).toMatchObject({
- lastMessageText: 'Can you check the Stripe renewal?',
- lastMessageSenderWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- writerWorkspaceMemberIds: [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
- });
- expect(owner).toMatchObject({ archivedAt: null, snoozedUntil: null });
- expect(new Date(owner!.lastReadAt!).getTime()).toBe(
- lastActivityAt!.getTime(),
- );
-
- // The other member archived before this activity, so it is back in their
- // inbox and unread, without anyone touching their row
- const member = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(new Date(member!.archivedAt!).getTime()).toBeLessThan(
- lastActivityAt!.getTime(),
- );
- expect(member!.lastReadAt).toBeNull();
- });
-
- it('brings a thread back for its members on activity no member wrote', async () => {
- const threadId = await createTestThread();
- const archived = await runInboxAction('ARCHIVE', threadId);
-
- expect(archived.body.errors).toBeUndefined();
- expect(
- archived.body.data.updateAgentChatThreadInboxState[0].archivedAt,
- ).not.toBeNull();
-
- await getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- ).recordThreadActivity({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- threadId,
- text: 'The renewal is due next week.',
- });
-
- const owner = await findMyParticipant(threadId);
- const { lastActivityAt, ...lastMessage } =
- await readThreadActivity(threadId);
-
- expect(lastMessage).toMatchObject({
- lastMessageText: 'The renewal is due next week.',
- lastMessageSenderWorkspaceMemberId: null,
- });
-
- expect(new Date(owner!.archivedAt!).getTime()).toBeLessThan(
- lastActivityAt.getTime(),
- );
- expect(new Date(owner!.lastReadAt!).getTime()).toBeLessThan(
- lastActivityAt.getTime(),
- );
- });
-
- it("only lists the caller's own rows", async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- const rows: { workspaceMemberId: string }[] =
- await global.testDataSource.query(
- `SELECT "workspaceMemberId" FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = $1`,
- [threadId],
- );
-
- expect(rows).toHaveLength(2);
- expect(
- await findThreadParticipants(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toEqual([
- expect.objectContaining({
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- }),
- ]);
- });
-
- it('stops listing a thread once the member loses access to it', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toBeDefined();
-
- await setShareWithJony(threadId, false);
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toBeUndefined();
- });
-
- it('shares the thread with a mentioned member and brings it to their inbox unread', async () => {
- const threadId = await createTestThread();
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toBeUndefined();
-
- expect(
- await addParticipants(threadId, [
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- ]),
- ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ lastReadAt: null, archivedAt: null, snoozedUntil: null });
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
- ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- // Editors can mention others too; the owner keeps following as owner
- expect(
- await addParticipants(
- threadId,
- [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- ),
- ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JANE]);
- expect(await findMyParticipant(threadId)).toMatchObject({
- lastReadAt: null,
- });
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
- ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- });
-
- it('brings the thread back unread for a participant who had read and archived it', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- await runInboxAction('READ', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ lastReadAt: null, archivedAt: null, snoozedUntil: null });
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
- ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- });
-
- it('refuses a member who can only read the thread', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
-
- await expect(
- addParticipants(
- threadId,
- [WORKSPACE_MEMBER_DATA_SEED_IDS.TIM],
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- ),
- ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_NOT_FOUND });
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],
- ).toEqual([]);
- });
-
- it('leaves out a member who could only read the thread when the sender cannot share it', async () => {
- const threadId = await createTestThread();
-
- await setShareWithMember({
- threadId,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- accessLevel: RecordShareAccessLevel.READ_WRITE,
- enabled: true,
- });
- await setShareWithMember({
- threadId,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
- accessLevel: RecordShareAccessLevel.READ,
- enabled: true,
- });
-
- expect(
- await addParticipants(
- threadId,
- [WORKSPACE_MEMBER_DATA_SEED_IDS.TIM],
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- ),
- ).toEqual([]);
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],
- ).toEqual([]);
- });
-
- it('keeps an unsubscribed chat done through new activity', async () => {
- const threadId = await createTestThread();
- const unsubscribed = await runInboxAction('UNSUBSCRIBE', threadId);
-
- expect(unsubscribed.body.errors).toBeUndefined();
- expect(
- unsubscribed.body.data.updateAgentChatThreadInboxState[0],
- ).toMatchObject({ isSubscribed: false, snoozedUntil: null });
- expect(
- unsubscribed.body.data.updateAgentChatThreadInboxState[0].archivedAt,
- ).not.toBeNull();
-
- await getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- ).recordThreadActivity({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- threadId,
- text: 'The renewal went through',
- });
-
- expect(await findMyParticipant(threadId)).toMatchObject({
- isSubscribed: false,
- });
-
- // Subscribing again leaves the chat where it is until something happens
- const subscribed = await runInboxAction('SUBSCRIBE', threadId);
-
- expect(subscribed.body.errors).toBeUndefined();
- expect(
- subscribed.body.data.updateAgentChatThreadInboxState[0],
- ).toMatchObject({
- isSubscribed: true,
- archivedAt:
- unsubscribed.body.data.updateAgentChatThreadInboxState[0].archivedAt,
- });
- });
-
- it('follows the chat again for a member who reopens, snoozes or writes in it', async () => {
- const threadId = await createTestThread();
-
- await runInboxAction('UNSUBSCRIBE', threadId);
- await runInboxAction('MOVE_TO_INBOX', threadId);
-
- expect(await findMyParticipant(threadId)).toMatchObject({
- isSubscribed: true,
- archivedAt: null,
- });
-
- await runInboxAction('UNSUBSCRIBE', threadId);
- await runInboxAction('SNOOZE', threadId, {
- snoozedUntil: buildFutureSnoozedUntil(),
- });
-
- expect(await findMyParticipant(threadId)).toMatchObject({
- isSubscribed: true,
- });
-
- await runInboxAction('UNSUBSCRIBE', threadId);
- await getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).recordMemberActivity({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadId,
- text: 'Back on this one',
- });
-
- expect(await findMyParticipant(threadId)).toMatchObject({
- isSubscribed: true,
- archivedAt: null,
- });
- });
-
- it('follows the chat again and records the mention for a mentioned member who had unsubscribed', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const firstMention = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(firstMention).toMatchObject({ isSubscribed: true });
- expect(firstMention!.lastMentionedAt).not.toBeNull();
-
- await runInboxAction('UNSUBSCRIBE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const secondMention = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(secondMention).toMatchObject({
- isSubscribed: true,
- archivedAt: null,
- lastReadAt: null,
- });
- expect(new Date(secondMention!.lastMentionedAt!).getTime()).toBeGreaterThan(
- new Date(firstMention!.lastMentionedAt!).getTime(),
- );
- });
-
- it('refuses to change the subscription of a member who cannot read the chat', async () => {
- const threadId = await createTestThread();
- const response = await runInboxAction('UNSUBSCRIBE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
- });
-
- it('assigns a chat to a member who could not read it, who then finds it unread in their inbox', async () => {
- const threadId = await createTestThread();
- const response = await assign(
- threadId,
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- );
-
- expect(response.body.errors).toBeUndefined();
- expect(await readAssigneeId(threadId)).toBe(
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- );
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({
- isSubscribed: true,
- archivedAt: null,
- lastReadAt: null,
- });
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
- ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- });
-
- it('keeps a chat read for a member who assigns it to themselves', async () => {
- const threadId = await createTestThread();
-
- await runInboxAction('ARCHIVE', threadId);
-
- const response = await assign(
- threadId,
- WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- );
-
- expect(response.body.errors).toBeUndefined();
-
- const participant = await findMyParticipant(threadId);
-
- expect(participant).toMatchObject({ archivedAt: null, isSubscribed: true });
- expect(participant!.lastReadAt).not.toBeNull();
- expect(
- (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],
- ).toEqual([]);
- });
-
- it('keeps the former assignee following the chat once it is unassigned', async () => {
- const threadId = await createTestThread();
-
- await assign(threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
-
- const response = await assign(threadId, null);
-
- expect(response.body.errors).toBeUndefined();
- expect(await readAssigneeId(threadId)).toBeNull();
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ isSubscribed: true });
- });
-
- it('refuses to unsubscribe the assignee', async () => {
- const threadId = await createTestThread();
-
- await assign(threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
-
- const response = await runInboxAction('UNSUBSCRIBE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(response.body.errors[0].extensions.code).toBe('CONFLICT');
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ isSubscribed: true });
- });
-
- it('refuses to assign a chat for a member who can only read it', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
-
- const response = await assign(
- threadId,
- WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
- expect(await readAssigneeId(threadId)).toBeNull();
- });
-
- it('refuses an assignee who cannot reply when the caller cannot share the chat', async () => {
- const threadId = await createTestThread();
-
- await setShareWithMember({
- threadId,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- accessLevel: RecordShareAccessLevel.READ_WRITE,
- enabled: true,
- });
-
- const response = await assign(
- threadId,
- WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
- expect(await readAssigneeId(threadId)).toBeNull();
- });
-
- // Other tests' chats may stay open for the member, so counts are compared
- // with what they were before
- it('summarizes the open chats the member follows, from their own rows', async () => {
- const before = await findOpenThreadsSummary();
- const threadId = await createTestThread();
-
- expect(await findOpenThreadsSummary()).toEqual(before);
-
- await setShareWithJony(threadId, true);
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "pendingQuestionMessageId" = $2 WHERE id = $1`,
- [threadId, randomUUID()],
- );
-
- // Being able to open a chat, reading it or marking it unread does not
- // follow it
- expect(await findOpenThreadsSummary()).toEqual(before);
-
- for (const action of ['UNREAD', 'READ'] as const) {
- await runInboxAction(action, threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(await findOpenThreadsSummary()).toEqual(before);
- }
-
- await runInboxAction('SUBSCRIBE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(await findOpenThreadsSummary()).toMatchObject({
- openThreadCount: before.openThreadCount + 1,
- unreadOpenThreadCount: before.unreadOpenThreadCount,
- needsInputThreadCount: before.needsInputThreadCount + 1,
- hasUnreadOpenThread: before.hasUnreadOpenThread,
- });
-
- await runInboxAction('UNREAD', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(await findOpenThreadsSummary()).toMatchObject({
- openThreadCount: before.openThreadCount + 1,
- unreadOpenThreadCount: before.unreadOpenThreadCount + 1,
- hasUnreadOpenThread: true,
- });
-
- await runInboxAction('READ', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(await findOpenThreadsSummary()).toMatchObject({
- openThreadCount: before.openThreadCount + 1,
- unreadOpenThreadCount: before.unreadOpenThreadCount,
- hasUnreadOpenThread: before.hasUnreadOpenThread,
- });
-
- await runInboxAction('UNREAD', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(await findOpenThreadsSummary()).toEqual(before);
- });
-
- it('follows a chat the member files as done, so new activity brings it back', async () => {
- const threadId = await createTestThread();
-
- await setShareWithJony(threadId, true);
- await runInboxAction('READ', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ isSubscribed: false, archivedAt: null });
-
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ isSubscribed: true, archivedAt: expect.any(String) });
- });
-
- it('flags the open chats the member was mentioned in or assigned that are unread', async () => {
- const initialSummary = await findOpenThreadsSummary();
- const mentionedThreadId = await createTestThread();
- const assignedThreadId = await createTestThread();
-
- await addParticipants(mentionedThreadId, [
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- ]);
- await assign(assignedThreadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
-
- expect(await findOpenThreadsSummary()).toMatchObject({
- unreadOpenThreadCount: initialSummary.unreadOpenThreadCount + 2,
- hasUnreadMentionThread: true,
- hasUnreadAssignedThread: true,
- });
-
- const unsubscribed = await runInboxAction(
- 'UNSUBSCRIBE',
- mentionedThreadId,
- { token: APPLE_JONY_MEMBER_ACCESS_TOKEN },
- );
-
- expect(unsubscribed.body.errors).toBeUndefined();
-
- await runInboxAction('ARCHIVE', assignedThreadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- const before = await findOpenThreadsSummary();
-
- expect(before.unreadOpenThreadCount).toBe(
- initialSummary.unreadOpenThreadCount,
- );
-
- // Activity brings back a chat filed under done, but not one the member left
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThread" SET "lastActivityAt" = clock_timestamp() WHERE id = ANY($1)`,
- [[mentionedThreadId, assignedThreadId]],
- );
-
- expect(await findOpenThreadsSummary()).toMatchObject({
- openThreadCount: before.openThreadCount + 1,
- unreadOpenThreadCount: before.unreadOpenThreadCount + 1,
- });
- });
-
- it('resolves the mention when the member reads the chat and keeps it when they mark it unread', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- for (const action of ['READ', 'UNREAD']) {
- const response = await runInboxAction(action, threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
- const participant = response.body.data.updateAgentChatThreadInboxState[0];
-
- expect(response.body.errors).toBeUndefined();
- expect(participant.mentionsResolvedAt).toBe(participant.lastMentionedAt);
- }
- });
-
- it('preserves unresolved mentions while marking unread and snoozing', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- for (const action of ['UNREAD', 'SNOOZE']) {
- const response = await runInboxAction(action, threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- snoozedUntil:
- action === 'SNOOZE' ? buildFutureSnoozedUntil() : undefined,
- });
-
- expect(response.body.errors).toBeUndefined();
- expect(
- response.body.data.updateAgentChatThreadInboxState[0],
- ).toMatchObject({
- lastMentionedAt: expect.any(String),
- mentionsResolvedAt: null,
- });
- }
- });
-
- it('resolves only the member who successfully sends a reply', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- await addParticipants(
- threadId,
- [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
- WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
- );
-
- await getAppProviderByClassName<AgentChatService>(
- 'AgentChatService',
- ).addMessageAndResolveMention({
- ...buildJonyThreadAccess(threadId),
- userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
- uiMessage: {
- role: AgentMessageRole.USER,
- parts: [{ type: 'text', text: 'I have handled this.' }],
- },
- });
-
- const repliedParticipant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(repliedParticipant!.mentionsResolvedAt).toBe(
- repliedParticipant!.lastMentionedAt,
- );
- expect(await findMyParticipant(threadId)).toMatchObject({
- lastMentionedAt: expect.any(String),
- mentionsResolvedAt: null,
- });
- });
-
- it('keeps a mention resolved after Done until an explicit new mention arrives', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- await runInboxAction('ARCHIVE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- const doneParticipant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(doneParticipant!.mentionsResolvedAt).toBe(
- doneParticipant!.lastMentionedAt,
- );
-
- await getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- ).recordThreadActivity({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- threadId,
- text: 'An unrelated update',
- });
- await runInboxAction('MOVE_TO_INBOX', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({
- lastMentionedAt: doneParticipant!.lastMentionedAt,
- mentionsResolvedAt: doneParticipant!.mentionsResolvedAt,
- });
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const mentionedAgain = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(
- new Date(mentionedAgain!.lastMentionedAt!).getTime(),
- ).toBeGreaterThan(new Date(mentionedAgain!.mentionsResolvedAt!).getTime());
- });
-
- it('resolves a mention when the member unsubscribes', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- await runInboxAction('UNSUBSCRIBE', threadId, {
- token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
- });
-
- const unsubscribedParticipant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(unsubscribedParticipant).toMatchObject({
- isSubscribed: false,
- mentionsResolvedAt: unsubscribedParticipant!.lastMentionedAt,
- });
- });
-
- describe('queued replies to a mention', () => {
- const queueReply = (threadId: string) =>
- getAppProviderByClassName<AgentChatQueueService>(
- 'AgentChatQueueService',
- ).queueMessage({
- ...buildJonyThreadAccess(threadId),
- userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
- text: 'On it',
- });
-
- const deleteQueuedReply = (messageId: string) =>
- getAppProviderByClassName<AgentChatQueueService>(
- 'AgentChatQueueService',
- ).deleteQueuedMessage({
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- messageId,
- });
-
- it('resolves the mention when the member queues a reply and keeps it after the reply is deleted', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const reply = await queueReply(threadId);
- const repliedParticipant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(repliedParticipant!.mentionsResolvedAt).toBe(
- repliedParticipant!.lastMentionedAt,
- );
-
- await deleteQueuedReply(reply.id);
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({
- mentionsResolvedAt: repliedParticipant!.lastMentionedAt,
- });
- });
-
- it('queues a reply while another write of the member locks the chat', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const writeEvents = new EventEmitter();
- const writeStarted = once(writeEvents, 'started');
- const writeResumed = once(writeEvents, 'resumed');
- const write =
- getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).resolveMention({
- ...buildJonyThreadAccess(threadId),
- writeResponse: async ({ manager, table }) => {
- const [{ backendProcessId }] = await manager.query<
- { backendProcessId: number }[]
- >('SELECT pg_backend_pid() AS "backendProcessId"');
-
- writeEvents.emit('started', backendProcessId);
- await writeResumed;
- await manager.query(
- `SELECT id FROM ${table('agentChatThread')} WHERE id = $1 FOR UPDATE`,
- [threadId],
- );
- },
- });
-
- const [blockingProcessId] = await writeStarted;
- const reply = queueReply(threadId);
-
- await waitForBlockedDatabaseQueryOrThrow(blockingProcessId);
- writeEvents.emit('resumed');
-
- await expect(Promise.all([write, reply])).resolves.toEqual([
- undefined,
- expect.objectContaining({ threadId }),
- ]);
- });
- });
-
- it('delivers app recipients without creating or clearing an explicit mention', async () => {
- const threadId = await createTestThread();
- const threadService = getAppProviderByClassName<AgentChatThreadService>(
- 'AgentChatThreadService',
- );
- const delivery = {
- workspaceId: SEED_APPLE_WORKSPACE_ID,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
- threadId,
- participantWorkspaceMemberIds: [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY],
- };
-
- await threadService.deliverToParticipants(delivery);
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({
- isSubscribed: true,
- lastReadAt: null,
- lastMentionedAt: null,
- mentionsResolvedAt: null,
- });
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const mentionedParticipant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- await threadService.deliverToParticipants(delivery);
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({
- lastMentionedAt: mentionedParticipant!.lastMentionedAt,
- mentionsResolvedAt: null,
- });
- });
-
- it('rolls mention resolution back when a response cannot be recorded', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- await expect(
- getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- ).resolveMention({
- ...buildJonyThreadAccess(threadId),
- writeResponse: async () => {
- throw new Error('The response is invalid');
- },
- }),
- ).rejects.toThrow('The response is invalid');
-
- expect(
- await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
- ).toMatchObject({ mentionsResolvedAt: null });
- });
-
- it('preserves a newer mention when an older response finishes first', async () => {
- const threadId = await createTestThread();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const responseEvents = new EventEmitter();
- const responseStarted = once(responseEvents, 'started');
- const responseFinished = once(responseEvents, 'finished');
- const participantService =
- getAppProviderByClassName<AgentChatThreadParticipantService>(
- 'AgentChatThreadParticipantService',
- );
- const response = participantService.resolveMention({
- ...buildJonyThreadAccess(threadId),
- writeResponse: async () => {
- responseEvents.emit('started');
- await responseFinished;
- },
- });
-
- await responseStarted;
-
- const laterMention = participantService.markAsMentioned(
- buildJonyThreadAccess(threadId),
- );
-
- responseEvents.emit('finished');
- await Promise.all([response, laterMention]);
-
- const participant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(new Date(participant!.lastMentionedAt!).getTime()).toBeGreaterThan(
- new Date(participant!.mentionsResolvedAt!).getTime(),
- );
- });
-
- it('orders a new mention after the resolved cursor at millisecond precision', async () => {
- const threadId = await createTestThread();
- const resolvedAt = new Date(Date.now() + 60_000).toISOString();
-
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
- await global.testDataSource.query(
- `UPDATE ${SCHEMA}."agentChatThreadParticipant"
- SET "lastMentionedAt" = $3, "mentionsResolvedAt" = $3
- WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
- [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY, resolvedAt],
- );
- await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
-
- const participant = await findMyParticipant(
- threadId,
- APPLE_JONY_MEMBER_ACCESS_TOKEN,
- );
-
- expect(new Date(participant!.lastMentionedAt!).getTime()).toBe(
- new Date(resolvedAt).getTime() + 1,
- );
- });
-});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-inbox-state.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-inbox-state.integration-spec.ts
new file mode 100644
index 00000000000..ca437f02afc
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-inbox-state.integration-spec.ts
@@ -0,0 +1,330 @@
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { AgentChatInboxAction } from 'src/engine/metadata-modules/ai/ai-chat/enums/agent-chat-inbox-action.enum';
+import { type AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import {
+ setUpChatThreadParticipantTests,
+ SCHEMA,
+ buildFutureSnoozedUntil,
+ runInboxAction,
+ findMyParticipant,
+ readLastActivityAt,
+ spyOnParticipantEvents,
+ findParticipantEvents,
+ listParticipantRecordIds,
+ setShareWithJony,
+} from 'test/integration/graphql/suites/chat-thread-participant/utils/chat-thread-participant-test.util';
+
+describe('Chat thread participant inbox state through the authenticated API', () => {
+ const { createTestThread } = setUpChatThreadParticipantTests();
+
+ it('starts the owner with the new thread read and in the inbox', async () => {
+ const threadId = await createTestThread();
+ const participant = await findMyParticipant(threadId);
+ const lastActivityAt = await readLastActivityAt(threadId);
+
+ expect(participant).toMatchObject({
+ archivedAt: null,
+ snoozedUntil: null,
+ });
+ expect(new Date(participant!.lastReadAt!).getTime()).toBe(
+ lastActivityAt.getTime(),
+ );
+ });
+
+ it('refuses a member who cannot read the thread', async () => {
+ const threadId = await createTestThread();
+ const response = await runInboxAction('READ', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toBeUndefined();
+ });
+
+ it('writes every selected thread in one call, or none when one cannot be read', async () => {
+ const threadIds = [await createTestThread(), await createTestThread()];
+
+ await setShareWithJony(threadIds[0], true);
+
+ const refused = await runInboxAction('ARCHIVE', threadIds, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(refused.body.errors[0].extensions.code).toBe('NOT_FOUND');
+ expect(
+ await findMyParticipant(threadIds[0], APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toBeUndefined();
+
+ await setShareWithJony(threadIds[1], true);
+
+ const archived = await runInboxAction('ARCHIVE', threadIds, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(archived.body.errors).toBeUndefined();
+ expect(archived.body.data.updateAgentChatThreadInboxState).toHaveLength(2);
+ expect(archived.body.data.updateAgentChatThreadInboxState).toEqual(
+ expect.arrayContaining(
+ threadIds.map((threadId) =>
+ expect.objectContaining({ threadId, archivedAt: expect.any(String) }),
+ ),
+ ),
+ );
+ });
+
+ it('keeps a shared member state apart from the owner state', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+
+ // A thread shared with a member they never opened has no state yet,
+ // which reads as one they do not follow
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toBeUndefined();
+
+ const archived = await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(archived.body.errors).toBeUndefined();
+ expect(
+ archived.body.data.updateAgentChatThreadInboxState[0].archivedAt,
+ ).not.toBeNull();
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ archivedAt: null,
+ });
+ });
+
+ it('never moves the read cursor past the latest activity or back', async () => {
+ const threadId = await createTestThread();
+ const lastActivityAt = await readLastActivityAt(threadId);
+
+ const unread = await runInboxAction('UNREAD', threadId);
+
+ expect(
+ unread.body.data.updateAgentChatThreadInboxState[0].lastReadAt,
+ ).toBeNull();
+
+ const read = await runInboxAction('READ', threadId);
+
+ expect(
+ new Date(
+ read.body.data.updateAgentChatThreadInboxState[0].lastReadAt,
+ ).getTime(),
+ ).toBe(lastActivityAt.getTime());
+
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "lastActivityAt" = $2 WHERE id = $1`,
+ [threadId, new Date(lastActivityAt.getTime() - 60_000)],
+ );
+
+ const readAgain = await runInboxAction('READ', threadId);
+
+ expect(
+ new Date(
+ readAgain.body.data.updateAgentChatThreadInboxState[0].lastReadAt,
+ ).getTime(),
+ ).toBe(lastActivityAt.getTime());
+ });
+
+ it('snoozes only into the future and moves the thread back to the inbox', async () => {
+ const threadId = await createTestThread();
+ const pastSnooze = await runInboxAction('SNOOZE', threadId, {
+ snoozedUntil: new Date(Date.now() - 60_000).toISOString(),
+ });
+
+ expect(pastSnooze.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+
+ const snoozedUntil = buildFutureSnoozedUntil();
+ const snoozed = await runInboxAction('SNOOZE', threadId, { snoozedUntil });
+
+ expect(snoozed.body.errors).toBeUndefined();
+ expect(
+ snoozed.body.data.updateAgentChatThreadInboxState[0].archivedAt,
+ ).not.toBeNull();
+ expect(
+ new Date(
+ snoozed.body.data.updateAgentChatThreadInboxState[0].snoozedUntil,
+ ).getTime(),
+ ).toBe(new Date(snoozedUntil).getTime());
+
+ const moved = await runInboxAction('MOVE_TO_INBOX', threadId);
+
+ expect(moved.body.data.updateAgentChatThreadInboxState[0]).toMatchObject({
+ archivedAt: null,
+ snoozedUntil: null,
+ });
+ });
+
+ it('sends each change as a record event carrying what changed', async () => {
+ const eventSpy = spyOnParticipantEvents();
+ const threadId = await createTestThread();
+
+ await runInboxAction('UNREAD', threadId);
+ await runInboxAction('UNREAD', threadId);
+ await runInboxAction('ARCHIVE', threadId);
+
+ expect(findParticipantEvents(eventSpy, threadId)).toEqual([
+ { action: 'created', updatedFields: [] },
+ { action: 'updated', updatedFields: ['lastReadAt', 'updatedAt'] },
+ { action: 'updated', updatedFields: ['archivedAt', 'updatedAt'] },
+ ]);
+ });
+
+ it('lets only its member read a row, through the grant it is given', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ const janeParticipant = await findMyParticipant(threadId);
+ const jonyParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+ const ownerShares: { recordId: string; principalId: string }[] =
+ await global.testDataSource.query(
+ `SELECT "recordId", "principalId" FROM ${SCHEMA}."recordShare"
+ WHERE "recordId" = ANY($1) AND "rowCause" = 'OWNER'
+ ORDER BY "principalId"`,
+ [[janeParticipant!.id, jonyParticipant!.id]],
+ );
+ const jonyRecordIds = await listParticipantRecordIds(
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(ownerShares).toEqual(
+ expect.arrayContaining([
+ {
+ recordId: janeParticipant!.id,
+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ },
+ {
+ recordId: jonyParticipant!.id,
+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ },
+ ]),
+ );
+ expect(ownerShares).toHaveLength(2);
+ expect(jonyRecordIds).toContain(jonyParticipant!.id);
+ expect(jonyRecordIds).not.toContain(janeParticipant!.id);
+ });
+
+ it('ends a snooze once its time passes by moving the chat back to the inbox', async () => {
+ const threadId = await createTestThread();
+
+ await runInboxAction('SNOOZE', threadId, {
+ snoozedUntil: buildFutureSnoozedUntil(),
+ });
+
+ const snoozedUntil = new Date(Date.now() - 1000);
+
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThreadParticipant" SET "snoozedUntil" = $3
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE, snoozedUntil],
+ );
+
+ const eventSpy = spyOnParticipantEvents();
+
+ await getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).endSnooze({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadId,
+ snoozedUntil: snoozedUntil.toISOString(),
+ });
+
+ const [row]: { archivedAt: Date | null; snoozedUntil: Date | null }[] =
+ await global.testDataSource.query(
+ `SELECT "archivedAt", "snoozedUntil" FROM ${SCHEMA}."agentChatThreadParticipant"
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
+ );
+
+ // The snooze stays recorded, so the chat shows what brought it back
+ expect(row.archivedAt).toBeNull();
+ expect(row.snoozedUntil?.getTime()).toBe(snoozedUntil.getTime());
+ expect(findParticipantEvents(eventSpy, threadId)).toEqual([
+ { action: 'updated', updatedFields: ['archivedAt', 'updatedAt'] },
+ ]);
+ });
+
+ it('saves as ended a snooze whose time passed before it was saved', async () => {
+ const threadId = await createTestThread();
+ const snoozedUntil = new Date(Date.now() - 1000);
+
+ // The snooze was accepted while its time was still ahead, and its
+ // queued end already ran and found nothing to end
+ const [participant] =
+ await getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).updateInboxState({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadIds: [threadId],
+ action: AgentChatInboxAction.SNOOZE,
+ snoozedUntil,
+ });
+
+ expect(participant.archivedAt).toBeNull();
+ expect(new Date(participant.snoozedUntil!).getTime()).toBe(
+ snoozedUntil.getTime(),
+ );
+ });
+
+ it('waits for the database clock before ending a snooze', async () => {
+ const threadId = await createTestThread();
+ const snoozedUntil = buildFutureSnoozedUntil();
+
+ await runInboxAction('SNOOZE', threadId, { snoozedUntil });
+
+ const eventSpy = spyOnParticipantEvents();
+
+ await getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).endSnooze({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadId,
+ snoozedUntil,
+ });
+
+ expect(findParticipantEvents(eventSpy, threadId)).toEqual([]);
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ archivedAt: expect.any(String),
+ });
+ });
+
+ it('leaves alone a snooze the member replaced since', async () => {
+ const threadId = await createTestThread();
+
+ await runInboxAction('SNOOZE', threadId, {
+ snoozedUntil: buildFutureSnoozedUntil(),
+ });
+
+ const eventSpy = spyOnParticipantEvents();
+
+ await getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).endSnooze({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadId,
+ snoozedUntil: new Date(Date.now() - 1000).toISOString(),
+ });
+
+ expect(findParticipantEvents(eventSpy, threadId)).toEqual([]);
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ archivedAt: expect.any(String),
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-mentions.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-mentions.integration-spec.ts
new file mode 100644
index 00000000000..71fe4877332
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-mentions.integration-spec.ts
@@ -0,0 +1,507 @@
+import { randomUUID } from 'node:crypto';
+import { EventEmitter, once } from 'node:events';
+import { waitForBlockedDatabaseQueryOrThrow } from 'test/integration/ai/utils/wait-for-blocked-database-query-or-throw.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type AgentChatQueueService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-queue.service';
+import { type AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
+import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-history/enums/agent-message-role.enum';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import {
+ setUpChatThreadParticipantTests,
+ SCHEMA,
+ buildJonyThreadAccess,
+ buildFutureSnoozedUntil,
+ assign,
+ addParticipants,
+ findOpenThreadsSummary,
+ runInboxAction,
+ findMyParticipant,
+ setShareWithJony,
+} from 'test/integration/graphql/suites/chat-thread-participant/utils/chat-thread-participant-test.util';
+
+describe('Chat thread participant mentions through the authenticated API', () => {
+ const { createTestThread } = setUpChatThreadParticipantTests();
+
+ // Other tests' chats may stay open for the member, so counts are compared
+ // with what they were before
+ it('summarizes the open chats the member follows, from their own rows', async () => {
+ const before = await findOpenThreadsSummary();
+ const threadId = await createTestThread();
+
+ expect(await findOpenThreadsSummary()).toEqual(before);
+
+ await setShareWithJony(threadId, true);
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "pendingQuestionMessageId" = $2 WHERE id = $1`,
+ [threadId, randomUUID()],
+ );
+
+ // Being able to open a chat, reading it or marking it unread does not
+ // follow it
+ expect(await findOpenThreadsSummary()).toEqual(before);
+
+ for (const action of ['UNREAD', 'READ'] as const) {
+ await runInboxAction(action, threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(await findOpenThreadsSummary()).toEqual(before);
+ }
+
+ await runInboxAction('SUBSCRIBE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(await findOpenThreadsSummary()).toMatchObject({
+ openThreadCount: before.openThreadCount + 1,
+ unreadOpenThreadCount: before.unreadOpenThreadCount,
+ needsInputThreadCount: before.needsInputThreadCount + 1,
+ hasUnreadOpenThread: before.hasUnreadOpenThread,
+ });
+
+ await runInboxAction('UNREAD', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(await findOpenThreadsSummary()).toMatchObject({
+ openThreadCount: before.openThreadCount + 1,
+ unreadOpenThreadCount: before.unreadOpenThreadCount + 1,
+ hasUnreadOpenThread: true,
+ });
+
+ await runInboxAction('READ', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(await findOpenThreadsSummary()).toMatchObject({
+ openThreadCount: before.openThreadCount + 1,
+ unreadOpenThreadCount: before.unreadOpenThreadCount,
+ hasUnreadOpenThread: before.hasUnreadOpenThread,
+ });
+
+ await runInboxAction('UNREAD', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(await findOpenThreadsSummary()).toEqual(before);
+ });
+
+ it('follows a chat the member files as done, so new activity brings it back', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+ await runInboxAction('READ', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ isSubscribed: false, archivedAt: null });
+
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ isSubscribed: true, archivedAt: expect.any(String) });
+ });
+
+ it('flags the open chats the member was mentioned in or assigned that are unread', async () => {
+ const initialSummary = await findOpenThreadsSummary();
+ const mentionedThreadId = await createTestThread();
+ const assignedThreadId = await createTestThread();
+
+ await addParticipants(mentionedThreadId, [
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ ]);
+ await assign(assignedThreadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
+
+ expect(await findOpenThreadsSummary()).toMatchObject({
+ unreadOpenThreadCount: initialSummary.unreadOpenThreadCount + 2,
+ hasUnreadMentionThread: true,
+ hasUnreadAssignedThread: true,
+ });
+
+ const unsubscribed = await runInboxAction(
+ 'UNSUBSCRIBE',
+ mentionedThreadId,
+ { token: APPLE_JONY_MEMBER_ACCESS_TOKEN },
+ );
+
+ expect(unsubscribed.body.errors).toBeUndefined();
+
+ await runInboxAction('ARCHIVE', assignedThreadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ const before = await findOpenThreadsSummary();
+
+ expect(before.unreadOpenThreadCount).toBe(
+ initialSummary.unreadOpenThreadCount,
+ );
+
+ // Activity brings back a chat filed under done, but not one the member left
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThread" SET "lastActivityAt" = clock_timestamp() WHERE id = ANY($1)`,
+ [[mentionedThreadId, assignedThreadId]],
+ );
+
+ expect(await findOpenThreadsSummary()).toMatchObject({
+ openThreadCount: before.openThreadCount + 1,
+ unreadOpenThreadCount: before.unreadOpenThreadCount + 1,
+ });
+ });
+
+ it('resolves the mention when the member reads the chat and keeps it when they mark it unread', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ for (const action of ['READ', 'UNREAD']) {
+ const response = await runInboxAction(action, threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+ const participant = response.body.data.updateAgentChatThreadInboxState[0];
+
+ expect(response.body.errors).toBeUndefined();
+ expect(participant.mentionsResolvedAt).toBe(participant.lastMentionedAt);
+ }
+ });
+
+ it('preserves unresolved mentions while marking unread and snoozing', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ for (const action of ['UNREAD', 'SNOOZE']) {
+ const response = await runInboxAction(action, threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ snoozedUntil:
+ action === 'SNOOZE' ? buildFutureSnoozedUntil() : undefined,
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(
+ response.body.data.updateAgentChatThreadInboxState[0],
+ ).toMatchObject({
+ lastMentionedAt: expect.any(String),
+ mentionsResolvedAt: null,
+ });
+ }
+ });
+
+ it('resolves only the member who successfully sends a reply', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ await addParticipants(
+ threadId,
+ [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ );
+
+ await getAppProviderByClassName<AgentChatService>(
+ 'AgentChatService',
+ ).addMessageAndResolveMention({
+ ...buildJonyThreadAccess(threadId),
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ uiMessage: {
+ role: AgentMessageRole.USER,
+ parts: [{ type: 'text', text: 'I have handled this.' }],
+ },
+ });
+
+ const repliedParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(repliedParticipant!.mentionsResolvedAt).toBe(
+ repliedParticipant!.lastMentionedAt,
+ );
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ lastMentionedAt: expect.any(String),
+ mentionsResolvedAt: null,
+ });
+ });
+
+ it('keeps a mention resolved after Done until an explicit new mention arrives', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ const doneParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(doneParticipant!.mentionsResolvedAt).toBe(
+ doneParticipant!.lastMentionedAt,
+ );
+
+ await getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ).recordThreadActivity({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ threadId,
+ text: 'An unrelated update',
+ });
+ await runInboxAction('MOVE_TO_INBOX', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({
+ lastMentionedAt: doneParticipant!.lastMentionedAt,
+ mentionsResolvedAt: doneParticipant!.mentionsResolvedAt,
+ });
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const mentionedAgain = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(
+ new Date(mentionedAgain!.lastMentionedAt!).getTime(),
+ ).toBeGreaterThan(new Date(mentionedAgain!.mentionsResolvedAt!).getTime());
+ });
+
+ it('resolves a mention when the member unsubscribes', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ await runInboxAction('UNSUBSCRIBE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ const unsubscribedParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(unsubscribedParticipant).toMatchObject({
+ isSubscribed: false,
+ mentionsResolvedAt: unsubscribedParticipant!.lastMentionedAt,
+ });
+ });
+
+ describe('queued replies to a mention', () => {
+ const queueReply = (threadId: string) =>
+ getAppProviderByClassName<AgentChatQueueService>(
+ 'AgentChatQueueService',
+ ).queueMessage({
+ ...buildJonyThreadAccess(threadId),
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ text: 'On it',
+ });
+
+ const deleteQueuedReply = (messageId: string) =>
+ getAppProviderByClassName<AgentChatQueueService>(
+ 'AgentChatQueueService',
+ ).deleteQueuedMessage({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ messageId,
+ });
+
+ it('resolves the mention when the member queues a reply and keeps it after the reply is deleted', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const reply = await queueReply(threadId);
+ const repliedParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(repliedParticipant!.mentionsResolvedAt).toBe(
+ repliedParticipant!.lastMentionedAt,
+ );
+
+ await deleteQueuedReply(reply.id);
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({
+ mentionsResolvedAt: repliedParticipant!.lastMentionedAt,
+ });
+ });
+
+ it('queues a reply while another write of the member locks the chat', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const writeEvents = new EventEmitter();
+ const writeStarted = once(writeEvents, 'started');
+ const writeResumed = once(writeEvents, 'resumed');
+ const write =
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).resolveMention({
+ ...buildJonyThreadAccess(threadId),
+ writeResponse: async ({ manager, table }) => {
+ const [{ backendProcessId }] = await manager.query<
+ { backendProcessId: number }[]
+ >('SELECT pg_backend_pid() AS "backendProcessId"');
+
+ writeEvents.emit('started', backendProcessId);
+ await writeResumed;
+ await manager.query(
+ `SELECT id FROM ${table('agentChatThread')} WHERE id = $1 FOR UPDATE`,
+ [threadId],
+ );
+ },
+ });
+
+ const [blockingProcessId] = await writeStarted;
+ const reply = queueReply(threadId);
+
+ await waitForBlockedDatabaseQueryOrThrow(blockingProcessId);
+ writeEvents.emit('resumed');
+
+ await expect(Promise.all([write, reply])).resolves.toEqual([
+ undefined,
+ expect.objectContaining({ threadId }),
+ ]);
+ });
+ });
+
+ it('delivers app recipients without creating or clearing an explicit mention', async () => {
+ const threadId = await createTestThread();
+ const threadService = getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ );
+ const delivery = {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadId,
+ participantWorkspaceMemberIds: [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY],
+ };
+
+ await threadService.deliverToParticipants(delivery);
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({
+ isSubscribed: true,
+ lastReadAt: null,
+ lastMentionedAt: null,
+ mentionsResolvedAt: null,
+ });
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const mentionedParticipant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ await threadService.deliverToParticipants(delivery);
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({
+ lastMentionedAt: mentionedParticipant!.lastMentionedAt,
+ mentionsResolvedAt: null,
+ });
+ });
+
+ it('rolls mention resolution back when a response cannot be recorded', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ await expect(
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).resolveMention({
+ ...buildJonyThreadAccess(threadId),
+ writeResponse: async () => {
+ throw new Error('The response is invalid');
+ },
+ }),
+ ).rejects.toThrow('The response is invalid');
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ mentionsResolvedAt: null });
+ });
+
+ it('preserves a newer mention when an older response finishes first', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const responseEvents = new EventEmitter();
+ const responseStarted = once(responseEvents, 'started');
+ const responseFinished = once(responseEvents, 'finished');
+ const participantService =
+ getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ );
+ const response = participantService.resolveMention({
+ ...buildJonyThreadAccess(threadId),
+ writeResponse: async () => {
+ responseEvents.emit('started');
+ await responseFinished;
+ },
+ });
+
+ await responseStarted;
+
+ const laterMention = participantService.markAsMentioned(
+ buildJonyThreadAccess(threadId),
+ );
+
+ responseEvents.emit('finished');
+ await Promise.all([response, laterMention]);
+
+ const participant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(new Date(participant!.lastMentionedAt!).getTime()).toBeGreaterThan(
+ new Date(participant!.mentionsResolvedAt!).getTime(),
+ );
+ });
+
+ it('orders a new mention after the resolved cursor at millisecond precision', async () => {
+ const threadId = await createTestThread();
+ const resolvedAt = new Date(Date.now() + 60_000).toISOString();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ await global.testDataSource.query(
+ `UPDATE ${SCHEMA}."agentChatThreadParticipant"
+ SET "lastMentionedAt" = $3, "mentionsResolvedAt" = $3
+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,
+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY, resolvedAt],
+ );
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const participant = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(new Date(participant!.lastMentionedAt!).getTime()).toBe(
+ new Date(resolvedAt).getTime() + 1,
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-sharing-and-assignment.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-sharing-and-assignment.integration-spec.ts
new file mode 100644
index 00000000000..094c26d5c84
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/chat-thread-participant-sharing-and-assignment.integration-spec.ts
@@ -0,0 +1,472 @@
+import { RecordShareAccessLevel } from 'twenty-shared/types';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { type AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';
+import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import {
+ setUpChatThreadParticipantTests,
+ SCHEMA,
+ buildFutureSnoozedUntil,
+ assign,
+ readAssigneeId,
+ addParticipants,
+ runInboxAction,
+ findThreadParticipants,
+ findMyParticipant,
+ readThreadActivity,
+ setShareWithMember,
+ setShareWithJony,
+} from 'test/integration/graphql/suites/chat-thread-participant/utils/chat-thread-participant-test.util';
+
+describe('Chat thread participant sharing, subscription and assignment through the authenticated API', () => {
+ const { createTestThread } = setUpChatThreadParticipantTests();
+
+ it('brings the thread back and marks it read for the member who writes in it', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+ await runInboxAction('ARCHIVE', threadId);
+ await runInboxAction('UNREAD', threadId);
+
+ const { lastActivityAt } =
+ await getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).recordMemberActivity({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadId,
+ text: 'Can you check the Stripe renewal?',
+ });
+
+ const owner = await findMyParticipant(threadId);
+
+ expect(lastActivityAt).not.toBeNull();
+ expect(await readThreadActivity(threadId)).toMatchObject({
+ lastMessageText: 'Can you check the Stripe renewal?',
+ lastMessageSenderWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ writerWorkspaceMemberIds: [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
+ });
+ expect(owner).toMatchObject({ archivedAt: null, snoozedUntil: null });
+ expect(new Date(owner!.lastReadAt!).getTime()).toBe(
+ lastActivityAt!.getTime(),
+ );
+
+ // The other member archived before this activity, so it is back in their
+ // inbox and unread, without anyone touching their row
+ const member = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(new Date(member!.archivedAt!).getTime()).toBeLessThan(
+ lastActivityAt!.getTime(),
+ );
+ expect(member!.lastReadAt).toBeNull();
+ });
+
+ it('brings a thread back for its members on activity no member wrote', async () => {
+ const threadId = await createTestThread();
+ const archived = await runInboxAction('ARCHIVE', threadId);
+
+ expect(archived.body.errors).toBeUndefined();
+ expect(
+ archived.body.data.updateAgentChatThreadInboxState[0].archivedAt,
+ ).not.toBeNull();
+
+ await getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ).recordThreadActivity({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ threadId,
+ text: 'The renewal is due next week.',
+ });
+
+ const owner = await findMyParticipant(threadId);
+ const { lastActivityAt, ...lastMessage } =
+ await readThreadActivity(threadId);
+
+ expect(lastMessage).toMatchObject({
+ lastMessageText: 'The renewal is due next week.',
+ lastMessageSenderWorkspaceMemberId: null,
+ });
+
+ expect(new Date(owner!.archivedAt!).getTime()).toBeLessThan(
+ lastActivityAt.getTime(),
+ );
+ expect(new Date(owner!.lastReadAt!).getTime()).toBeLessThan(
+ lastActivityAt.getTime(),
+ );
+ });
+
+ it("only lists the caller's own rows", async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ const rows: { workspaceMemberId: string }[] =
+ await global.testDataSource.query(
+ `SELECT "workspaceMemberId" FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = $1`,
+ [threadId],
+ );
+
+ expect(rows).toHaveLength(2);
+ expect(
+ await findThreadParticipants(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toEqual([
+ expect.objectContaining({
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ }),
+ ]);
+ });
+
+ it('stops listing a thread once the member loses access to it', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toBeDefined();
+
+ await setShareWithJony(threadId, false);
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toBeUndefined();
+ });
+
+ it('shares the thread with a mentioned member and brings it to their inbox unread', async () => {
+ const threadId = await createTestThread();
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toBeUndefined();
+
+ expect(
+ await addParticipants(threadId, [
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ ]),
+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ lastReadAt: null, archivedAt: null, snoozedUntil: null });
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ // Editors can mention others too; the owner keeps following as owner
+ expect(
+ await addParticipants(
+ threadId,
+ [WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ ),
+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JANE]);
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ lastReadAt: null,
+ });
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ });
+
+ it('brings the thread back unread for a participant who had read and archived it', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ await runInboxAction('READ', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+ await runInboxAction('ARCHIVE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ lastReadAt: null, archivedAt: null, snoozedUntil: null });
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ });
+
+ it('refuses a member who can only read the thread', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+
+ await expect(
+ addParticipants(
+ threadId,
+ [WORKSPACE_MEMBER_DATA_SEED_IDS.TIM],
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ ),
+ ).rejects.toMatchObject({ code: AiExceptionCode.THREAD_NOT_FOUND });
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],
+ ).toEqual([]);
+ });
+
+ it('leaves out a member who could only read the thread when the sender cannot share it', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithMember({
+ threadId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ enabled: true,
+ });
+ await setShareWithMember({
+ threadId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ accessLevel: RecordShareAccessLevel.READ,
+ enabled: true,
+ });
+
+ expect(
+ await addParticipants(
+ threadId,
+ [WORKSPACE_MEMBER_DATA_SEED_IDS.TIM],
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ ),
+ ).toEqual([]);
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],
+ ).toEqual([]);
+ });
+
+ it('keeps an unsubscribed chat done through new activity', async () => {
+ const threadId = await createTestThread();
+ const unsubscribed = await runInboxAction('UNSUBSCRIBE', threadId);
+
+ expect(unsubscribed.body.errors).toBeUndefined();
+ expect(
+ unsubscribed.body.data.updateAgentChatThreadInboxState[0],
+ ).toMatchObject({ isSubscribed: false, snoozedUntil: null });
+ expect(
+ unsubscribed.body.data.updateAgentChatThreadInboxState[0].archivedAt,
+ ).not.toBeNull();
+
+ await getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ).recordThreadActivity({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ threadId,
+ text: 'The renewal went through',
+ });
+
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ isSubscribed: false,
+ });
+
+ // Subscribing again leaves the chat where it is until something happens
+ const subscribed = await runInboxAction('SUBSCRIBE', threadId);
+
+ expect(subscribed.body.errors).toBeUndefined();
+ expect(
+ subscribed.body.data.updateAgentChatThreadInboxState[0],
+ ).toMatchObject({
+ isSubscribed: true,
+ archivedAt:
+ unsubscribed.body.data.updateAgentChatThreadInboxState[0].archivedAt,
+ });
+ });
+
+ it('follows the chat again for a member who reopens, snoozes or writes in it', async () => {
+ const threadId = await createTestThread();
+
+ await runInboxAction('UNSUBSCRIBE', threadId);
+ await runInboxAction('MOVE_TO_INBOX', threadId);
+
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ isSubscribed: true,
+ archivedAt: null,
+ });
+
+ await runInboxAction('UNSUBSCRIBE', threadId);
+ await runInboxAction('SNOOZE', threadId, {
+ snoozedUntil: buildFutureSnoozedUntil(),
+ });
+
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ isSubscribed: true,
+ });
+
+ await runInboxAction('UNSUBSCRIBE', threadId);
+ await getAppProviderByClassName<AgentChatThreadParticipantService>(
+ 'AgentChatThreadParticipantService',
+ ).recordMemberActivity({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadId,
+ text: 'Back on this one',
+ });
+
+ expect(await findMyParticipant(threadId)).toMatchObject({
+ isSubscribed: true,
+ archivedAt: null,
+ });
+ });
+
+ it('follows the chat again and records the mention for a mentioned member who had unsubscribed', async () => {
+ const threadId = await createTestThread();
+
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const firstMention = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(firstMention).toMatchObject({ isSubscribed: true });
+ expect(firstMention!.lastMentionedAt).not.toBeNull();
+
+ await runInboxAction('UNSUBSCRIBE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+ await addParticipants(threadId, [WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+
+ const secondMention = await findMyParticipant(
+ threadId,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(secondMention).toMatchObject({
+ isSubscribed: true,
+ archivedAt: null,
+ lastReadAt: null,
+ });
+ expect(new Date(secondMention!.lastMentionedAt!).getTime()).toBeGreaterThan(
+ new Date(firstMention!.lastMentionedAt!).getTime(),
+ );
+ });
+
+ it('refuses to change the subscription of a member who cannot read the chat', async () => {
+ const threadId = await createTestThread();
+ const response = await runInboxAction('UNSUBSCRIBE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
+ });
+
+ it('assigns a chat to a member who could not read it, who then finds it unread in their inbox', async () => {
+ const threadId = await createTestThread();
+ const response = await assign(
+ threadId,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+ expect(await readAssigneeId(threadId)).toBe(
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ );
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({
+ isSubscribed: true,
+ archivedAt: null,
+ lastReadAt: null,
+ });
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds,
+ ).toEqual([WORKSPACE_MEMBER_DATA_SEED_IDS.JONY]);
+ });
+
+ it('keeps a chat read for a member who assigns it to themselves', async () => {
+ const threadId = await createTestThread();
+
+ await runInboxAction('ARCHIVE', threadId);
+
+ const response = await assign(
+ threadId,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ const participant = await findMyParticipant(threadId);
+
+ expect(participant).toMatchObject({ archivedAt: null, isSubscribed: true });
+ expect(participant!.lastReadAt).not.toBeNull();
+ expect(
+ (await readThreadActivity(threadId)).writerWorkspaceMemberIds ?? [],
+ ).toEqual([]);
+ });
+
+ it('keeps the former assignee following the chat once it is unassigned', async () => {
+ const threadId = await createTestThread();
+
+ await assign(threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
+
+ const response = await assign(threadId, null);
+
+ expect(response.body.errors).toBeUndefined();
+ expect(await readAssigneeId(threadId)).toBeNull();
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ isSubscribed: true });
+ });
+
+ it('refuses to unsubscribe the assignee', async () => {
+ const threadId = await createTestThread();
+
+ await assign(threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
+
+ const response = await runInboxAction('UNSUBSCRIBE', threadId, {
+ token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ });
+
+ expect(response.body.errors[0].extensions.code).toBe('CONFLICT');
+ expect(
+ await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
+ ).toMatchObject({ isSubscribed: true });
+ });
+
+ it('refuses to assign a chat for a member who can only read it', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithJony(threadId, true);
+
+ const response = await assign(
+ threadId,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('NOT_FOUND');
+ expect(await readAssigneeId(threadId)).toBeNull();
+ });
+
+ it('refuses an assignee who cannot reply when the caller cannot share the chat', async () => {
+ const threadId = await createTestThread();
+
+ await setShareWithMember({
+ threadId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ enabled: true,
+ });
+
+ const response = await assign(
+ threadId,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(response.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');
+ expect(await readAssigneeId(threadId)).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/utils/chat-thread-participant-test.util.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/utils/chat-thread-participant-test.util.ts
new file mode 100644
index 00000000000..749184f22de
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant/utils/chat-thread-participant-test.util.ts
@@ -0,0 +1,352 @@
+import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
+import { randomUUID } from 'node:crypto';
+import { parse } from 'graphql';
+import {
+ type ObjectRecordCreateEvent,
+ type ObjectRecordUpdateEvent,
+} from 'twenty-shared/database-events';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import {
+ FeatureFlagKey,
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+} from 'twenty-shared/types';
+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { setManualRecordShare } from 'test/integration/utils/set-manual-record-share.util';
+import { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { type WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+export const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+export const buildJonyThreadAccess = (threadId: string) => ({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ threadId,
+});
+
+const PARTICIPANT_FIELDS =
+ 'id threadId lastReadAt archivedAt snoozedUntil isSubscribed lastMentionedAt mentionsResolvedAt updatedAt';
+
+const UPDATE_INBOX_STATE = parse(
+ `mutation UpdateInboxState($threadIds: [UUID!]!, $action: AgentChatInboxAction!, $snoozedUntil: DateTime) { updateAgentChatThreadInboxState(threadIds: $threadIds, action: $action, snoozedUntil: $snoozedUntil) { ${PARTICIPANT_FIELDS} } }`,
+);
+
+// Outlasts any test, yet within the delay the test queue fast-forwards
+export const buildFutureSnoozedUntil = () =>
+ new Date(Date.now() + 30_000).toISOString();
+
+const ASSIGN = parse(
+ `mutation Assign($threadId: UUID!, $assigneeWorkspaceMemberId: UUID) { assignAgentChatThread(threadId: $threadId, assigneeWorkspaceMemberId: $assigneeWorkspaceMemberId) }`,
+);
+
+export const assign = (
+ threadId: string,
+ assigneeWorkspaceMemberId: string | null,
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+) =>
+ makeMetadataApiRequest(
+ { query: ASSIGN, variables: { threadId, assigneeWorkspaceMemberId } },
+ token,
+ );
+
+export const readAssigneeId = async (
+ threadId: string,
+): Promise<string | null> => {
+ const [{ assigneeId }]: { assigneeId: string | null }[] =
+ await global.testDataSource.query(
+ `SELECT "assigneeId" FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,
+ [threadId],
+ );
+
+ return assigneeId;
+};
+
+export const addParticipants = (
+ threadId: string,
+ participantWorkspaceMemberIds: string[],
+ workspaceMemberId: string = WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+) =>
+ getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ).mentionParticipants({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId,
+ threadId,
+ participantWorkspaceMemberIds,
+ });
+
+type Participant = {
+ id: string;
+ threadId: string;
+ lastReadAt: string | null;
+ archivedAt: string | null;
+ snoozedUntil: string | null;
+ isSubscribed: boolean;
+ lastMentionedAt: string | null;
+ mentionsResolvedAt: string | null;
+};
+
+const OPEN_THREADS_SUMMARY = parse(
+ `query OpenThreadsSummary { agentChatOpenThreadsSummary { openThreadCount unreadOpenThreadCount needsInputThreadCount hasUnreadOpenThread hasUnreadMentionThread hasUnreadAssignedThread } }`,
+);
+
+type OpenThreadsSummary = {
+ openThreadCount: number;
+ unreadOpenThreadCount: number;
+ needsInputThreadCount: number;
+ hasUnreadOpenThread: boolean;
+ hasUnreadMentionThread: boolean;
+ hasUnreadAssignedThread: boolean;
+};
+
+export const findOpenThreadsSummary = async (
+ token: string = APPLE_JONY_MEMBER_ACCESS_TOKEN,
+): Promise<OpenThreadsSummary> => {
+ const response = await makeMetadataApiRequest(
+ { query: OPEN_THREADS_SUMMARY },
+ token,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.agentChatOpenThreadsSummary;
+};
+
+export const runInboxAction = (
+ action: string,
+ threadIds: string | string[],
+ {
+ token = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ snoozedUntil,
+ }: { token?: string; snoozedUntil?: string } = {},
+) =>
+ makeMetadataApiRequest(
+ {
+ query: UPDATE_INBOX_STATE,
+ variables: { threadIds: [threadIds].flat(), action, snoozedUntil },
+ },
+ token,
+ );
+
+// Read the way the inbox does: rows come with the threads the caller can read
+export const findThreadParticipants = async (
+ threadId: string,
+ token: string,
+): Promise<(Participant & { workspaceMemberId: string })[] | undefined> => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'agentChatThread',
+ objectMetadataPluralName: 'agentChatThreads',
+ gqlFields: `id participants { edges { node { ${PARTICIPANT_FIELDS} workspaceMemberId } } }`,
+ filter: { id: { eq: threadId } },
+ }),
+ token,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ const [thread] = response.body.data.agentChatThreads.edges;
+
+ return thread?.node.participants.edges.map(
+ ({ node }: { node: Participant & { workspaceMemberId: string } }) => node,
+ );
+};
+
+export const findMyParticipant = async (
+ threadId: string,
+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,
+): Promise<Participant | undefined> => {
+ const workspaceMemberId =
+ token === APPLE_JONY_MEMBER_ACCESS_TOKEN
+ ? WORKSPACE_MEMBER_DATA_SEED_IDS.JONY
+ : WORKSPACE_MEMBER_DATA_SEED_IDS.JANE;
+
+ return (await findThreadParticipants(threadId, token))?.find(
+ (participant) => participant.workspaceMemberId === workspaceMemberId,
+ );
+};
+
+export const readThreadActivity = async (threadId: string) => {
+ const [row]: {
+ lastActivityAt: Date;
+ lastMessageText: string | null;
+ lastMessageSenderWorkspaceMemberId: string | null;
+ writerWorkspaceMemberIds: string[] | null;
+ }[] = await global.testDataSource.query(
+ `SELECT "lastActivityAt", "lastMessageText", "lastMessageSenderWorkspaceMemberId", "writerWorkspaceMemberIds"
+ FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,
+ [threadId],
+ );
+
+ return row;
+};
+
+export const readLastActivityAt = async (threadId: string): Promise<Date> =>
+ (await readThreadActivity(threadId)).lastActivityAt;
+
+const createThread = async (): Promise<string> => {
+ const threadId = randomUUID();
+
+ await getAppProviderByClassName<AgentChatThreadService>(
+ 'AgentChatThreadService',
+ ).createThread({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ id: threadId,
+ title: 'Participant state',
+ });
+
+ return threadId;
+};
+
+export const spyOnParticipantEvents = () =>
+ jest.spyOn(
+ getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter'),
+ 'emitDatabaseBatchEvent',
+ );
+
+export const findParticipantEvents = (
+ eventSpy: ReturnType<typeof spyOnParticipantEvents>,
+ threadId: string,
+) =>
+ eventSpy.mock.calls
+ .map(([batchEvent]) => batchEvent)
+ .filter(
+ (batchEvent) =>
+ batchEvent?.objectMetadataNameSingular === 'agentChatThreadParticipant',
+ )
+ .flatMap((batchEvent) =>
+ (
+ batchEvent!.events as (
+ | ObjectRecordCreateEvent<Participant>
+ | ObjectRecordUpdateEvent<Participant>
+ )[]
+ )
+ .filter(({ properties }) => properties.after.threadId === threadId)
+ .map(({ properties }) => ({
+ action: batchEvent!.action,
+ updatedFields:
+ 'updatedFields' in properties ? properties.updatedFields : [],
+ })),
+ );
+
+export const listParticipantRecordIds = async (
+ token: string,
+): Promise<string[]> => {
+ const response = await makeGraphqlApiRequest(
+ findManyOperationFactory({
+ objectMetadataSingularName: 'agentChatThreadParticipant',
+ objectMetadataPluralName: 'agentChatThreadParticipants',
+ gqlFields: 'id',
+ first: 200,
+ }),
+ token,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+
+ return response.body.data.agentChatThreadParticipants.edges.map(
+ ({ node }: { node: { id: string } }) => node.id,
+ );
+};
+
+type ManualShare = {
+ threadId: string;
+ workspaceMemberId: string;
+ accessLevel: RecordShareAccessLevel;
+};
+
+// Destroying a chat keeps its grants, so every grant a test enables is
+// disabled again after it
+const enabledManualShares: ManualShare[] = [];
+
+export const setShareWithMember = async ({
+ threadId,
+ workspaceMemberId,
+ accessLevel,
+ enabled,
+}: {
+ threadId: string;
+ workspaceMemberId: string;
+ accessLevel: RecordShareAccessLevel;
+ enabled: boolean;
+}) => {
+ if (enabled) {
+ enabledManualShares.push({ threadId, workspaceMemberId, accessLevel });
+ }
+
+ const { flatObjectMetadataMaps } =
+ await getAppProviderByClassName<WorkspaceCacheService>(
+ 'WorkspaceCacheService',
+ ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, ['flatObjectMetadataMaps']);
+
+ await setManualRecordShare({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ share: {
+ objectMetadataId:
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier
+ ]!.id,
+ recordId: threadId,
+ principalId: workspaceMemberId,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel,
+ sourceId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ },
+ enabled,
+ });
+};
+
+export const setShareWithJony = (threadId: string, enabled: boolean) =>
+ setShareWithMember({
+ threadId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ accessLevel: RecordShareAccessLevel.READ,
+ enabled,
+ });
+
+const setRecordSharingEnabled = (value: boolean) =>
+ updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED,
+ value,
+ expectToFail: false,
+ });
+
+export const setUpChatThreadParticipantTests = () => {
+ beforeAll(() => setRecordSharingEnabled(true));
+
+ afterAll(() => setRecordSharingEnabled(false));
+
+ const createdThreadIds: string[] = [];
+
+ const createTestThread = async () => {
+ const threadId = await createThread();
+
+ createdThreadIds.push(threadId);
+
+ return threadId;
+ };
+
+ afterEach(async () => {
+ jest.restoreAllMocks();
+
+ for (const manualShare of enabledManualShares.splice(0)) {
+ await setShareWithMember({ ...manualShare, enabled: false });
+ }
+ // Mentions share chats with Jony from the code under test
+ for (const threadId of createdThreadIds.splice(0)) {
+ await setShareWithJony(threadId, false);
+ await destroyAgentChatThread({ threadId });
+ }
+ });
+
+ return { createTestThread };
+};