Skip to content

The open alternative to Salesforce, designed for AI.

Follow shared chats only when taking part in them, and track what members read (#27786)

Félix Malfait2f9bd3aa6bcf
diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx
index 13d92247885..2fe3a8e600c 100644
--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx
@@ -94,7 +94,9 @@ export const AgentChatThreadMarkAsReadEffect = () => {
const isKeptUnread = visit?.threadId === threadId && visit.isKeptUnread;
- if (isUnread && !isKeptUnread) {
+ // Opening a chat the member does not participate in yet starts tracking
+ // it for them, so later activity in it reads as unread
+ if ((isUnread || !isDefined(participant)) && !isKeptUnread) {
void updateAgentChatThreadInboxState({
threadIds: [threadId],
action: AgentChatInboxAction.READ,
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx
index 6a3f9c69519..b2b5a7f00c0 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx
@@ -70,6 +70,24 @@ describe('AgentChatThreadMarkAsReadEffect', () => {
});
});
+ it('starts tracking a thread the member opens without participating in it', () => {
+ jotaiStore.set(agentChatThreadParticipantsState.atom, {});
+
+ renderChatView();
+
+ expect(updateAgentChatThreadInboxState).toHaveBeenCalledTimes(1);
+ expect(updateAgentChatThreadInboxState).toHaveBeenCalledWith({
+ threadIds: [THREAD_ID],
+ action: 'READ',
+ });
+ expect(jotaiStore.get(agentChatThreadVisitState.atom)).toEqual({
+ threadId: THREAD_ID,
+ isUnread: false,
+ lastReadAt: null,
+ isKeptUnread: false,
+ });
+ });
+
it('keeps the visit while another view still shows the thread', () => {
const sidePanelView = renderChatView();
const recordPageView = renderChatView();
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx
index f567f4fe325..8ae08024b7f 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx
@@ -4,6 +4,7 @@ import { type ReactNode } from 'react';
import { useLeaveRemovedAiChatThread } from '@/ai/hooks/useLeaveRemovedAiChatThread';
import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';
import { agentChatInputIsEmptySelector } from '@/ai/states/selectors/agentChatInputIsEmptySelector';
import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';
import { newAiChatThreadIdState } from '@/ai/states/newAiChatThreadIdState';
@@ -39,6 +40,17 @@ const buildChat = (id: string, updatedAt: string): AgentChatThreadRecord => ({
deletedAt: null,
});
+const buildFollowedParticipant = (threadId: string) => ({
+ id: `participant-${threadId}`,
+ threadId,
+ lastReadAt: null,
+ archivedAt: null,
+ snoozedUntil: null,
+ isSubscribed: true,
+ lastMentionedAt: null,
+ updatedAt: '2026-09-20T00:00:00.000Z',
+});
+
const Wrapper = ({ children }: { children: ReactNode }) => (
<JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
);
@@ -65,6 +77,15 @@ describe('useLeaveRemovedAiChatThread', () => {
buildChat(OLDER_CHAT_ID, '2026-09-01T00:00:00.000Z'),
buildChat(RECENT_CHAT_ID, '2026-09-20T00:00:00.000Z'),
]);
+ jotaiStore.set(
+ agentChatThreadParticipantsState.atom,
+ Object.fromEntries(
+ [OLDER_CHAT_ID, RECENT_CHAT_ID].map((threadId) => [
+ threadId,
+ buildFollowedParticipant(threadId),
+ ]),
+ ),
+ );
jotaiStore.set(agentChatDraftsByThreadIdState.atom, {
[RECENT_CHAT_ID]: 'Pending question',
});
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useUpdateAgentChatThreadInboxState.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useUpdateAgentChatThreadInboxState.test.tsx
index 1d13eaaf955..cfa27c13254 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useUpdateAgentChatThreadInboxState.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useUpdateAgentChatThreadInboxState.test.tsx
@@ -59,7 +59,7 @@ describe('useUpdateAgentChatThreadInboxState', () => {
jest.clearAllMocks();
});
- it('reads a thread up to its last activity before the server answers', async () => {
+ it('reads a thread up to its last activity before the server answers, without following it', async () => {
mutate.mockReturnValue(new Promise(() => undefined));
const { result, store } = renderUpdateInboxState();
@@ -77,7 +77,7 @@ describe('useUpdateAgentChatThreadInboxState', () => {
lastReadAt: LAST_ACTIVITY_AT,
archivedAt: null,
snoozedUntil: null,
- isSubscribed: true,
+ isSubscribed: false,
});
});
@@ -94,7 +94,10 @@ describe('useUpdateAgentChatThreadInboxState', () => {
const participants = store.get(agentChatThreadParticipantsState.atom);
- expect(participants?.[THREAD_ID]?.archivedAt).toEqual(expect.any(String));
+ expect(participants?.[THREAD_ID]).toMatchObject({
+ archivedAt: expect.any(String),
+ isSubscribed: true,
+ });
expect(participants?.[OTHER_THREAD_ID]?.archivedAt).toEqual(
expect.any(String),
);
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatThreadInboxStatusFamilySelector.test.ts b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatThreadInboxStatusFamilySelector.test.ts
index 79b40f88893..e3849ec5b81 100644
--- a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatThreadInboxStatusFamilySelector.test.ts
+++ b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatThreadInboxStatusFamilySelector.test.ts
@@ -26,6 +26,19 @@ const buildStore = () => {
return store;
};
+const UNREAD_PARTICIPANT = {
+ [THREAD_ID]: {
+ id: 'participant',
+ threadId: THREAD_ID,
+ lastReadAt: null,
+ archivedAt: null,
+ snoozedUntil: null,
+ isSubscribed: true,
+ lastMentionedAt: null,
+ updatedAt: LAST_ACTIVITY_AT,
+ },
+};
+
const isUnread = (store: ReturnType<typeof createStore>) =>
store.get(agentChatThreadInboxStatusFamilySelector.selectorFamily(THREAD_ID))
.isUnread;
@@ -34,11 +47,19 @@ describe('agentChatThreadInboxStatusFamilySelector', () => {
it('reads a stored thread against the member state', () => {
const store = buildStore();
- store.set(agentChatThreadParticipantsState.atom, {});
+ store.set(agentChatThreadParticipantsState.atom, UNREAD_PARTICIPANT);
expect(isUnread(store)).toBe(true);
});
+ it('never reads as unread for a member who does not participate', () => {
+ const store = buildStore();
+
+ store.set(agentChatThreadParticipantsState.atom, {});
+
+ expect(isUnread(store)).toBe(false);
+ });
+
it('never reads as unread before the member state loads', () => {
expect(isUnread(buildStore())).toBe(false);
});
@@ -46,7 +67,7 @@ describe('agentChatThreadInboxStatusFamilySelector', () => {
it('never reads the thread on screen as unread, unless the member kept it unread', () => {
const store = buildStore();
- store.set(agentChatThreadParticipantsState.atom, {});
+ store.set(agentChatThreadParticipantsState.atom, UNREAD_PARTICIPANT);
store.set(agentChatThreadVisitState.atom, {
threadId: THREAD_ID,
isUnread: true,
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts
index e0853029370..6015ea8d2d3 100644
--- a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts
+++ b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts
@@ -45,7 +45,17 @@ const THREADS: {
snoozedUntil: '2026-10-02T09:00:00.000Z',
},
},
- { id: 'unread', deletedAt: null, participant: undefined },
+ {
+ id: 'unread',
+ deletedAt: null,
+ participant: { ...READ, lastReadAt: null, archivedAt: null },
+ },
+ { id: 'not-followed', deletedAt: null, participant: undefined },
+ {
+ id: 'opened-not-followed',
+ deletedAt: null,
+ participant: { ...READ, archivedAt: null, isSubscribed: false },
+ },
{
id: 'snoozed',
deletedAt: null,
diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatThreadInboxStatus.ts b/packages/twenty-front/src/modules/ai/types/AgentChatThreadInboxStatus.ts
index 720396002fc..c01ee178209 100644
--- a/packages/twenty-front/src/modules/ai/types/AgentChatThreadInboxStatus.ts
+++ b/packages/twenty-front/src/modules/ai/types/AgentChatThreadInboxStatus.ts
@@ -1,5 +1,6 @@
export type AgentChatThreadInboxStatus = {
- scope: 'INBOX' | 'SNOOZED' | 'ARCHIVED';
+ // NONE: a chat the member can open but does not follow
+ scope: 'INBOX' | 'SNOOZED' | 'ARCHIVED' | 'NONE';
isUnread: boolean;
isSubscribed: boolean;
isMentioned: boolean;
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts
index 08ff9dcbf6d..d3fccbed402 100644
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts
@@ -33,16 +33,32 @@ const getStatus = ({
});
describe('getAgentChatThreadInboxStatus', () => {
- it('keeps a thread nobody acted on in the inbox, unread', () => {
+ it('keeps a thread the member does not follow out of their inbox, read', () => {
expect(
getAgentChatThreadInboxStatus({
lastActivityAt: '2026-10-01T09:00:00.000Z',
participant: undefined,
}),
).toEqual({
- scope: 'INBOX',
+ scope: 'NONE',
+ isUnread: false,
+ isSubscribed: false,
+ isMentioned: false,
+ event: null,
+ });
+ });
+
+ it('tracks what a member who opened a thread without following it has read, outside their inbox', () => {
+ expect(
+ getStatus({
+ lastActivityAt: '2026-10-01T11:00:00.000Z',
+ lastReadAt: '2026-10-01T09:00:00.000Z',
+ isSubscribed: false,
+ }),
+ ).toEqual({
+ scope: 'NONE',
isUnread: true,
- isSubscribed: true,
+ isSubscribed: false,
isMentioned: false,
event: null,
});
diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts
index 62eded75fdb..03e897de2b2 100644
--- a/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts
+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts
@@ -9,7 +9,9 @@ import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metad
// thread back whichever write committed last. Snooze is an archive with a
// wake-up time; the server unarchives the thread when it passes and keeps the
// snooze as what brought it back. A member who unsubscribed keeps the thread
-// under done whatever happens in it.
+// under done whatever happens in it. A chat the member can open but does not
+// follow stays out of their inbox until they take part in it or file it, and
+// only has unread messages once they have opened it.
export const getAgentChatThreadInboxStatus = ({
lastActivityAt,
participant,
@@ -19,13 +21,24 @@ export const getAgentChatThreadInboxStatus = ({
}): Omit<AgentChatThreadInboxStatus, 'isAssignedToMe'> => {
const isUnread =
isDefined(lastActivityAt) &&
- (!isDefined(participant?.lastReadAt) ||
+ isDefined(participant) &&
+ (!isDefined(participant.lastReadAt) ||
isAfter(lastActivityAt, participant.lastReadAt));
- const isSubscribed = participant?.isSubscribed ?? true;
+ const isSubscribed = participant?.isSubscribed ?? false;
const isMentioned = isDefined(participant?.lastMentionedAt);
const archivedAt = participant?.archivedAt;
const snoozedUntil = participant?.snoozedUntil;
+ if (!isSubscribed && !isDefined(archivedAt)) {
+ return {
+ scope: 'NONE',
+ isUnread,
+ isSubscribed,
+ isMentioned,
+ event: null,
+ };
+ }
+
if (!isSubscribed) {
return {
scope: 'ARCHIVED',
diff --git a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
index f7a9f00615a..73d419596bb 100644
--- a/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
+++ b/packages/twenty-front/src/pages/ai-chat/__tests__/AiChatInboxPage.test.tsx
@@ -239,6 +239,25 @@ describe('AiChatInboxPage', () => {
hasNextPage: false,
endCursor: null,
});
+ // The member's own chats, which they follow
+ jotaiStore.set(
+ agentChatThreadParticipantsState.atom,
+ Object.fromEntries(
+ THREADS.map(({ id, updatedAt }) => [
+ id,
+ {
+ id: `participant-${id}`,
+ threadId: id,
+ lastReadAt: updatedAt,
+ archivedAt: null,
+ snoozedUntil: null,
+ isSubscribed: true,
+ lastMentionedAt: null,
+ updatedAt,
+ },
+ ]),
+ ),
+ );
isMobile = false;
mockIsAiChatInboxEnabled = true;
});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-upgrade-version-command.module.ts
index d0ee2b5973a..40462891d22 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-upgrade-version-command.module.ts
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
import { UnpinNewAiChatCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-workspace-command-1791405719721-unpin-new-ai-chat.command';
+import { UnfollowChatsMembersOnlyReadCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.command';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';
@@ -11,6 +12,6 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
WorkspaceIteratorModule,
WorkspaceMigrationModule,
],
- providers: [UnpinNewAiChatCommand],
+ providers: [UnpinNewAiChatCommand, UnfollowChatsMembersOnlyReadCommand],
})
export class V2_47_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.command.ts
new file mode 100644
index 00000000000..4810fd1fd49
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-47/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.command.ts
@@ -0,0 +1,110 @@
+import { InjectDataSource } from '@nestjs/typeorm';
+import { Command } from 'nest-commander';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+import { DataSource } from 'typeorm';
+
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';
+
+// Members now follow a chat by taking part in it or filing it, rather than by
+// being able to open it. A row that only records reading was written by the
+// inbox backfill or by opening the chat, so its chat leaves the member's
+// inbox. Rows used to stop following only when filed under done, so down
+// follows again every row that does not follow and is not filed.
+@RegisteredWorkspaceCommand('2.47.0', 1791728623417)
+@Command({
+ name: 'upgrade:2-47:unfollow-chats-members-only-read',
+ description:
+ 'Stop following the chats a member only read, so they leave their inbox',
+})
+export class UnfollowChatsMembersOnlyReadCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ @InjectDataSource() private readonly dataSource: DataSource,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ if (!(await this.hasParticipantObject(workspaceId))) {
+ return;
+ }
+
+ const schemaName = escapeIdentifier(getWorkspaceSchemaName(workspaceId));
+ const whereOnlyRead = `participant."isSubscribed"
+ AND participant."archivedAt" IS NULL
+ AND participant."snoozedUntil" IS NULL
+ AND participant."lastMentionedAt" IS NULL
+ AND participant."threadId" = thread.id
+ AND participant."workspaceMemberId" IS DISTINCT FROM thread."workspaceMemberId"
+ AND participant."workspaceMemberId" IS DISTINCT FROM thread."assigneeId"
+ AND NOT participant."workspaceMemberId"::text = ANY(COALESCE(thread."writerWorkspaceMemberIds", '{}'))`;
+
+ if (options.dryRun ?? false) {
+ const [{ count }] = await this.dataSource.query<{ count: number }[]>(
+ `SELECT COUNT(*)::int AS count
+ FROM ${schemaName}."agentChatThreadParticipant" participant
+ JOIN ${schemaName}."agentChatThread" thread ON ${whereOnlyRead}`,
+ );
+
+ this.logger.log(
+ `[DRY RUN] Would unfollow ${count} chat(s) members only read in workspace ${workspaceId}`,
+ );
+
+ return;
+ }
+
+ const [, unfollowedCount]: [unknown[], number] =
+ await this.dataSource.query(
+ `UPDATE ${schemaName}."agentChatThreadParticipant" participant
+ SET "isSubscribed" = false, "updatedAt" = now()
+ FROM ${schemaName}."agentChatThread" thread
+ WHERE ${whereOnlyRead}`,
+ );
+
+ this.logger.log(
+ `Unfollowed ${unfollowedCount} chat(s) members only read in workspace ${workspaceId}`,
+ );
+ }
+
+ async down({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ if (
+ (options.dryRun ?? false) ||
+ !(await this.hasParticipantObject(workspaceId))
+ ) {
+ return;
+ }
+
+ const schemaName = escapeIdentifier(getWorkspaceSchemaName(workspaceId));
+
+ await this.dataSource.query(
+ `UPDATE ${schemaName}."agentChatThreadParticipant"
+ SET "isSubscribed" = true, "updatedAt" = now()
+ WHERE NOT "isSubscribed" AND "archivedAt" IS NULL`,
+ );
+ }
+
+ private async hasParticipantObject(workspaceId: string): Promise<boolean> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+
+ return isDefined(
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier
+ ],
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts
index e72ce33958d..4faa60bc3fa 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts
@@ -49,15 +49,15 @@ type BuildParticipantWriteQuery = (tables: {
}) => string;
// A snooze whose end is already due, which its queued end may have checked
-// before this write, is saved as ended. A snoozed thread is meant to come
-// back, so snoozing follows it again
+// before this write, is saved as ended. Filing a thread, done or snoozed,
+// follows it, so new activity or the snooze's end brings it back
const buildArchiveQuery: BuildParticipantWriteQuery = ({ participantTable }) =>
- `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "archivedAt", "snoozedUntil")
- VALUES ($1, $2, CASE WHEN $3::timestamptz <= clock_timestamp() THEN NULL ELSE clock_timestamp() END, $3)
+ `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "archivedAt", "snoozedUntil", "isSubscribed")
+ VALUES ($1, $2, CASE WHEN $3::timestamptz <= clock_timestamp() THEN NULL ELSE clock_timestamp() END, $3, true)
ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET
"archivedAt" = EXCLUDED."archivedAt",
"snoozedUntil" = EXCLUDED."snoozedUntil",
- "isSubscribed" = participant."isSubscribed" OR EXCLUDED."snoozedUntil" IS NOT NULL,
+ "isSubscribed" = true,
"updatedAt" = now()
RETURNING *`;
@@ -68,17 +68,18 @@ const INBOX_ACTION_QUERIES: Record<
AgentChatInboxAction,
BuildParticipantWriteQuery
> = {
- // Read up to what the thread holds now, never past it, and never back
+ // Read up to what the thread holds now, never past it, and never back.
+ // Reading or marking unread tracks a chat without following it
[AgentChatInboxAction.READ]: ({ participantTable, threadTable }) =>
- `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "lastReadAt")
- SELECT thread.id, $2, thread."lastActivityAt" FROM ${threadTable} thread WHERE thread.id = $1
+ `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "lastReadAt", "isSubscribed")
+ SELECT thread.id, $2, thread."lastActivityAt", false FROM ${threadTable} thread WHERE thread.id = $1
ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET
"lastReadAt" = GREATEST(participant."lastReadAt", EXCLUDED."lastReadAt"),
"updatedAt" = now()
RETURNING *`,
[AgentChatInboxAction.UNREAD]: ({ participantTable }) =>
- `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "lastReadAt")
- VALUES ($1, $2, NULL)
+ `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "lastReadAt", "isSubscribed")
+ VALUES ($1, $2, NULL, false)
ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET
"lastReadAt" = NULL,
"updatedAt" = now()
@@ -409,8 +410,8 @@ export class AgentChatThreadParticipantService {
return rows[0];
}
- // Over every chat the member can open, the way the inbox lists them; a chat
- // without the member's row is in their inbox, unread
+ // Over the chats the member can open and follows, the way the inbox lists
+ // them
async findOpenThreadsSummary({
workspaceId,
workspaceMemberId,
@@ -452,9 +453,9 @@ export class AgentChatThreadParticipantService {
thread."lastActivityAt" IS NOT NULL
AND (participant."lastReadAt" IS NULL OR thread."lastActivityAt" > participant."lastReadAt") AS "isUnread"
FROM (${readableThreads.getQuery()}) thread
- LEFT JOIN ${getAgentChatThreadParticipantTable(workspaceId)} participant
+ JOIN ${getAgentChatThreadParticipantTable(workspaceId)} participant
ON participant."threadId" = thread.id AND participant."workspaceMemberId" = :summaryWorkspaceMemberId
- WHERE COALESCE(participant."isSubscribed", true)
+ WHERE participant."isSubscribed"
AND (participant."archivedAt" IS NULL OR thread."lastActivityAt" > participant."archivedAt")
)
SELECT
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
index a9f6c99835f..5b7575849e2 100644
--- 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
@@ -392,7 +392,7 @@ describe('Chat thread participant state through the authenticated API', () => {
await setShareWithJony(threadId, true);
// A thread shared with a member they never opened has no state yet,
- // which reads as unread
+ // which reads as one they do not follow
expect(
await findMyParticipant(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),
).toBeUndefined();
@@ -1087,7 +1087,7 @@ describe('Chat thread participant state through the authenticated API', () => {
// 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 can read, from their own rows', async () => {
+ it('summarizes the open chats the member follows, from their own rows', async () => {
const before = await findOpenThreadsSummary();
const threadId = await createTestThread();
@@ -1099,19 +1099,35 @@ describe('Chat thread participant state through the authenticated API', () => {
[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,
needsInputThreadCount: before.needsInputThreadCount + 1,
- hasUnreadOpenThread: true,
+ hasUnreadOpenThread: before.hasUnreadOpenThread,
});
- await runInboxAction('READ', threadId, {
+ await runInboxAction('UNREAD', threadId, {
token: APPLE_JONY_MEMBER_ACCESS_TOKEN,
});
expect(await findOpenThreadsSummary()).toMatchObject({
openThreadCount: before.openThreadCount + 1,
- hasUnreadOpenThread: before.hasUnreadOpenThread,
+ hasUnreadOpenThread: true,
});
await runInboxAction('ARCHIVE', threadId, {
@@ -1121,6 +1137,27 @@ describe('Chat thread participant state through the authenticated API', () => {
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 mentionedThreadId = await createTestThread();
const assignedThreadId = await createTestThread();
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.integration-spec.ts
new file mode 100644
index 00000000000..dd66770f5c1
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.integration-spec.ts
@@ -0,0 +1,120 @@
+import { randomUUID } from 'node:crypto';
+
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+import { type UnfollowChatsMembersOnlyReadCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-workspace-command-1791728623417-unfollow-chats-members-only-read.command';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+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 RUN_ON_WORKSPACE_ARGS = {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ options: {},
+ index: 0,
+ total: 1,
+};
+
+const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const { JANE, JONY, PHIL, TIM } = WORKSPACE_MEMBER_DATA_SEED_IDS;
+
+describe('2-47 workspace command - unfollow chats members only read (integration)', () => {
+ let command: UnfollowChatsMembersOnlyReadCommand;
+ let workspaceOrmManager: WorkspaceOrmManager;
+
+ const threadId = randomUUID();
+ const filedThreadId = randomUUID();
+
+ const runCommand = (direction: 'up' | 'down') =>
+ workspaceOrmManager.executeInWorkspaceContext(
+ () => command[direction](RUN_ON_WORKSPACE_ARGS),
+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),
+ );
+
+ const readFollowing = async () => {
+ const rows: {
+ threadId: string;
+ workspaceMemberId: string;
+ isSubscribed: boolean;
+ }[] = await global.testDataSource.query(
+ `SELECT "threadId", "workspaceMemberId", "isSubscribed"
+ FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = ANY($1)`,
+ [[threadId, filedThreadId]],
+ );
+
+ return Object.fromEntries(
+ rows.map((row) => [
+ `${row.threadId === threadId ? 'chat' : 'filed'}:${row.workspaceMemberId}`,
+ row.isSubscribed,
+ ]),
+ );
+ };
+
+ beforeAll(async () => {
+ command = getAppProviderByClassName<UnfollowChatsMembersOnlyReadCommand>(
+ 'UnfollowChatsMembersOnlyReadCommand',
+ );
+ workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(
+ 'WorkspaceOrmManager',
+ );
+
+ // Jane owns the chat, Jony wrote in it and Tim is assigned; Phil only
+ // read it, and filed the other chat
+ await global.testDataSource.query(
+ `INSERT INTO ${SCHEMA}."agentChatThread" (id, title, "workspaceMemberId", "assigneeId", "writerWorkspaceMemberIds")
+ VALUES ($1, 'Read by Phil', $3, $4, ARRAY[$5]::text[]), ($2, 'Filed by Phil', $3, NULL, NULL)`,
+ [threadId, filedThreadId, JANE, TIM, JONY],
+ );
+ await global.testDataSource.query(
+ `INSERT INTO ${SCHEMA}."agentChatThreadParticipant" ("threadId", "workspaceMemberId", "lastReadAt", "archivedAt")
+ VALUES ($1, $3, now(), NULL), ($1, $4, now(), NULL), ($1, $5, now(), NULL), ($1, $6, now(), NULL),
+ ($2, $6, now(), now())`,
+ [threadId, filedThreadId, JANE, JONY, TIM, PHIL],
+ );
+ });
+
+ afterAll(async () => {
+ // down follows every unfiled row that does not follow, in any chat
+ await runCommand('up');
+ await global.testDataSource.query(
+ `DELETE FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = ANY($1)`,
+ [[threadId, filedThreadId]],
+ );
+ await global.testDataSource.query(
+ `DELETE FROM ${SCHEMA}."agentChatThread" WHERE id = ANY($1)`,
+ [[threadId, filedThreadId]],
+ );
+ });
+
+ it('unfollows only the chats a member read without taking part in or filing them', async () => {
+ await runCommand('up');
+
+ expect(await readFollowing()).toEqual({
+ [`chat:${JANE}`]: true,
+ [`chat:${JONY}`]: true,
+ [`chat:${TIM}`]: true,
+ [`chat:${PHIL}`]: false,
+ [`filed:${PHIL}`]: true,
+ });
+ });
+
+ it('changes nothing when run again', async () => {
+ await runCommand('up');
+
+ expect((await readFollowing())[`chat:${PHIL}`]).toBe(false);
+ });
+
+ it('follows the unfollowed chats again on rollback', async () => {
+ await runCommand('down');
+
+ expect(await readFollowing()).toEqual({
+ [`chat:${JANE}`]: true,
+ [`chat:${JONY}`]: true,
+ [`chat:${TIM}`]: true,
+ [`chat:${PHIL}`]: true,
+ [`filed:${PHIL}`]: true,
+ });
+ });
+});
diff --git a/packages/twenty-shared/src/ai/utils/__tests__/apply-agent-chat-inbox-action.util.spec.ts b/packages/twenty-shared/src/ai/utils/__tests__/apply-agent-chat-inbox-action.util.spec.ts
index 20e50a1150e..1f079165ca5 100644
--- a/packages/twenty-shared/src/ai/utils/__tests__/apply-agent-chat-inbox-action.util.spec.ts
+++ b/packages/twenty-shared/src/ai/utils/__tests__/apply-agent-chat-inbox-action.util.spec.ts
@@ -31,11 +31,18 @@ describe('applyAgentChatInboxAction', () => {
]
>([
[
- 'reads a chat without a row up to its last activity',
+ 'reads a chat without a row up to its last activity, without following it',
undefined,
'READ',
{ threadLastActivityAt: EARLIER },
- READ,
+ { ...READ, isSubscribed: false },
+ ],
+ [
+ 'marks a chat without a row unread, without following it',
+ undefined,
+ 'UNREAD',
+ {},
+ { ...READ, lastReadAt: null, isSubscribed: false },
],
[
'never moves the read cursor back',
@@ -46,11 +53,11 @@ describe('applyAgentChatInboxAction', () => {
],
['marks unread', READ, 'UNREAD', {}, { ...READ, lastReadAt: null }],
[
- 'archives without following the chat again',
+ 'archives and follows the chat again',
SNOOZED_UNSUBSCRIBED,
'ARCHIVE',
{},
- { ...READ, archivedAt: NOW.toISOString(), isSubscribed: false },
+ { ...READ, archivedAt: NOW.toISOString() },
],
[
'snoozes and follows the chat again',
diff --git a/packages/twenty-shared/src/ai/utils/apply-agent-chat-inbox-action.util.ts b/packages/twenty-shared/src/ai/utils/apply-agent-chat-inbox-action.util.ts
index e3c1336d26f..361eb2993dd 100644
--- a/packages/twenty-shared/src/ai/utils/apply-agent-chat-inbox-action.util.ts
+++ b/packages/twenty-shared/src/ai/utils/apply-agent-chat-inbox-action.util.ts
@@ -2,12 +2,13 @@ import { type AgentChatInboxAction } from '@/ai/types/AgentChatInboxAction';
import { type AgentChatInboxState } from '@/ai/types/AgentChatInboxState';
import { isDefined } from '@/utils/validation/isDefined';
-// What a chat without the member's row reads as
+// What a chat without the member's row reads as: one they can open but do
+// not follow, since only taking part in it or filing it follows a chat
const DEFAULT_AGENT_CHAT_INBOX_STATE: AgentChatInboxState = {
lastReadAt: null,
archivedAt: null,
snoozedUntil: null,
- isSubscribed: true,
+ isSubscribed: false,
};
// The server writes each action as one SQL upsert stamped by the database
@@ -42,8 +43,14 @@ export const applyAgentChatInboxAction = ({
};
case 'UNREAD':
return { ...state, lastReadAt: null };
+ // Filing a chat follows it, so new activity brings it back
case 'ARCHIVE':
- return { ...state, archivedAt: now.toISOString(), snoozedUntil: null };
+ return {
+ ...state,
+ archivedAt: now.toISOString(),
+ snoozedUntil: null,
+ isSubscribed: true,
+ };
// A snooze already due is saved as ended, and a snoozed chat is followed
// again since it is meant to come back
case 'SNOOZE':