Open-source and local-first Slack and Notion alternative that puts you in control of your data
TypeScript chatchat-applicationcrdteditorelectronknowledge-baselocal-firstnotionnotion-alternativerealtime-collaborationself-hostedslacksqliteteam-collaborationwikiyjs
Treat messages as a separate entity from nodes
Hakan Shehue798db5691c6
diff --git a/apps/desktop/src/main/consumers/message-reactions.ts b/apps/desktop/src/main/consumers/message-reactions.tsnew file mode 100644index 00000000..3f98fab2--- /dev/null+++ b/apps/desktop/src/main/consumers/message-reactions.ts@@ -0,0 +1,81 @@+import { Kysely } from 'kysely';+import {+ MessageReactionsBatchMessage,+ ConsumeMessageReactionsMessage,+} from '@colanode/core';++import { messageService } from '@/main/services/message-service';+import { createDebugger } from '@/main/debugger';+import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';+import { BaseConsumer } from '@/main/consumers/base';++export class MessageReactionsConsumer extends BaseConsumer {+ private readonly debug = createDebugger('consumer:message-reactions');+ private readonly rootId: string;++ constructor(+ userId: string,+ accountId: string,+ rootId: string,+ workspaceDatabase: Kysely<WorkspaceDatabaseSchema>+ ) {+ super(userId, accountId, workspaceDatabase);+ this.rootId = rootId;+ }++ protected get cursorKey(): string {+ return `message-reactions:${this.rootId}`;+ }++ public async init() {+ await super.initCursor();+ this.requestMessageReactions();+ }++ public async processMessageReactions(message: MessageReactionsBatchMessage) {+ if (this.status === 'syncing') {+ this.debug(+ `Syncing of server messages already in progress for user ${message.userId}, skipping`+ );+ return;+ }++ this.debug(`Syncing server messages for user ${message.userId}`);++ this.status = 'syncing';+ let cursor: bigint | null = null;+ try {+ for (const item of message.messageReactions) {+ await messageService.syncServerMessageReaction(message.userId, item);+ cursor = BigInt(item.version);+ }+ } catch (error) {+ this.debug(+ error,+ `Error syncing server messages for user ${message.userId}`+ );+ } finally {+ this.debug(+ `Syncing of server messages completed for user ${message.userId}`+ );++ if (cursor) {+ await this.setCursor(cursor);+ }++ this.status = 'idle';+ this.requestMessageReactions();+ }+ }++ private async requestMessageReactions() {+ const message: ConsumeMessageReactionsMessage = {+ type: 'consume_message_reactions',+ userId: this.userId,+ rootId: this.rootId,+ cursor: this.cursor.toString(),+ };++ this.sendMessage(message);+ }+}diff --git a/apps/desktop/src/main/consumers/messages.ts b/apps/desktop/src/main/consumers/messages.tsnew file mode 100644index 00000000..2fbd742b--- /dev/null+++ b/apps/desktop/src/main/consumers/messages.ts@@ -0,0 +1,78 @@+import { Kysely } from 'kysely';+import { ConsumeMessagesMessage, MessagesBatchMessage } from '@colanode/core';++import { messageService } from '@/main/services/message-service';+import { createDebugger } from '@/main/debugger';+import { WorkspaceDatabaseSchema } from '@/main/data/workspace/schema';+import { BaseConsumer } from '@/main/consumers/base';++export class MessagesConsumer extends BaseConsumer {+ private readonly debug = createDebugger('consumer:messages');+ private readonly rootId: string;++ constructor(+ userId: string,+ accountId: string,+ rootId: string,+ workspaceDatabase: Kysely<WorkspaceDatabaseSchema>+ ) {+ super(userId, accountId, workspaceDatabase);+ this.rootId = rootId;+ }++ protected get cursorKey(): string {+ return `messages:${this.rootId}`;+ }++ public async init() {+ await super.initCursor();+ this.requestMessages();+ }++ public async processMessages(message: MessagesBatchMessage) {+ if (this.status === 'syncing') {+ this.debug(+ `Syncing of server messages already in progress for user ${message.userId}, skipping`+ );+ return;+ }++ this.debug(`Syncing server messages for user ${message.userId}`);++ this.status = 'syncing';+ let cursor: bigint | null = null;+ try {+ for (const item of message.messages) {+ await messageService.syncServerMessage(message.userId, item);+ cursor = BigInt(item.version);+ }+ } catch (error) {+ this.debug(+ error,+ `Error syncing server messages for user ${message.userId}`+ );+ } finally {+ this.debug(+ `Syncing of server messages completed for user ${message.userId}`+ );++ if (cursor) {+ await this.setCursor(cursor);+ }++ this.status = 'idle';+ this.requestMessages();+ }+ }++ private async requestMessages() {+ const message: ConsumeMessagesMessage = {+ type: 'consume_messages',+ userId: this.userId,+ rootId: this.rootId,+ cursor: this.cursor.toString(),+ };++ this.sendMessage(message);+ }+}diff --git a/apps/desktop/src/main/data/workspace/migrations.ts b/apps/desktop/src/main/data/workspace/migrations.tsindex 53b33a68..1808d53f 100644--- a/apps/desktop/src/main/data/workspace/migrations.ts+++ b/apps/desktop/src/main/data/workspace/migrations.ts@@ -94,6 +94,50 @@ const createCollaborationsTable: Migration = {},};+const createMessagesTable: Migration = {+ up: async (db) => {+ await db.schema+ .createTable('messages')+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())+ .addColumn('type', 'text', (col) => col.notNull())+ .addColumn('parent_id', 'text', (col) => col.notNull())+ .addColumn('node_id', 'text', (col) => col.notNull())+ .addColumn('root_id', 'text', (col) => col.notNull())+ .addColumn('content', 'text', (col) => col.notNull())+ .addColumn('created_at', 'text', (col) => col.notNull())+ .addColumn('created_by', 'text', (col) => col.notNull())+ .addColumn('updated_at', 'text')+ .addColumn('updated_by', 'text')+ .addColumn('version', 'integer')+ .execute();+ },+ down: async (db) => {+ await db.schema.dropTable('messages').execute();+ },+};++const createMessageReactionsTable: Migration = {+ up: async (db) => {+ await db.schema+ .createTable('message_reactions')+ .addColumn('message_id', 'text', (col) => col.notNull())+ .addColumn('collaborator_id', 'text', (col) => col.notNull())+ .addColumn('reaction', 'text', (col) => col.notNull())+ .addColumn('root_id', 'text', (col) => col.notNull())+ .addColumn('created_at', 'text', (col) => col.notNull())+ .addColumn('version', 'integer', (col) => col.notNull())+ .addPrimaryKeyConstraint('message_reactions_pkey', [+ 'message_id',+ 'collaborator_id',+ 'reaction',+ ])+ .execute();+ },+ down: async (db) => {+ await db.schema.dropTable('message_reactions').execute();+ },+};+const createFilesTable: Migration = {up: async (db) => {await db.schema@@ -147,7 +191,6 @@ const createMutationsTable: Migration = {.addColumn('id', 'text', (col) => col.notNull().primaryKey()).addColumn('type', 'text', (col) => col.notNull()).addColumn('node_id', 'text', (col) => col.notNull())- .addColumn('key', 'text', (col) => col.notNull()).addColumn('data', 'text', (col) => col.notNull()).addColumn('created_at', 'text', (col) => col.notNull()).addColumn('retries', 'integer', (col) => col.notNull())@@ -318,13 +361,15 @@ export const workspaceDatabaseMigrations: Record<string, Migration> = {'00002_create_nodes_table': createNodesTable,'00003_create_transactions_table': createTransactionsTable,'00004_create_collaborations_table': createCollaborationsTable,- '00005_create_files_table': createFilesTable,- '00006_create_file_states_table': createFileStatesTable,- '00007_create_interactions_table': createInteractionsTable,- '00008_create_interaction_events_table': createInteractionEventsTable,- '00009_create_mutations_table': createMutationsTable,- '00010_create_node_paths_table': createNodePathsTable,- '00011_create_node_names_table': createNodeNamesTable,- '00012_create_node_texts_table': createNodeTextsTable,- '00013_create_cursors_table': createCursorsTable,+ '00005_create_messages_table': createMessagesTable,+ '00006_create_message_reactions_table': createMessageReactionsTable,+ '00007_create_files_table': createFilesTable,+ '00008_create_file_states_table': createFileStatesTable,+ '00009_create_interactions_table': createInteractionsTable,+ '00010_create_interaction_events_table': createInteractionEventsTable,+ '00011_create_mutations_table': createMutationsTable,+ '00012_create_node_paths_table': createNodePathsTable,+ '00013_create_node_names_table': createNodeNamesTable,+ '00014_create_node_texts_table': createNodeTextsTable,+ '00015_create_cursors_table': createCursorsTable,};diff --git a/apps/desktop/src/main/data/workspace/schema.ts b/apps/desktop/src/main/data/workspace/schema.tsindex b93b824e..aa0fbbe2 100644--- a/apps/desktop/src/main/data/workspace/schema.ts+++ b/apps/desktop/src/main/data/workspace/schema.ts@@ -2,6 +2,7 @@ import {FileStatus,FileType,InteractionAttribute,+ MessageType,MutationType,NodeType,WorkspaceRole,@@ -99,6 +100,37 @@ export type SelectInteraction = Selectable<InteractionTable>;export type CreateInteraction = Insertable<InteractionTable>;export type UpdateInteraction = Updateable<InteractionTable>;+interface MessageTable {+ id: ColumnType<string, string, never>;+ type: ColumnType<MessageType, MessageType, MessageType>;+ parent_id: ColumnType<string, string, string>;+ node_id: ColumnType<string, string, string>;+ root_id: ColumnType<string, string, string>;+ content: ColumnType<string, string, string>;+ created_at: ColumnType<string, string, never>;+ created_by: ColumnType<string, string, never>;+ updated_at: ColumnType<string | null, string | null, string | null>;+ updated_by: ColumnType<string | null, string | null, string | null>;+ version: ColumnType<bigint, bigint, bigint>;+}++export type SelectMessage = Selectable<MessageTable>;+export type CreateMessage = Insertable<MessageTable>;+export type UpdateMessage = Updateable<MessageTable>;++interface MessageReactionTable {+ message_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ reaction: ColumnType<string, string, string>;+ root_id: ColumnType<string, string, string>;+ created_at: ColumnType<string, string, never>;+ version: ColumnType<bigint, bigint, bigint>;+}++export type SelectMessageReaction = Selectable<MessageReactionTable>;+export type CreateMessageReaction = Insertable<MessageReactionTable>;+export type UpdateMessageReaction = Updateable<MessageReactionTable>;+interface FileTable {id: ColumnType<string, string, never>;type: ColumnType<FileType, FileType, FileType>;@@ -155,7 +187,6 @@ interface MutationTable {id: ColumnType<string, string, never>;type: ColumnType<MutationType, MutationType, never>;node_id: ColumnType<string, string, never>;- key: ColumnType<string, string, string>;data: ColumnType<string, string, never>;created_at: ColumnType<string, string, never>;retries: ColumnType<number, number, number>;@@ -198,6 +229,8 @@ export interface WorkspaceDatabaseSchema {collaborations: CollaborationTable;interactions: InteractionTable;interaction_events: InteractionEventTable;+ messages: MessageTable;+ message_reactions: MessageReactionTable;files: FileTable;file_states: FileStateTable;mutations: MutationTable;diff --git a/apps/desktop/src/main/mutations/files/file-create.ts b/apps/desktop/src/main/mutations/files/file-create.tsindex e4c1966d..4411b11d 100644--- a/apps/desktop/src/main/mutations/files/file-create.ts+++ b/apps/desktop/src/main/mutations/files/file-create.ts@@ -45,7 +45,7 @@ export class FileCreateMutationHandlerconst mutationData: CreateFileMutationData = {id: fileId,- fileType: metadata.type,+ type: metadata.type,parentId: input.parentId,rootId: input.rootId,name: metadata.name,@@ -103,7 +103,6 @@ export class FileCreateMutationHandlerid: generateId(IdType.Mutation),type: 'create_file',node_id: fileId,- key: `create_${fileId}`,data: JSON.stringify(mutationData),created_at: new Date().toISOString(),retries: 0,diff --git a/apps/desktop/src/main/mutations/messages/message-create.ts b/apps/desktop/src/main/mutations/messages/message-create.tsindex abc4bb41..2846ed0f 100644--- a/apps/desktop/src/main/mutations/messages/message-create.ts+++ b/apps/desktop/src/main/mutations/messages/message-create.ts@@ -1,15 +1,16 @@import {Block,+ CreateFileMutationData,+ CreateMessageMutationData,EditorNodeTypes,FileStatus,generateId,IdType,- MessageAttributes,+ MessageContent,NodeTypes,} from '@colanode/core';import { fileService } from '@/main/services/file-service';-import { CreateNodeInput, nodeService } from '@/main/services/node-service';import { MutationHandler } from '@/main/types';import { mapContentsToBlocks } from '@/shared/lib/editor';import {@@ -17,10 +18,14 @@ import {MessageCreateMutationOutput,} from '@/shared/mutations/messages/message-create';import { MutationError } from '@/shared/mutations';-import { CreateFile, CreateFileState } from '@/main/data/workspace/schema';+import {+ CreateFile,+ CreateFileState,+ CreateMutation,+} from '@/main/data/workspace/schema';import { databaseService } from '@/main/data/database-service';import { eventBus } from '@/shared/lib/event-bus';-import { mapFile, mapFileState } from '@/main/utils';+import { mapFile, mapFileState, mapMessage } from '@/main/utils';export class MessageCreateMutationHandlerimplements MutationHandler<MessageCreateMutationInput>@@ -28,14 +33,18 @@ export class MessageCreateMutationHandlerasync handleMutation(input: MessageCreateMutationInput): Promise<MessageCreateMutationOutput> {- const inputs: CreateNodeInput[] = [];+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );- const messageContent = input.content.content ?? [];+ const editorContent = input.content.content ?? [];const messageId = generateId(IdType.Message);const createdAt = new Date().toISOString();- const blocks = mapContentsToBlocks(messageId, messageContent, new Map());+ const blocks = mapContentsToBlocks(messageId, editorContent, new Map());+const files: CreateFile[] = [];const fileStates: CreateFileState[] = [];+ const fileMutations: CreateMutation[] = [];// check if there are nested nodes (files, pages, folders etc.)for (const block of blocks) {@@ -77,6 +86,28 @@ export class MessageCreateMutationHandlerversion: 0n,});+ const mutationData: CreateFileMutationData = {+ id: fileId,+ type: metadata.type,+ parentId: messageId,+ rootId: input.rootId,+ name: metadata.name,+ originalName: metadata.name,+ extension: metadata.extension,+ mimeType: metadata.mimeType,+ size: metadata.size,+ createdAt: createdAt,+ };++ fileMutations.push({+ id: generateId(IdType.Mutation),+ type: 'create_file',+ node_id: fileId,+ data: JSON.stringify(mutationData),+ created_at: createdAt,+ retries: 0,+ });+fileStates.push({file_id: fileId,upload_status: 'pending',@@ -98,51 +129,55 @@ export class MessageCreateMutationHandler{} as Record<string, Block>);- if (input.referenceId) {- const reference = await nodeService.fetchNode(- input.referenceId,- input.userId- );-- if (!reference || reference.type !== 'message') {- throw new MutationError(- 'node_not_found',- 'Referenced message not found or has been deleted.'- );- }-- const messageAttributes: MessageAttributes = {- type: 'message',- subtype: 'reply',- parentId: input.conversationId,- referenceId: input.referenceId,- content: blocksRecord,- reactions: {},- };-- inputs.unshift({ id: messageId, attributes: messageAttributes });- } else {- const messageAttributes: MessageAttributes = {- type: 'message',- subtype: 'standard',- parentId: input.conversationId,- content: blocksRecord,- reactions: {},- };-- inputs.unshift({ id: messageId, attributes: messageAttributes });- }-- await nodeService.createNode(input.userId, inputs);+ const messageContent: MessageContent = {+ blocks: blocksRecord,+ };- if (files.length > 0) {- const workspaceDatabase = await databaseService.getWorkspaceDatabase(- input.userId- );+ const { createdMessage, createdFiles, createdFileStates } =+ await workspaceDatabase.transaction().execute(async (tx) => {+ const createdMessage = await tx+ .insertInto('messages')+ .returningAll()+ .values({+ id: messageId,+ type: 'standard',+ node_id: input.conversationId,+ parent_id: input.conversationId,+ root_id: input.rootId,+ content: JSON.stringify(messageContent),+ created_at: createdAt,+ created_by: input.userId,+ version: 0n,+ })+ .executeTakeFirst();++ if (!createdMessage) {+ throw new Error('Failed to create message.');+ }- const { createdFiles, createdFileStates } = await workspaceDatabase- .transaction()- .execute(async (tx) => {+ const createMessageMutationData: CreateMessageMutationData = {+ id: messageId,+ type: 'standard',+ nodeId: input.conversationId,+ parentId: input.conversationId,+ rootId: input.rootId,+ content: messageContent,+ createdAt: createdAt,+ };++ await tx+ .insertInto('mutations')+ .values({+ id: generateId(IdType.Mutation),+ type: 'create_message',+ node_id: messageId,+ data: JSON.stringify(createMessageMutationData),+ created_at: createdAt,+ retries: 0,+ })+ .execute();++ if (files.length > 0) {const createdFiles = await tx.insertInto('files').returningAll()@@ -153,6 +188,8 @@ export class MessageCreateMutationHandlerthrow new Error('Failed to create files.');}+ await tx.insertInto('mutations').values(fileMutations).execute();+const createdFileStates = await tx.insertInto('file_states').returningAll()@@ -166,9 +203,24 @@ export class MessageCreateMutationHandlerreturn {createdFiles,createdFileStates,+ createdMessage,};- });+ }++ return {+ createdMessage,+ };+ });++ if (createdMessage) {+ eventBus.publish({+ type: 'message_created',+ userId: input.userId,+ message: mapMessage(createdMessage),+ });+ }+ if (createdFiles) {for (const file of createdFiles) {eventBus.publish({type: 'file_created',@@ -176,7 +228,9 @@ export class MessageCreateMutationHandlerfile: mapFile(file),});}+ }+ if (createdFileStates) {for (const fileState of createdFileStates) {eventBus.publish({type: 'file_state_created',@@ -186,6 +240,11 @@ export class MessageCreateMutationHandler}}+ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });+return {id: messageId,};diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts b/apps/desktop/src/main/mutations/messages/message-reaction-create.tsindex d73866d9..3500e91b 100644--- a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts+++ b/apps/desktop/src/main/mutations/messages/message-reaction-create.ts@@ -1,10 +1,17 @@-import { nodeService } from '@/main/services/node-service';+import {+ CreateMessageReactionMutation,+ generateId,+ IdType,+} from '@colanode/core';++import { databaseService } from '@/main/data/database-service';import { MutationHandler } from '@/main/types';-import { MutationError } from '@/shared/mutations';import {MessageReactionCreateMutationInput,MessageReactionCreateMutationOutput,} from '@/shared/mutations/messages/message-reaction-create';+import { eventBus } from '@/shared/lib/event-bus';+import { mapMessageReaction } from '@/main/utils';export class MessageReactionCreateMutationHandlerimplements MutationHandler<MessageReactionCreateMutationInput>@@ -12,42 +19,90 @@ export class MessageReactionCreateMutationHandlerasync handleMutation(input: MessageReactionCreateMutationInput): Promise<MessageReactionCreateMutationOutput> {- const result = await nodeService.updateNode(- input.messageId,- input.userId,- (attributes) => {- if (attributes.type !== 'message') {- throw new MutationError(- 'invalid_attributes',- 'Node is not a message'- );- }+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const existingMessageReaction = await workspaceDatabase+ .selectFrom('message_reactions')+ .selectAll()+ .where('message_id', '=', input.messageId)+ .where('collaborator_id', '=', input.userId)+ .where('reaction', '=', input.reaction)+ .executeTakeFirst();++ if (existingMessageReaction) {+ return {+ success: true,+ };+ }- const reactionsUsers = attributes.reactions[input.reaction] ?? [];- if (reactionsUsers.includes(input.userId)) {- return attributes;+ const { createdMessageReaction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const createdMessageReaction = await trx+ .insertInto('message_reactions')+ .returningAll()+ .values({+ message_id: input.messageId,+ collaborator_id: input.userId,+ reaction: input.reaction,+ root_id: input.rootId,+ version: 0n,+ created_at: new Date().toISOString(),+ })+ .executeTakeFirst();++ if (!createdMessageReaction) {+ throw new Error('Failed to create message reaction');}- reactionsUsers.push(input.userId);- attributes.reactions[input.reaction] = reactionsUsers;- return attributes;- }- );+ const mutation: CreateMessageReactionMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'create_message_reaction',+ data: {+ messageId: input.messageId,+ reaction: input.reaction,+ rootId: input.rootId,+ createdAt: new Date().toISOString(),+ },+ };- if (result === 'unauthorized') {- throw new MutationError(- 'unauthorized',- "You don't have permission to react to this message."- );- }+ const createdMutation = await trx+ .insertInto('mutations')+ .returningAll()+ .values({+ id: mutation.id,+ type: mutation.type,+ data: JSON.stringify(mutation.data),+ created_at: mutation.createdAt,+ node_id: input.messageId,+ retries: 0,+ })+ .executeTakeFirst();- if (result !== 'success') {- throw new MutationError(- 'unknown',- 'Something went wrong while reacting to the message.'- );+ return {+ createdMessageReaction,+ createdMutation,+ };+ });++ if (!createdMessageReaction || !createdMutation) {+ throw new Error('Failed to create message reaction');}+ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'message_reaction_created',+ userId: input.userId,+ messageReaction: mapMessageReaction(createdMessageReaction),+ });+return {success: true,};diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/main/mutations/messages/message-reaction-delete.tsindex a8a36430..aeeea4d0 100644--- a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts+++ b/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts@@ -1,10 +1,17 @@-import { nodeService } from '@/main/services/node-service';+import {+ DeleteMessageReactionMutation,+ generateId,+ IdType,+} from '@colanode/core';++import { databaseService } from '@/main/data/database-service';import { MutationHandler } from '@/main/types';-import { MutationError } from '@/shared/mutations';import {MessageReactionDeleteMutationInput,MessageReactionDeleteMutationOutput,} from '@/shared/mutations/messages/message-reaction-delete';+import { mapMessageReaction } from '@/main/utils';+import { eventBus } from '@/shared/lib/event-bus';export class MessageReactionDeleteMutationHandlerimplements MutationHandler<MessageReactionDeleteMutationInput>@@ -12,47 +19,85 @@ export class MessageReactionDeleteMutationHandlerasync handleMutation(input: MessageReactionDeleteMutationInput): Promise<MessageReactionDeleteMutationOutput> {- const result = await nodeService.updateNode(- input.messageId,- input.userId,- (attributes) => {- if (attributes.type !== 'message') {- throw new MutationError(- 'invalid_attributes',- 'Node is not a message'- );- }+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );- const reactionUsers = attributes.reactions[input.reaction] ?? [];- if (!reactionUsers.includes(input.userId)) {- return attributes;- }+ const existingMessageReaction = await workspaceDatabase+ .selectFrom('message_reactions')+ .selectAll()+ .where('message_id', '=', input.messageId)+ .where('collaborator_id', '=', input.userId)+ .where('reaction', '=', input.reaction)+ .executeTakeFirst();++ if (!existingMessageReaction) {+ return {+ success: true,+ };+ }- const index = reactionUsers.indexOf(input.userId);- if (index === -1) {- return attributes;+ const { deletedMessageReaction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const deletedMessageReaction = await trx+ .deleteFrom('message_reactions')+ .where('message_id', '=', input.messageId)+ .where('collaborator_id', '=', input.userId)+ .where('reaction', '=', input.reaction)+ .returningAll()+ .executeTakeFirst();++ if (!deletedMessageReaction) {+ throw new Error('Failed to delete message reaction');}- reactionUsers.splice(index, 1);- attributes.reactions[input.reaction] = reactionUsers;- return attributes;- }- );+ const mutation: DeleteMessageReactionMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'delete_message_reaction',+ data: {+ messageId: input.messageId,+ reaction: deletedMessageReaction.reaction,+ rootId: input.rootId,+ deletedAt: new Date().toISOString(),+ },+ };- if (result === 'unauthorized') {- throw new MutationError(- 'unauthorized',- "You don't have permission to react to this message."- );- }+ const createdMutation = await trx+ .insertInto('mutations')+ .returningAll()+ .values({+ id: mutation.id,+ type: mutation.type,+ data: JSON.stringify(mutation.data),+ created_at: mutation.createdAt,+ node_id: input.messageId,+ retries: 0,+ })+ .executeTakeFirst();- if (result !== 'success') {- throw new MutationError(- 'unknown',- 'Something went wrong while deleting the reaction.'- );+ return {+ deletedMessageReaction,+ createdMutation,+ };+ });++ if (!deletedMessageReaction || !createdMutation) {+ throw new Error('Failed to delete message reaction');}+ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'message_reaction_deleted',+ userId: input.userId,+ messageReaction: mapMessageReaction(deletedMessageReaction),+ });+return {success: true,};diff --git a/apps/desktop/src/main/queries/index.ts b/apps/desktop/src/main/queries/index.tsindex dd33cc41..d9ae8fe2 100644--- a/apps/desktop/src/main/queries/index.ts+++ b/apps/desktop/src/main/queries/index.ts@@ -6,6 +6,7 @@ import { FileGetQueryHandler } from '@/main/queries/files/file-get';import { FileMetadataGetQueryHandler } from '@/main/queries/files/file-metadata-get';import { IconsGetQueryHandler } from '@/main/queries/icons/icons-get';import { MessageListQueryHandler } from '@/main/queries/messages/message-list';+import { MessageReactionsGetQueryHandler } from '@/main/queries/messages/message-reactions-get';import { NodeChildrenGetQueryHandler } from '@/main/queries/nodes/node-children-get';import { NodeGetQueryHandler } from '@/main/queries/nodes/node-get';import { NodeTreeGetQueryHandler } from '@/main/queries/nodes/node-tree-get';@@ -29,6 +30,7 @@ type QueryHandlerMap = {export const queryHandlerMap: QueryHandlerMap = {account_list: new AccountListQueryHandler(),message_list: new MessageListQueryHandler(),+ message_reactions_get: new MessageReactionsGetQueryHandler(),node_get: new NodeGetQueryHandler(),record_list: new RecordListQueryHandler(),server_list: new ServerListQueryHandler(),diff --git a/apps/desktop/src/main/queries/messages/message-list.ts b/apps/desktop/src/main/queries/messages/message-list.tsindex fc7d8e9e..4430f313 100644--- a/apps/desktop/src/main/queries/messages/message-list.ts+++ b/apps/desktop/src/main/queries/messages/message-list.ts@@ -1,11 +1,12 @@-import { compareString, MessageNode } from '@colanode/core';+import { compareString } from '@colanode/core';import { databaseService } from '@/main/data/database-service';-import { SelectNode } from '@/main/data/workspace/schema';+import { SelectMessage } from '@/main/data/workspace/schema';import { ChangeCheckResult, QueryHandler } from '@/main/types';-import { mapNode } from '@/main/utils';+import { mapMessage } from '@/main/utils';import { MessageListQueryInput } from '@/shared/queries/messages/message-list';import { Event } from '@/shared/types/events';+import { MessageNode } from '@/shared/types/messages';export class MessageListQueryHandlerimplements QueryHandler<MessageListQueryInput>@@ -33,10 +34,9 @@ export class MessageListQueryHandler}if (- event.type === 'node_created' &&+ event.type === 'message_created' &&event.userId === input.userId &&- event.node.type === 'message' &&- event.node.parentId === input.conversationId+ event.message.parentId === input.conversationId) {const newResult = await this.handleQuery(input);@@ -47,16 +47,15 @@ export class MessageListQueryHandler}if (- event.type === 'node_updated' &&+ event.type === 'message_updated' &&event.userId === input.userId &&- event.node.type === 'message' &&- event.node.parentId === input.conversationId+ event.message.parentId === input.conversationId) {- const message = output.find((message) => message.id === event.node.id);+ const message = output.find((message) => message.id === event.message.id);if (message) {const newResult = output.map((message) => {- if (message.id === event.node.id) {- return event.node as MessageNode;+ if (message.id === event.message.id) {+ return event.message;}return message;});@@ -69,12 +68,11 @@ export class MessageListQueryHandler}if (- event.type === 'node_deleted' &&+ event.type === 'message_deleted' &&event.userId === input.userId &&- event.node.type === 'message' &&- event.node.parentId === input.conversationId+ event.message.parentId === input.conversationId) {- const message = output.find((message) => message.id === event.node.id);+ const message = output.find((message) => message.id === event.message.id);if (message) {const newOutput = await this.handleQuery(input);@@ -92,21 +90,16 @@ export class MessageListQueryHandlerprivate async fetchMesssages(input: MessageListQueryInput- ): Promise<SelectNode[]> {+ ): Promise<SelectMessage[]> {const workspaceDatabase = await databaseService.getWorkspaceDatabase(input.userId);const offset = (input.page - 1) * input.count;const messages = await workspaceDatabase- .selectFrom('nodes')+ .selectFrom('messages').selectAll()- .where((eb) =>- eb.and([- eb('parent_id', '=', input.conversationId),- eb('type', '=', 'message'),- ])- )+ .where('parent_id', '=', input.conversationId).orderBy('id', 'desc').limit(input.count).offset(offset)@@ -115,18 +108,8 @@ export class MessageListQueryHandlerreturn messages;}- private buildMessages = (rows: SelectNode[]): MessageNode[] => {- const nodes = rows.map(mapNode);- const messageNodes: MessageNode[] = [];-- for (const node of nodes) {- if (node.type !== 'message') {- continue;- }-- messageNodes.push(node);- }-- return messageNodes.sort((a, b) => compareString(a.id, b.id));+ private buildMessages = (rows: SelectMessage[]): MessageNode[] => {+ const messages = rows.map(mapMessage);+ return messages.sort((a, b) => compareString(a.id, b.id));};}diff --git a/apps/desktop/src/main/queries/messages/message-reactions-get.ts b/apps/desktop/src/main/queries/messages/message-reactions-get.tsnew file mode 100644index 00000000..8ba8c302--- /dev/null+++ b/apps/desktop/src/main/queries/messages/message-reactions-get.ts@@ -0,0 +1,112 @@+import { compareString } from '@colanode/core';+import { sql } from 'kysely';++import { databaseService } from '@/main/data/database-service';+import { SelectMessage } from '@/main/data/workspace/schema';+import { ChangeCheckResult, QueryHandler } from '@/main/types';+import { mapMessage } from '@/main/utils';+import { MessageReactionsGetQueryInput } from '@/shared/queries/messages/message-reactions-get';+import { Event } from '@/shared/types/events';+import { MessageNode, MessageReactionsCount } from '@/shared/types/messages';++interface MessageReactionsCountRow {+ reaction: string;+ count: number;+ reacted: number;+}++export class MessageReactionsGetQueryHandler+ implements QueryHandler<MessageReactionsGetQueryInput>+{+ public async handleQuery(+ input: MessageReactionsGetQueryInput+ ): Promise<MessageReactionsCount[]> {+ return this.fetchMessageReactions(input);+ }++ public async checkForChanges(+ event: Event,+ input: MessageReactionsGetQueryInput,+ _: MessageReactionsCount[]+ ): Promise<ChangeCheckResult<MessageReactionsGetQueryInput>> {+ if (+ event.type === 'workspace_deleted' &&+ event.workspace.userId === input.userId+ ) {+ return {+ hasChanges: true,+ result: [],+ };+ }++ if (+ event.type === 'message_reaction_created' &&+ event.userId === input.userId &&+ event.messageReaction.messageId === input.messageId+ ) {+ const newResult = await this.handleQuery(input);++ return {+ hasChanges: true,+ result: newResult,+ };+ }++ if (+ event.type === 'message_reaction_deleted' &&+ event.userId === input.userId &&+ event.messageReaction.messageId === input.messageId+ ) {+ const newResult = await this.handleQuery(input);++ return {+ hasChanges: true,+ result: newResult,+ };+ }++ return {+ hasChanges: false,+ };+ }++ private async fetchMessageReactions(+ input: MessageReactionsGetQueryInput+ ): Promise<MessageReactionsCount[]> {+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const result = await sql<MessageReactionsCountRow>`+ SELECT+ reaction,+ COUNT(reaction) as count,+ MAX(CASE+ WHEN collaborator_id = ${input.userId} THEN 1+ ELSE 0+ END) as reacted+ FROM message_reactions+ WHERE message_id = ${input.messageId}+ GROUP BY reaction+ `.execute(workspaceDatabase);++ if (result.rows.length === 0) {+ return [];+ }++ const counts = result.rows.map((row) => {+ return {+ reaction: row.reaction,+ count: row.count,+ reacted: row.reacted === 1,+ };+ });++ return counts;+ }++ private buildMessages = (rows: SelectMessage[]): MessageNode[] => {+ const messages = rows.map(mapMessage);+ return messages.sort((a, b) => compareString(a.id, b.id));+ };+}diff --git a/apps/desktop/src/main/services/message-service.ts b/apps/desktop/src/main/services/message-service.tsnew file mode 100644index 00000000..503ac43c--- /dev/null+++ b/apps/desktop/src/main/services/message-service.ts@@ -0,0 +1,161 @@+import { ServerMessage, ServerMessageReaction } from '@colanode/core';++import { mapMessage, mapMessageReaction } from '@/main/utils';+import { databaseService } from '@/main/data/database-service';+import { createDebugger } from '@/main/debugger';+import { eventBus } from '@/shared/lib/event-bus';++class MessageService {+ private readonly debug = createDebugger('service:message');++ public async syncServerMessage(userId: string, message: ServerMessage) {+ const workspaceDatabase =+ await databaseService.getWorkspaceDatabase(userId);++ const existingMessage = await workspaceDatabase+ .selectFrom('messages')+ .selectAll()+ .where('id', '=', message.id)+ .executeTakeFirst();++ const version = BigInt(message.version);+ if (existingMessage) {+ if (existingMessage.version === version) {+ this.debug(`Server message ${message.id} is already synced`);+ return;+ }++ const updatedMessage = await workspaceDatabase+ .updateTable('messages')+ .returningAll()+ .set({+ content: JSON.stringify(message.content),+ type: message.type,+ updated_at: message.updatedAt,+ updated_by: message.updatedBy,+ root_id: message.rootId,+ version,+ })+ .where('id', '=', message.id)+ .executeTakeFirst();++ if (!updatedMessage) {+ return;+ }++ eventBus.publish({+ type: 'message_updated',+ userId,+ message: mapMessage(updatedMessage),+ });++ this.debug(`Server message ${message.id} has been synced`);+ return;+ }++ const createdMessage = await workspaceDatabase+ .insertInto('messages')+ .returningAll()+ .values({+ id: message.id,+ version,+ type: message.type,+ parent_id: message.nodeId,+ node_id: message.nodeId,+ root_id: message.rootId,+ content: JSON.stringify(message.content),+ created_at: message.createdAt,+ created_by: message.createdBy,+ updated_at: message.updatedAt,+ updated_by: message.updatedBy,+ })+ .executeTakeFirst();++ if (!createdMessage) {+ return;+ }++ eventBus.publish({+ type: 'message_created',+ userId,+ message: mapMessage(createdMessage),+ });++ this.debug(`Server message ${message.id} has been synced`);+ }++ public async syncServerMessageReaction(+ userId: string,+ messageReaction: ServerMessageReaction+ ) {+ const workspaceDatabase =+ await databaseService.getWorkspaceDatabase(userId);++ const existingMessageReaction = await workspaceDatabase+ .selectFrom('message_reactions')+ .selectAll()+ .where('message_id', '=', messageReaction.messageId)+ .where('collaborator_id', '=', messageReaction.collaboratorId)+ .where('reaction', '=', messageReaction.reaction)+ .executeTakeFirst();++ const version = BigInt(messageReaction.version);+ if (existingMessageReaction) {+ if (existingMessageReaction.version === version) {+ this.debug(+ `Server message reaction for message ${messageReaction.messageId} is already synced`+ );+ return;+ }++ const updatedMessageReaction = await workspaceDatabase+ .updateTable('message_reactions')+ .returningAll()+ .set({+ version,+ })+ .where('message_id', '=', messageReaction.messageId)+ .where('collaborator_id', '=', messageReaction.collaboratorId)+ .where('reaction', '=', messageReaction.reaction)+ .executeTakeFirst();++ if (!updatedMessageReaction) {+ return;+ }++ this.debug(+ `Server message reaction for message ${messageReaction.messageId} has been synced`+ );+ return;+ }++ const createdMessageReaction = await workspaceDatabase+ .insertInto('message_reactions')+ .returningAll()+ .values({+ message_id: messageReaction.messageId,+ collaborator_id: messageReaction.collaboratorId,+ reaction: messageReaction.reaction,+ root_id: messageReaction.rootId,+ created_at: messageReaction.createdAt,+ version,+ })+ .executeTakeFirst();++ if (!createdMessageReaction) {+ return;+ }++ eventBus.publish({+ type: 'message_reaction_created',+ userId,+ messageReaction: mapMessageReaction(createdMessageReaction),+ });++ this.debug(+ `Server message reaction for message ${messageReaction.messageId} has been synced`+ );+ }+}++export const messageService = new MessageService();diff --git a/apps/desktop/src/main/services/node-service.ts b/apps/desktop/src/main/services/node-service.tsindex 442d4b8b..63ee156c 100644--- a/apps/desktop/src/main/services/node-service.ts+++ b/apps/desktop/src/main/services/node-service.ts@@ -161,7 +161,6 @@ class NodeService {id: generateId(IdType.Mutation),node_id: inputItem.id,type: 'apply_create_transaction',- key: `transaction_${createdTransaction.id}`,data: JSON.stringify(mapTransaction(createdTransaction)),created_at: createdAt,retries: 0,@@ -208,7 +207,6 @@ class NodeService {eventBus.publish({type: 'mutation_created',userId,- mutationId: createdMutation.id,});}}@@ -338,7 +336,6 @@ class NodeService {id: generateId(IdType.Mutation),node_id: nodeId,type: 'apply_update_transaction',- key: `transaction_${createdTransaction.id}`,data: JSON.stringify(mapTransaction(createdTransaction)),created_at: updatedAt,retries: 0,@@ -397,7 +394,6 @@ class NodeService {eventBus.publish({type: 'mutation_created',userId,- mutationId: createdMutation.id,});} else {this.debug(`Failed to create mutation for node ${nodeId}`);@@ -498,7 +494,6 @@ class NodeService {id: generateId(IdType.Mutation),node_id: nodeId,type: 'apply_delete_transaction',- key: `transaction_${createdTransaction.id}`,data: JSON.stringify(mapTransaction(createdTransaction)),created_at: new Date().toISOString(),retries: 0,@@ -528,7 +523,6 @@ class NodeService {eventBus.publish({type: 'mutation_created',userId,- mutationId: createdMutation.id,});} else {this.debug(`Failed to create mutation for node ${nodeId}`);diff --git a/apps/desktop/src/main/services/radar-service.ts b/apps/desktop/src/main/services/radar-service.tsindex d45c5295..07ebd6c2 100644--- a/apps/desktop/src/main/services/radar-service.ts+++ b/apps/desktop/src/main/services/radar-service.ts@@ -100,7 +100,6 @@ class RadarWorkspace {.on('parent_interactions.user_id', '=', this.workspace.userId)).select(['node.id as node_id', 'node.parent_id as parent_id'])- .where('node.type', '=', 'message').where('node.created_by', '!=', this.workspace.userId).where('node_interactions.last_seen_at', 'is', null).where('parent_interactions.last_seen_at', 'is not', null)@@ -158,10 +157,6 @@ class RadarWorkspace {return;}- if (node.type !== 'message') {- return;- }-const parentInteraction = await this.workspaceDatabase.selectFrom('interactions').selectAll()diff --git a/apps/desktop/src/main/services/socket-connection.ts b/apps/desktop/src/main/services/socket-connection.tsindex d2663929..397951b4 100644--- a/apps/desktop/src/main/services/socket-connection.ts+++ b/apps/desktop/src/main/services/socket-connection.ts@@ -84,6 +84,19 @@ export class SocketConnection {message.rootId);filesConsumer?.processFiles(message);+ } else if (message.type === 'messages_batch') {+ const messagesConsumer = syncService.getMessagesConsumer(+ message.userId,+ message.rootId+ );+ messagesConsumer?.processMessages(message);+ } else if (message.type === 'message_reactions_batch') {+ const messageReactionsConsumer =+ syncService.getMessageReactionsConsumer(+ message.userId,+ message.rootId+ );+ messageReactionsConsumer?.processMessageReactions(message);} else if (message.type === 'account_updated') {scheduler.trigger({type: 'sync_account',diff --git a/apps/desktop/src/main/services/sync-service.ts b/apps/desktop/src/main/services/sync-service.tsindex 7212e914..e17cf588 100644--- a/apps/desktop/src/main/services/sync-service.ts+++ b/apps/desktop/src/main/services/sync-service.ts@@ -5,11 +5,15 @@ import { CollaborationsConsumer } from '@/main/consumers/collaborations';import { InteractionsConsumer } from '@/main/consumers/interactions';import { FilesConsumer } from '@/main/consumers/files';import { createDebugger } from '@/main/debugger';+import { MessagesConsumer } from '@/main/consumers/messages';+import { MessageReactionsConsumer } from '@/main/consumers/message-reactions';export type NodeConsumersWrapper = {transactions: TransactionsConsumer;interactions: InteractionsConsumer;files: FilesConsumer;+ messages: MessagesConsumer;+ messageReactions: MessageReactionsConsumer;};export type ConsumersWrapper = {@@ -87,10 +91,28 @@ class SyncService {);await filesConsumer.init();+ const messagesConsumer = new MessagesConsumer(+ userId,+ accountId,+ rootId,+ workspaceDatabase+ );+ await messagesConsumer.init();++ const messageReactionsConsumer = new MessageReactionsConsumer(+ userId,+ accountId,+ rootId,+ workspaceDatabase+ );+ await messageReactionsConsumer.init();+consumers.nodes[rootId] = {transactions: transactionsConsumer,interactions: interactionsConsumer,files: filesConsumer,+ messages: messagesConsumer,+ messageReactions: messageReactionsConsumer,};}@@ -132,6 +154,20 @@ class SyncService {): FilesConsumer | undefined {return this.users.get(userId)?.nodes[rootId]?.files;}++ public getMessagesConsumer(+ userId: string,+ rootId: string+ ): MessagesConsumer | undefined {+ return this.users.get(userId)?.nodes[rootId]?.messages;+ }++ public getMessageReactionsConsumer(+ userId: string,+ rootId: string+ ): MessageReactionsConsumer | undefined {+ return this.users.get(userId)?.nodes[rootId]?.messageReactions;+ }}export const syncService = new SyncService();diff --git a/apps/desktop/src/main/utils.ts b/apps/desktop/src/main/utils.tsindex da9d1135..87a92f82 100644--- a/apps/desktop/src/main/utils.ts+++ b/apps/desktop/src/main/utils.ts@@ -22,6 +22,8 @@ import {SelectFile,SelectFileState,SelectInteraction,+ SelectMessage,+ SelectMessageReaction,SelectMutation,SelectNode,SelectTransaction,@@ -34,6 +36,7 @@ import { Server } from '@/shared/types/servers';import { User } from '@/shared/types/users';import { File, FileState } from '@/shared/types/files';import { Workspace, WorkspaceCredentials } from '@/shared/types/workspaces';+import { MessageNode, MessageReaction } from '@/shared/types/messages';export const appPath = app.getPath('userData');@@ -232,43 +235,12 @@ export const mapTransaction = (row: SelectTransaction): LocalTransaction => {};export const mapMutation = (row: SelectMutation): Mutation => {- if (row.type === 'apply_create_transaction') {- return {- id: row.id,- type: 'apply_create_transaction',- data: JSON.parse(row.data),- createdAt: row.created_at,- };- }-- if (row.type === 'apply_update_transaction') {- return {- id: row.id,- type: 'apply_update_transaction',- data: JSON.parse(row.data),- createdAt: row.created_at,- };- }-- if (row.type === 'apply_delete_transaction') {- return {- id: row.id,- type: 'apply_delete_transaction',- data: JSON.parse(row.data),- createdAt: row.created_at,- };- }-- if (row.type === 'create_file') {- return {- id: row.id,- type: 'create_file',- data: JSON.parse(row.data),- createdAt: row.created_at,- };- }-- throw new Error('Invalid mutation type');+ return {+ id: row.id,+ type: row.type,+ data: JSON.parse(row.data),+ createdAt: row.created_at,+ };};export const mapServer = (row: SelectServer): Server => {@@ -283,6 +255,33 @@ export const mapServer = (row: SelectServer): Server => {};};+export const mapMessage = (row: SelectMessage): MessageNode => {+ return {+ id: row.id,+ type: row.type,+ parentId: row.parent_id,+ rootId: row.root_id,+ content: JSON.parse(row.content),+ createdAt: row.created_at,+ createdBy: row.created_by,+ updatedAt: row.updated_at,+ updatedBy: row.updated_by,+ version: row.version,+ };+};++export const mapMessageReaction = (+ row: SelectMessageReaction+): MessageReaction => {+ return {+ messageId: row.message_id,+ collaboratorId: row.collaborator_id,+ reaction: row.reaction,+ rootId: row.root_id,+ createdAt: row.created_at,+ };+};+export const mapFile = (row: SelectFile): File => {return {id: row.id,diff --git a/apps/desktop/src/renderer/components/channels/channel-body.tsx b/apps/desktop/src/renderer/components/channels/channel-body.tsxindex cdf6edfe..02671434 100644--- a/apps/desktop/src/renderer/components/channels/channel-body.tsx+++ b/apps/desktop/src/renderer/components/channels/channel-body.tsx@@ -34,5 +34,11 @@ export const ChannelBody = ({ channel, role }: ChannelBodyProps) => {return () => clearInterval(interval);}, [channel.id, channel.type, channel.transactionId]);- return <Conversation conversationId={channel.id} role={role} />;+ return (+ <Conversation+ conversationId={channel.id}+ rootId={channel.rootId}+ role={role}+ />+ );};diff --git a/apps/desktop/src/renderer/components/chats/chat-body.tsx b/apps/desktop/src/renderer/components/chats/chat-body.tsxindex 37cc48c5..ba7a2531 100644--- a/apps/desktop/src/renderer/components/chats/chat-body.tsx+++ b/apps/desktop/src/renderer/components/chats/chat-body.tsx@@ -34,5 +34,7 @@ export const ChatBody = ({ chat, role }: ChatBodyProps) => {return () => clearInterval(interval);}, [chat.id, chat.type, chat.transactionId]);- return <Conversation conversationId={chat.id} role={role} />;+ return (+ <Conversation conversationId={chat.id} rootId={chat.rootId} role={role} />+ );};diff --git a/apps/desktop/src/renderer/components/layouts/node-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/layouts/node-breadcrumb-item.tsxindex 66d6b2ec..0e71803c 100644--- a/apps/desktop/src/renderer/components/layouts/node-breadcrumb-item.tsx+++ b/apps/desktop/src/renderer/components/layouts/node-breadcrumb-item.tsx@@ -4,7 +4,6 @@ import { ChannelBreadcrumbItem } from '@/renderer/components/channels/channel-brimport { ChatBreadcrumbItem } from '@/renderer/components/chats/chat-breadcrumb-item';import { DatabaseBreadcrumbItem } from '@/renderer/components/databases/database-breadcrumb-item';import { FolderBreadcrumbItem } from '@/renderer/components/folders/folder-breadcrumb-item';-import { MessageBreadcrumbItem } from '@/renderer/components/messages/message-breadcrumb-item';import { PageBreadcrumbItem } from '@/renderer/components/pages/page-breadcrumb-item';import { RecordBreadcrumbItem } from '@/renderer/components/records/record-breadcrumb-item';import { SpaceBreadcrumbItem } from '@/renderer/components/spaces/space-breadcrumb-item';@@ -29,8 +28,6 @@ export const NodeBreadcrumbItem = ({ node }: NodeBreadcrumbItemProps) => {return <RecordBreadcrumbItem node={node} />;case 'folder':return <FolderBreadcrumbItem node={node} />;- case 'message':- return <MessageBreadcrumbItem node={node} />;default:return null;}diff --git a/apps/desktop/src/renderer/components/messages/conversation.tsx b/apps/desktop/src/renderer/components/messages/conversation.tsxindex 378632f0..3be0f878 100644--- a/apps/desktop/src/renderer/components/messages/conversation.tsx+++ b/apps/desktop/src/renderer/components/messages/conversation.tsx@@ -17,10 +17,15 @@ import { useWorkspace } from '@/renderer/contexts/workspace';interface ConversationProps {conversationId: string;+ rootId: string;role: NodeRole;}-export const Conversation = ({ conversationId, role }: ConversationProps) => {+export const Conversation = ({+ conversationId,+ rootId,+ role,+}: ConversationProps) => {const workspace = useWorkspace();const viewportRef = React.useRef<HTMLDivElement>(null);@@ -79,6 +84,7 @@ export const Conversation = ({ conversationId, role }: ConversationProps) => {value={{id: conversationId,role,+ rootId,canCreateMessage: isCollaborator,onReply: (message) => {if (messageCreateRef.current) {diff --git a/apps/desktop/src/renderer/components/messages/message-actions.tsx b/apps/desktop/src/renderer/components/messages/message-actions.tsxindex fb172880..d9e25794 100644--- a/apps/desktop/src/renderer/components/messages/message-actions.tsx+++ b/apps/desktop/src/renderer/components/messages/message-actions.tsx@@ -1,4 +1,3 @@-import { MessageNode } from '@colanode/core';import { MessagesSquare, Reply } from 'lucide-react';import React from 'react';@@ -10,6 +9,7 @@ import { useConversation } from '@/renderer/contexts/conversation';import { useWorkspace } from '@/renderer/contexts/workspace';import { useMutation } from '@/renderer/hooks/use-mutation';import { toast } from '@/renderer/hooks/use-toast';+import { MessageNode } from '@/shared/types/messages';const MessageAction = ({ children }: { children: React.ReactNode }) => {return (@@ -49,6 +49,7 @@ export const MessageActions = ({ message }: MessageActionsProps) => {messageId: message.id,userId: workspace.userId,reaction,+ rootId: conversation.rootId,},onError(error) {toast({@@ -92,6 +93,7 @@ export const MessageActions = ({ message }: MessageActionsProps) => {messageId: message.id,userId: workspace.userId,reaction,+ rootId: conversation.rootId,},onError(error) {toast({diff --git a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsxindex 853d67e9..3b9e5a0f 100644--- a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx+++ b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx@@ -1,8 +1,7 @@-import { MessageNode } from '@colanode/core';-import { Avatar } from '@/renderer/components/avatars/avatar';import { useWorkspace } from '@/renderer/contexts/workspace';import { useQuery } from '@/renderer/hooks/use-query';+import { MessageNode } from '@/shared/types/messages';interface MessageAuthorAvatarProps {message: MessageNode;diff --git a/apps/desktop/src/renderer/components/messages/message-author-name.tsx b/apps/desktop/src/renderer/components/messages/message-author-name.tsxindex 42349e8e..aef47ff0 100644--- a/apps/desktop/src/renderer/components/messages/message-author-name.tsx+++ b/apps/desktop/src/renderer/components/messages/message-author-name.tsx@@ -1,5 +1,4 @@-import { MessageNode } from '@colanode/core';-+import { MessageNode } from '@/shared/types/messages';import { useWorkspace } from '@/renderer/contexts/workspace';import { useQuery } from '@/renderer/hooks/use-query';import { cn } from '@/shared/lib/utils';diff --git a/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsxdeleted file mode 100644index b4a903e5..00000000--- a/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { MessageNode } from '@colanode/core';-import { MessageCircleMore } from 'lucide-react';--interface MessageBreadcrumbItemProps {- node: MessageNode;-}--export const MessageBreadcrumbItem = ({ node }: MessageBreadcrumbItemProps) => {- return (- <div key={node.id} className="flex items-center space-x-2">- <MessageCircleMore className="size-5" />- <span>Message</span>- </div>- );-};diff --git a/apps/desktop/src/renderer/components/messages/message-content.tsx b/apps/desktop/src/renderer/components/messages/message-content.tsxindex d734c0d1..cd7ca830 100644--- a/apps/desktop/src/renderer/components/messages/message-content.tsx+++ b/apps/desktop/src/renderer/components/messages/message-content.tsx@@ -1,5 +1,4 @@-import { MessageNode } from '@colanode/core';-+import { MessageNode } from '@/shared/types/messages';import { NodeRenderer } from '@/renderer/editor/renderers/node';import { mapBlocksToContents } from '@/shared/lib/editor';@@ -8,7 +7,7 @@ interface MessageContentProps {}export const MessageContent = ({ message }: MessageContentProps) => {- const nodeBlocks = Object.values(message.attributes.content ?? {});+ const nodeBlocks = Object.values(message.content.blocks ?? {});const contents = mapBlocksToContents(message.id, nodeBlocks);return (diff --git a/apps/desktop/src/renderer/components/messages/message-create.tsx b/apps/desktop/src/renderer/components/messages/message-create.tsxindex 72c9eaa3..8ab12dd5 100644--- a/apps/desktop/src/renderer/components/messages/message-create.tsx+++ b/apps/desktop/src/renderer/components/messages/message-create.tsx@@ -1,4 +1,3 @@-import { MessageNode } from '@colanode/core';import { JSONContent } from '@tiptap/core';import { Plus, Search, Send, Upload } from 'lucide-react';import React from 'react';@@ -20,7 +19,7 @@ import { useWorkspace } from '@/renderer/contexts/workspace';import { useMutation } from '@/renderer/hooks/use-mutation';import { toast } from '@/renderer/hooks/use-toast';import { editorHasContent } from '@/shared/lib/editor';-+import { MessageNode } from '@/shared/types/messages';export interface MessageCreateRefProps {setReplyTo: (replyTo: MessageNode) => void;}@@ -71,6 +70,7 @@ export const MessageCreate = React.forwardRef<MessageCreateRefProps>(content: content,userId: workspace.userId,referenceId: replyTo?.id,+ rootId: conversation.rootId,},onSuccess: () => {setReplyTo(null);diff --git a/apps/desktop/src/renderer/components/messages/message-reactions.tsx b/apps/desktop/src/renderer/components/messages/message-reactions.tsxindex 8e333739..352a2ca5 100644--- a/apps/desktop/src/renderer/components/messages/message-reactions.tsx+++ b/apps/desktop/src/renderer/components/messages/message-reactions.tsx@@ -1,10 +1,10 @@-import { MessageNode } from '@colanode/core';-+import { MessageNode } from '@/shared/types/messages';import { EmojiElement } from '@/renderer/components/emojis/emoji-element';import { useWorkspace } from '@/renderer/contexts/workspace';import { useMutation } from '@/renderer/hooks/use-mutation';import { cn } from '@/shared/lib/utils';import { toast } from '@/renderer/hooks/use-toast';+import { useQuery } from '@/renderer/hooks/use-query';interface MessageReactionsProps {message: MessageNode;@@ -14,14 +14,13 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {const workspace = useWorkspace();const { mutate, isPending } = useMutation();- const reactionCounts = Object.entries(message.attributes.reactions ?? {})- .map(([reaction, users]) => ({- reaction,- count: users.length,- isReactedTo: users.includes(workspace.userId),- }))- .filter((reactionCount) => reactionCount.count > 0);+ const { data } = useQuery({+ type: 'message_reactions_get',+ messageId: message.id,+ userId: workspace.userId,+ });+ const reactionCounts = data ?? [];if (reactionCounts.length === 0) {return null;}@@ -33,7 +32,7 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {return null;}- const hasReacted = reaction.isReactedTo;+ const hasReacted = reaction.reacted;return (<divkey={reaction.reaction}@@ -51,7 +50,7 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {reactionCounts.some((reactionCount) =>reactionCount.reaction === reaction.reaction &&- reactionCount.isReactedTo+ reactionCount.reacted)) {mutate({@@ -59,6 +58,7 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {type: 'message_reaction_delete',messageId: message.id,userId: workspace.userId,+ rootId: message.rootId,reaction: reaction.reaction,},onError(error) {@@ -75,6 +75,7 @@ export const MessageReactions = ({ message }: MessageReactionsProps) => {type: 'message_reaction_create',messageId: message.id,userId: workspace.userId,+ rootId: message.rootId,reaction: reaction.reaction,},onError(error) {diff --git a/apps/desktop/src/renderer/components/messages/message-reference.tsx b/apps/desktop/src/renderer/components/messages/message-reference.tsxindex b8dbb4d9..4c286636 100644--- a/apps/desktop/src/renderer/components/messages/message-reference.tsx+++ b/apps/desktop/src/renderer/components/messages/message-reference.tsx@@ -1,36 +1,35 @@-import { MessageNode } from '@colanode/core';+// import { MessageNode } from '@/shared/types/messages';+// import { MessageAuthorAvatar } from '@/renderer/components/messages/message-author-avatar';+// import { MessageAuthorName } from '@/renderer/components/messages/message-author-name';+// import { MessageContent } from '@/renderer/components/messages/message-content';+// import { useWorkspace } from '@/renderer/contexts/workspace';+// import { useQuery } from '@/renderer/hooks/use-query';-import { MessageAuthorAvatar } from '@/renderer/components/messages/message-author-avatar';-import { MessageAuthorName } from '@/renderer/components/messages/message-author-name';-import { MessageContent } from '@/renderer/components/messages/message-content';-import { useWorkspace } from '@/renderer/contexts/workspace';-import { useQuery } from '@/renderer/hooks/use-query';+// interface MessageReferenceProps {+// messageId: string;+// }-interface MessageReferenceProps {- messageId: string;-}+// export const MessageReference = ({ messageId }: MessageReferenceProps) => {+// const workspace = useWorkspace();+// const { data } = useQuery({+// type: 'node_get',+// nodeId: messageId,+// userId: workspace.userId,+// });-export const MessageReference = ({ messageId }: MessageReferenceProps) => {- const workspace = useWorkspace();- const { data } = useQuery({- type: 'node_get',- nodeId: messageId,- userId: workspace.userId,- });+// if (!data || data.type !== 'message') {+// return null;+// }- if (!data || data.type !== 'message') {- return null;- }+// const message = data as MessageNode;- const message = data as MessageNode;-- return (- <div className="flex flex-row gap-2 border-l-4 p-2">- <MessageAuthorAvatar message={message} className="size-5 mt-1" />- <div className='"flex-grow flex-col gap-1'>- <MessageAuthorName message={message} />- <MessageContent message={message} />- </div>- </div>- );-};+// return (+// <div className="flex flex-row gap-2 border-l-4 p-2">+// <MessageAuthorAvatar message={message} className="size-5 mt-1" />+// <div className='"flex-grow flex-col gap-1'>+// <MessageAuthorName message={message} />+// <MessageContent message={message} />+// </div>+// </div>+// );+// };diff --git a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsxindex eaae4f98..d2458022 100644--- a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx+++ b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx@@ -1,6 +1,6 @@-import { MessageNode } from '@colanode/core';import { CircleX } from 'lucide-react';+import { MessageNode } from '@/shared/types/messages';import { useWorkspace } from '@/renderer/contexts/workspace';import { useQuery } from '@/renderer/hooks/use-query';diff --git a/apps/desktop/src/renderer/components/messages/message-time.tsx b/apps/desktop/src/renderer/components/messages/message-time.tsxindex 3eaeea33..5e14a57f 100644--- a/apps/desktop/src/renderer/components/messages/message-time.tsx+++ b/apps/desktop/src/renderer/components/messages/message-time.tsx@@ -1,11 +1,11 @@-import { formatDate, MessageNode, timeAgo } from '@colanode/core';+import { formatDate, timeAgo } from '@colanode/core';import {Tooltip,TooltipContent,TooltipTrigger,} from '@/renderer/components/ui/tooltip';-+import { MessageNode } from '@/shared/types/messages';interface MessageTimeProps {message: MessageNode;}diff --git a/apps/desktop/src/renderer/components/messages/message.tsx b/apps/desktop/src/renderer/components/messages/message.tsxindex 03185bd8..9a47a143 100644--- a/apps/desktop/src/renderer/components/messages/message.tsx+++ b/apps/desktop/src/renderer/components/messages/message.tsx@@ -1,4 +1,3 @@-import { MessageNode } from '@colanode/core';import { InView } from 'react-intersection-observer';import { MessageActions } from '@/renderer/components/messages/message-actions';@@ -6,11 +5,10 @@ import { MessageAuthorAvatar } from '@/renderer/components/messages/message-authimport { MessageAuthorName } from '@/renderer/components/messages/message-author-name';import { MessageContent } from '@/renderer/components/messages/message-content';import { MessageReactions } from '@/renderer/components/messages/message-reactions';-import { MessageReference } from '@/renderer/components/messages/message-reference';import { MessageTime } from '@/renderer/components/messages/message-time';-import { useRadar } from '@/renderer/contexts/radar';-import { useWorkspace } from '@/renderer/contexts/workspace';-+// import { useRadar } from '@/renderer/contexts/radar';+// import { useWorkspace } from '@/renderer/contexts/workspace';+import { MessageNode } from '@/shared/types/messages';interface MessageProps {message: MessageNode;previousMessage?: MessageNode | null;@@ -35,8 +33,8 @@ const shouldDisplayAuthor = (};export const Message = ({ message, previousMessage }: MessageProps) => {- const workspace = useWorkspace();- const radar = useRadar();+ // const workspace = useWorkspace();+ // const radar = useRadar();const displayAuthor = shouldDisplayAuthor(message, previousMessage);return (@@ -62,19 +60,19 @@ export const Message = ({ message, previousMessage }: MessageProps) => {rootMargin="50px"onChange={(inView) => {if (inView) {- radar.markAsSeen(- workspace.userId,- message.id,- message.type,- message.transactionId- );+ // radar.markAsSeen(+ // workspace.userId,+ // message.id,+ // message.type,+ // message.transactionId+ // );}}}><MessageActions message={message} />- {message.attributes.subtype === 'reply' && (- <MessageReference messageId={message.attributes.referenceId} />- )}+ {/* {message.type === 'reply' && (+ <MessageReference messageId={message.referenceId} />+ )} */}<MessageContent message={message} /><MessageReactions message={message} /></InView>diff --git a/apps/desktop/src/renderer/contexts/conversation.ts b/apps/desktop/src/renderer/contexts/conversation.tsindex 7df0e35c..0ab55291 100644--- a/apps/desktop/src/renderer/contexts/conversation.ts+++ b/apps/desktop/src/renderer/contexts/conversation.ts@@ -1,8 +1,11 @@-import { MessageNode,NodeRole } from '@colanode/core';+import { NodeRole } from '@colanode/core';import { createContext, useContext } from 'react';+import { MessageNode } from '@/shared/types/messages';+interface ConversationContext {id: string;+ rootId: string;role: NodeRole;canCreateMessage: boolean;onReply: (message: MessageNode) => void;diff --git a/apps/desktop/src/shared/mutations/messages/message-create.ts b/apps/desktop/src/shared/mutations/messages/message-create.tsindex a4030eb1..4bc5b8d3 100644--- a/apps/desktop/src/shared/mutations/messages/message-create.ts+++ b/apps/desktop/src/shared/mutations/messages/message-create.ts@@ -4,6 +4,7 @@ export type MessageCreateMutationInput = {type: 'message_create';userId: string;conversationId: string;+ rootId: string;content: JSONContent;referenceId?: string;};diff --git a/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts b/apps/desktop/src/shared/mutations/messages/message-reaction-create.tsindex 3dd5a6d0..6c341708 100644--- a/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts+++ b/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts@@ -2,6 +2,7 @@ export type MessageReactionCreateMutationInput = {type: 'message_reaction_create';userId: string;messageId: string;+ rootId: string;reaction: string;};diff --git a/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/shared/mutations/messages/message-reaction-delete.tsindex e759dba4..51dbdc22 100644--- a/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts+++ b/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts@@ -2,6 +2,7 @@ export type MessageReactionDeleteMutationInput = {type: 'message_reaction_delete';userId: string;messageId: string;+ rootId: string;reaction: string;};diff --git a/apps/desktop/src/shared/queries/messages/message-list.ts b/apps/desktop/src/shared/queries/messages/message-list.tsindex dcf6ca05..7eac8c77 100644--- a/apps/desktop/src/shared/queries/messages/message-list.ts+++ b/apps/desktop/src/shared/queries/messages/message-list.ts@@ -1,4 +1,4 @@-import { MessageNode } from '@colanode/core';+import { MessageNode } from '@/shared/types/messages';export type MessageListQueryInput = {type: 'message_list';diff --git a/apps/desktop/src/shared/queries/messages/message-reactions-get.ts b/apps/desktop/src/shared/queries/messages/message-reactions-get.tsnew file mode 100644index 00000000..a49cc1bd--- /dev/null+++ b/apps/desktop/src/shared/queries/messages/message-reactions-get.ts@@ -0,0 +1,16 @@+import { MessageReactionsCount } from '@/shared/types/messages';++export type MessageReactionsGetQueryInput = {+ type: 'message_reactions_get';+ messageId: string;+ userId: string;+};++declare module '@/shared/queries' {+ interface QueryMap {+ message_reactions_get: {+ input: MessageReactionsGetQueryInput;+ output: MessageReactionsCount[];+ };+ }+}diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.tsindex 92966231..9968b2f9 100644--- a/apps/desktop/src/shared/types/events.ts+++ b/apps/desktop/src/shared/types/events.ts@@ -1,5 +1,6 @@import { Node } from '@colanode/core';+import { MessageNode, MessageReaction } from '@/shared/types/messages';import { Account } from '@/shared/types/accounts';import { Interaction } from '@/shared/types/interactions';import { Server } from '@/shared/types/servers';@@ -43,6 +44,36 @@ export type NodeDeletedEvent = {node: Node;};+export type MessageCreatedEvent = {+ type: 'message_created';+ userId: string;+ message: MessageNode;+};++export type MessageUpdatedEvent = {+ type: 'message_updated';+ userId: string;+ message: MessageNode;+};++export type MessageDeletedEvent = {+ type: 'message_deleted';+ userId: string;+ message: MessageNode;+};++export type MessageReactionCreatedEvent = {+ type: 'message_reaction_created';+ userId: string;+ messageReaction: MessageReaction;+};++export type MessageReactionDeletedEvent = {+ type: 'message_reaction_deleted';+ userId: string;+ messageReaction: MessageReaction;+};+export type FileCreatedEvent = {type: 'file_created';userId: string;@@ -132,7 +163,6 @@ export type RadarDataUpdatedEvent = {export type MutationCreatedEvent = {type: 'mutation_created';userId: string;- mutationId: string;};export type CollaborationCreatedEvent = {@@ -177,6 +207,11 @@ export type Event =| NodeCreatedEvent| NodeUpdatedEvent| NodeDeletedEvent+ | MessageCreatedEvent+ | MessageUpdatedEvent+ | MessageDeletedEvent+ | MessageReactionCreatedEvent+ | MessageReactionDeletedEvent| AccountCreatedEvent| AccountUpdatedEvent| AccountDeletedEventdiff --git a/apps/desktop/src/shared/types/messages.ts b/apps/desktop/src/shared/types/messages.tsnew file mode 100644index 00000000..e8a3d6a0--- /dev/null+++ b/apps/desktop/src/shared/types/messages.ts@@ -0,0 +1,28 @@+import { MessageContent, MessageType } from '@colanode/core';++export type MessageNode = {+ id: string;+ type: MessageType;+ parentId: string;+ rootId: string;+ content: MessageContent;+ createdAt: string;+ createdBy: string;+ updatedAt: string | null;+ updatedBy: string | null;+ version: bigint;+};++export type MessageReaction = {+ messageId: string;+ collaboratorId: string;+ rootId: string;+ reaction: string;+ createdAt: string;+};++export type MessageReactionsCount = {+ reaction: string;+ count: number;+ reacted: boolean;+};diff --git a/apps/server/src/consumers/message-reactions.ts b/apps/server/src/consumers/message-reactions.tsnew file mode 100644index 00000000..8f8e32cf--- /dev/null+++ b/apps/server/src/consumers/message-reactions.ts@@ -0,0 +1,85 @@+import {+ ConsumeMessageReactionsMessage,+ MessageReactionsBatchMessage,+} from '@colanode/core';++import { BaseConsumer } from '@/consumers/base';+import { Event } from '@/types/events';+import { database } from '@/data/database';+import { mapMessageReaction } from '@/lib/nodes';+import { ConnectedUser } from '@/types/users';++export class MessageReactionsConsumer extends BaseConsumer {+ private readonly rootId: string;++ constructor(user: ConnectedUser, rootId: string) {+ super(user);+ this.rootId = rootId;+ }++ public processEvent(event: Event): void {+ if (+ event.type === 'message_reaction_created' &&+ event.rootId === this.rootId+ ) {+ this.fetchMessageReactions();+ } else if (+ event.type === 'message_reaction_deleted' &&+ event.rootId === this.rootId+ ) {+ this.fetchMessageReactions();+ }+ }++ public async consume(message: ConsumeMessageReactionsMessage) {+ if (this.status === 'fetching') {+ return;+ }++ const cursor = BigInt(message.cursor);+ if (this.status === 'idle') {+ this.cursor = cursor;+ this.status = 'pending';+ await this.fetchMessageReactions();+ } else if (this.status === 'pending' && this.cursor !== cursor) {+ this.cursor = cursor;+ await this.fetchMessageReactions();+ }+ }++ private async fetchMessageReactions() {+ if (this.cursor === null) {+ return;+ }++ if (this.status !== 'pending') {+ return;+ }++ this.status = 'fetching';+ const unsyncedMessageReactions = await database+ .selectFrom('message_reactions')+ .selectAll()+ .where('root_id', '=', this.rootId)+ .where('version', '>', this.cursor)+ .orderBy('version', 'asc')+ .limit(20)+ .execute();++ if (unsyncedMessageReactions.length === 0) {+ this.status = 'pending';+ return;+ }++ const messageReactions = unsyncedMessageReactions.map(mapMessageReaction);+ const message: MessageReactionsBatchMessage = {+ type: 'message_reactions_batch',+ userId: this.user.userId,+ rootId: this.rootId,+ messageReactions,+ };++ this.status = 'idle';+ this.user.sendMessage(message);+ }+}diff --git a/apps/server/src/consumers/messages.ts b/apps/server/src/consumers/messages.tsnew file mode 100644index 00000000..c57a232b--- /dev/null+++ b/apps/server/src/consumers/messages.ts@@ -0,0 +1,84 @@+import { ConsumeMessagesMessage, MessagesBatchMessage } from '@colanode/core';++import { BaseConsumer } from '@/consumers/base';+import { Event } from '@/types/events';+import { database } from '@/data/database';+import { mapMessage } from '@/lib/nodes';+import { ConnectedUser } from '@/types/users';++export class MessagesConsumer extends BaseConsumer {+ private readonly rootId: string;++ constructor(user: ConnectedUser, rootId: string) {+ super(user);+ this.rootId = rootId;+ }++ public processEvent(event: Event): void {+ if (event.type === 'message_created' && event.rootId === this.rootId) {+ this.fetchMessages();+ } else if (+ event.type === 'message_updated' &&+ event.rootId === this.rootId+ ) {+ this.fetchMessages();+ } else if (+ event.type === 'message_deleted' &&+ event.rootId === this.rootId+ ) {+ this.fetchMessages();+ }+ }++ public async consume(message: ConsumeMessagesMessage) {+ if (this.status === 'fetching') {+ return;+ }++ const cursor = BigInt(message.cursor);+ if (this.status === 'idle') {+ this.cursor = cursor;+ this.status = 'pending';+ await this.fetchMessages();+ } else if (this.status === 'pending' && this.cursor !== cursor) {+ this.cursor = cursor;+ await this.fetchMessages();+ }+ }++ private async fetchMessages() {+ if (this.cursor === null) {+ return;+ }++ if (this.status !== 'pending') {+ return;+ }++ this.status = 'fetching';+ const unsyncedMessages = await database+ .selectFrom('messages')+ .selectAll()+ .where('root_id', '=', this.rootId)+ .where('version', '>', this.cursor)+ .orderBy('version', 'asc')+ .limit(20)+ .execute();++ if (unsyncedMessages.length === 0) {+ this.status = 'pending';+ return;+ }++ const messages = unsyncedMessages.map(mapMessage);+ const message: MessagesBatchMessage = {+ type: 'messages_batch',+ userId: this.user.userId,+ rootId: this.rootId,+ messages,+ };++ this.status = 'idle';+ this.user.sendMessage(message);+ }+}diff --git a/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.ts b/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.tsindex dcf4c396..39e2b2fa 100644--- a/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.ts+++ b/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.ts@@ -8,11 +8,15 @@ import {ApplyUpdateTransactionMutation,ApplyDeleteTransactionMutation,CreateFileMutation,+ CreateMessageMutation,+ CreateMessageReactionMutation,+ DeleteMessageReactionMutation,} from '@colanode/core';import { SelectUser } from '@/data/schema';import { nodeService } from '@/services/node-service';import { fileService } from '@/services/file-service';+import { messageService } from '@/services/message-service';export const mutationsSyncHandler = async (req: Request,@@ -53,6 +57,12 @@ const handleMutation = async (return await handleDeleteTransaction(user, mutation);} else if (mutation.type === 'create_file') {return await handleCreateFile(user, mutation);+ } else if (mutation.type === 'create_message') {+ return await handleCreateMessage(user, mutation);+ } else if (mutation.type === 'create_message_reaction') {+ return await handleCreateMessageReaction(user, mutation);+ } else if (mutation.type === 'delete_message_reaction') {+ return await handleDeleteMessageReaction(user, mutation);} else {return 'error';}@@ -122,3 +132,27 @@ const handleCreateFile = async (const output = await fileService.createFile(user, mutation);return output ? 'success' : 'error';};++const handleCreateMessage = async (+ user: SelectUser,+ mutation: CreateMessageMutation+): Promise<SyncMutationStatus> => {+ const output = await messageService.createMessage(user, mutation);+ return output ? 'success' : 'error';+};++const handleCreateMessageReaction = async (+ user: SelectUser,+ mutation: CreateMessageReactionMutation+): Promise<SyncMutationStatus> => {+ const output = await messageService.createMessageReaction(user, mutation);+ return output ? 'success' : 'error';+};++const handleDeleteMessageReaction = async (+ user: SelectUser,+ mutation: DeleteMessageReactionMutation+): Promise<SyncMutationStatus> => {+ const output = await messageService.deleteMessageReaction(user, mutation);+ return output ? 'success' : 'error';+};diff --git a/apps/server/src/data/migrations.ts b/apps/server/src/data/migrations.tsindex 87f812ca..61401745 100644--- a/apps/server/src/data/migrations.ts+++ b/apps/server/src/data/migrations.ts@@ -253,6 +253,116 @@ const createCollaborationsTable: Migration = {},};+const createMessagesTable: Migration = {+ up: async (db) => {+ await sql`+ CREATE SEQUENCE IF NOT EXISTS messages_version_sequence+ START WITH 1000000000+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+ `.execute(db);++ await db.schema+ .createTable('messages')+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())+ .addColumn('type', 'varchar(30)', (col) => col.notNull())+ .addColumn('parent_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('node_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('content', 'text', (col) => col.notNull())+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())+ .addColumn('updated_at', 'timestamptz')+ .addColumn('updated_by', 'varchar(30)')+ .addColumn('deleted_at', 'timestamptz')+ .addColumn('deleted_by', 'varchar(30)')+ .addColumn('version', 'bigint', (col) =>+ col.notNull().defaultTo(sql`nextval('messages_version_sequence')`)+ )+ .execute();++ await sql`+ CREATE OR REPLACE FUNCTION update_message_version() RETURNS TRIGGER AS $$+ BEGIN+ NEW.version = nextval('messages_version_sequence');+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql;++ CREATE TRIGGER trg_update_message_version+ BEFORE UPDATE ON messages+ FOR EACH ROW+ EXECUTE FUNCTION update_message_version();+ `.execute(db);+ },+ down: async (db) => {+ await sql`+ DROP TRIGGER IF EXISTS trg_update_message_version ON messages;+ DROP FUNCTION IF EXISTS update_message_version();+ `.execute(db);++ await db.schema.dropTable('messages').execute();+ await sql`DROP SEQUENCE IF EXISTS messages_version_sequence`.execute(db);+ },+};++const createMessageReactionsTable: Migration = {+ up: async (db) => {+ await sql`+ CREATE SEQUENCE IF NOT EXISTS message_reactions_version_sequence+ START WITH 1000000000+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+ `.execute(db);++ await db.schema+ .createTable('message_reactions')+ .addColumn('message_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('reaction', 'varchar(30)', (col) => col.notNull())+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())+ .addColumn('deleted_at', 'timestamptz')+ .addColumn('version', 'bigint', (col) =>+ col+ .notNull()+ .defaultTo(sql`nextval('message_reactions_version_sequence')`)+ )+ .addPrimaryKeyConstraint('message_reactions_pkey', [+ 'message_id',+ 'collaborator_id',+ 'reaction',+ ])+ .execute();++ await sql`+ CREATE OR REPLACE FUNCTION update_message_reaction_version() RETURNS TRIGGER AS $$+ BEGIN+ NEW.version = nextval('message_reactions_version_sequence');+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql;+ `.execute(db);+ },+ down: async (db) => {+ await sql`+ DROP TRIGGER IF EXISTS trg_update_message_reaction_version ON message_reactions;+ DROP FUNCTION IF EXISTS update_message_reaction_version();+ `.execute(db);++ await db.schema.dropTable('message_reactions').execute();+ await sql`DROP SEQUENCE IF EXISTS message_reactions_version_sequence`.execute(+ db+ );+ },+};+const createFilesTable: Migration = {up: async (db) => {await sql`@@ -446,8 +556,10 @@ export const databaseMigrations: Record<string, Migration> = {'00004_create_users_table': createUsersTable,'00005_create_nodes_table': createNodesTable,'00006_create_transactions_table': createTransactionsTable,- '00007_create_collaborations_table': createCollaborationsTable,- '00008_create_files_table': createFilesTable,- '00009_create_node_paths_table': createNodePathsTable,- '00010_create_interactions_table': createInteractionsTable,+ '00007_create_messages_table': createMessagesTable,+ '00008_create_message_reactions_table': createMessageReactionsTable,+ '00009_create_files_table': createFilesTable,+ '00010_create_collaborations_table': createCollaborationsTable,+ '00011_create_node_paths_table': createNodePathsTable,+ '00012_create_interactions_table': createInteractionsTable,};diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.tsindex 3c94e1d9..0bf12342 100644--- a/apps/server/src/data/schema.ts+++ b/apps/server/src/data/schema.ts@@ -6,6 +6,7 @@ import {NodeRole,NodeType,WorkspaceRole,+ MessageType,} from '@colanode/core';import {ColumnType,@@ -147,6 +148,42 @@ export type SelectTransaction = Selectable<TransactionTable>;export type CreateTransaction = Insertable<TransactionTable>;export type UpdateTransaction = Updateable<TransactionTable>;+interface MessageTable {+ id: ColumnType<string, string, never>;+ type: ColumnType<MessageType, MessageType, MessageType>;+ parent_id: ColumnType<string, string, never>;+ node_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, never>;+ workspace_id: ColumnType<string, string, never>;+ content: ColumnType<string, string, never>;+ created_at: ColumnType<Date, Date, never>;+ created_by: ColumnType<string, string, never>;+ updated_at: ColumnType<Date | null, Date | null, Date>;+ updated_by: ColumnType<string | null, string | null, string>;+ deleted_at: ColumnType<Date | null, Date | null, Date>;+ deleted_by: ColumnType<string | null, string | null, string>;+ version: ColumnType<bigint, never, never>;+}++export type SelectMessage = Selectable<MessageTable>;+export type CreateMessage = Insertable<MessageTable>;+export type UpdateMessage = Updateable<MessageTable>;++interface MessageReactionTable {+ message_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, never>;+ workspace_id: ColumnType<string, string, never>;+ reaction: ColumnType<string, string, string>;+ created_at: ColumnType<Date, Date, Date>;+ deleted_at: ColumnType<Date | null, Date | null, Date | null>;+ version: ColumnType<bigint, never, never>;+}++export type SelectMessageReaction = Selectable<MessageReactionTable>;+export type CreateMessageReaction = Insertable<MessageReactionTable>;+export type UpdateMessageReaction = Updateable<MessageReactionTable>;+interface FileTable {id: ColumnType<string, string, never>;type: ColumnType<FileType, FileType, FileType>;@@ -210,6 +247,8 @@ export interface DatabaseSchema {users: UserTable;nodes: NodeTable;transactions: TransactionTable;+ messages: MessageTable;+ message_reactions: MessageReactionTable;collaborations: CollaborationTable;files: FileTable;node_paths: NodePathTable;diff --git a/apps/server/src/lib/nodes.ts b/apps/server/src/lib/nodes.tsindex 70f8826e..34b189bc 100644--- a/apps/server/src/lib/nodes.ts+++ b/apps/server/src/lib/nodes.ts@@ -8,6 +8,8 @@ import {ServerCollaboration,ServerFile,ServerInteraction,+ ServerMessage,+ ServerMessageReaction,ServerTransaction,ServerUser,} from '@colanode/core';@@ -21,6 +23,8 @@ import {SelectTransaction,SelectUser,SelectFile,+ SelectMessage,+ SelectMessageReaction,} from '@/data/schema';import { NodeCollaborator } from '@/types/nodes';@@ -179,6 +183,40 @@ export const mapFile = (file: SelectFile): ServerFile => {};};+export const mapMessage = (message: SelectMessage): ServerMessage => {+ return {+ id: message.id,+ type: message.type,+ nodeId: message.node_id,+ parentId: message.parent_id,+ rootId: message.root_id,+ workspaceId: message.workspace_id,+ content: JSON.parse(message.content),+ createdAt: message.created_at.toISOString(),+ createdBy: message.created_by,+ updatedAt: message.updated_at?.toISOString() ?? null,+ updatedBy: message.updated_by ?? null,+ deletedAt: message.deleted_at?.toISOString() ?? null,+ deletedBy: message.deleted_by ?? null,+ version: message.version.toString(),+ };+};++export const mapMessageReaction = (+ messageReaction: SelectMessageReaction+): ServerMessageReaction => {+ return {+ messageId: messageReaction.message_id,+ collaboratorId: messageReaction.collaborator_id,+ reaction: messageReaction.reaction,+ rootId: messageReaction.root_id,+ workspaceId: messageReaction.workspace_id,+ createdAt: messageReaction.created_at.toISOString(),+ deletedAt: messageReaction.deleted_at?.toISOString() ?? null,+ version: messageReaction.version.toString(),+ };+};+export const fetchNode = async (nodeId: string): Promise<SelectNode | null> => {const result = await database.selectFrom('nodes')diff --git a/apps/server/src/services/file-service.ts b/apps/server/src/services/file-service.tsindex 430b0179..13557e9a 100644--- a/apps/server/src/services/file-service.ts+++ b/apps/server/src/services/file-service.ts@@ -45,7 +45,7 @@ class FileService {.returningAll().values({id: mutation.data.id,- type: mutation.data.fileType,+ type: mutation.data.type,parent_id: mutation.data.parentId,root_id: mutation.data.rootId,workspace_id: root.workspace_id,diff --git a/apps/server/src/services/message-service.ts b/apps/server/src/services/message-service.tsnew file mode 100644index 00000000..6d4e6071--- /dev/null+++ b/apps/server/src/services/message-service.ts@@ -0,0 +1,194 @@+import {+ CreateMessageMutation,+ CreateMessageReactionMutation,+ DeleteMessageReactionMutation,+ extractNodeRole,+ hasCollaboratorAccess,+} from '@colanode/core';++import { database } from '@/data/database';+import { SelectUser } from '@/data/schema';+import { mapNode } from '@/lib/nodes';+import { eventBus } from '@/lib/event-bus';++class MessageService {+ public async createMessage(+ user: SelectUser,+ mutation: CreateMessageMutation+ ): Promise<boolean> {+ const existingMessage = await database+ .selectFrom('messages')+ .where('id', '=', mutation.data.id)+ .executeTakeFirst();++ if (existingMessage) {+ return true;+ }++ const root = await database+ .selectFrom('nodes')+ .selectAll()+ .where('id', '=', mutation.data.rootId)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootNode = mapNode(root);+ const role = extractNodeRole(rootNode, user.id);+ if (!hasCollaboratorAccess(role)) {+ return false;+ }++ const createdMessage = await database+ .insertInto('messages')+ .returningAll()+ .values({+ id: mutation.data.id,+ type: mutation.data.type,+ node_id: mutation.data.nodeId,+ parent_id: mutation.data.parentId,+ root_id: mutation.data.rootId,+ workspace_id: root.workspace_id,+ content: JSON.stringify(mutation.data.content),+ created_by: user.id,+ created_at: new Date(mutation.data.createdAt),+ })+ .executeTakeFirst();++ if (!createdMessage) {+ return false;+ }++ eventBus.publish({+ type: 'message_created',+ messageId: createdMessage.id,+ rootId: createdMessage.root_id,+ workspaceId: createdMessage.workspace_id,+ });++ return true;+ }++ public async createMessageReaction(+ user: SelectUser,+ mutation: CreateMessageReactionMutation+ ): Promise<boolean> {+ const message = await database+ .selectFrom('messages')+ .select(['id', 'root_id', 'workspace_id'])+ .where('id', '=', mutation.data.messageId)+ .executeTakeFirst();++ if (!message) {+ return false;+ }++ const root = await database+ .selectFrom('nodes')+ .selectAll()+ .where('id', '=', message.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootNode = mapNode(root);+ const role = extractNodeRole(rootNode, user.id);+ if (!hasCollaboratorAccess(role)) {+ return false;+ }++ const createdMessageReaction = await database+ .insertInto('message_reactions')+ .returningAll()+ .values({+ message_id: mutation.data.messageId,+ collaborator_id: user.id,+ reaction: mutation.data.reaction,+ workspace_id: root.workspace_id,+ root_id: root.id,+ created_at: new Date(mutation.data.createdAt),+ })+ .onConflict((b) =>+ b.columns(['message_id', 'collaborator_id', 'reaction']).doUpdateSet({+ created_at: new Date(mutation.data.createdAt),+ deleted_at: null,+ })+ )+ .executeTakeFirst();++ if (!createdMessageReaction) {+ return false;+ }++ eventBus.publish({+ type: 'message_reaction_created',+ messageId: createdMessageReaction.message_id,+ collaboratorId: createdMessageReaction.collaborator_id,+ rootId: createdMessageReaction.root_id,+ workspaceId: createdMessageReaction.workspace_id,+ });++ return true;+ }++ public async deleteMessageReaction(+ user: SelectUser,+ mutation: DeleteMessageReactionMutation+ ): Promise<boolean> {+ const message = await database+ .selectFrom('messages')+ .select(['id', 'root_id', 'workspace_id'])+ .where('id', '=', mutation.data.messageId)+ .executeTakeFirst();++ if (!message) {+ return false;+ }++ const root = await database+ .selectFrom('nodes')+ .selectAll()+ .where('id', '=', message.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootNode = mapNode(root);+ const role = extractNodeRole(rootNode, user.id);+ if (!hasCollaboratorAccess(role)) {+ return false;+ }++ const deletedMessageReaction = await database+ .updateTable('message_reactions')+ .set({+ deleted_at: new Date(mutation.data.deletedAt),+ })+ .where('message_id', '=', mutation.data.messageId)+ .where('collaborator_id', '=', user.id)+ .where('reaction', '=', mutation.data.reaction)+ .executeTakeFirst();++ if (!deletedMessageReaction) {+ return false;+ }++ eventBus.publish({+ type: 'message_reaction_deleted',+ messageId: mutation.data.messageId,+ collaboratorId: user.id,+ rootId: root.id,+ workspaceId: root.workspace_id,+ });++ return true;+ }+}++export const messageService = new MessageService();diff --git a/apps/server/src/services/socket-connection.ts b/apps/server/src/services/socket-connection.tsindex bbab2d7c..99475889 100644--- a/apps/server/src/services/socket-connection.ts+++ b/apps/server/src/services/socket-connection.ts@@ -7,6 +7,8 @@ import {ConsumeTransactionsMessage,ConsumeInteractionsMessage,ConsumeFilesMessage,+ ConsumeMessagesMessage,+ ConsumeMessageReactionsMessage,} from '@colanode/core';import { interactionService } from '@/services/interaction-service';@@ -25,11 +27,15 @@ import { CollaborationsConsumer } from '@/consumers/collaborations';import { TransactionsConsumer } from '@/consumers/transactions';import { InteractionsConsumer } from '@/consumers/interactions';import { FilesConsumer } from '@/consumers/files';+import { MessagesConsumer } from '@/consumers/messages';+import { MessageReactionsConsumer } from '@/consumers/message-reactions';type NodeConsumersWrapper = {transactions: TransactionsConsumer;interactions: InteractionsConsumer;files: FilesConsumer;+ messages: MessagesConsumer;+ messageReactions: MessageReactionsConsumer;};type ConsumersWrapper = {@@ -92,6 +98,9 @@ export class SocketConnection {for (const node of user.consumers.nodes.values()) {node.transactions.processEvent(event);node.interactions.processEvent(event);+ node.files.processEvent(event);+ node.messages.processEvent(event);+ node.messageReactions.processEvent(event);}}}@@ -110,6 +119,10 @@ export class SocketConnection {this.handleConsumeInteractions(message);} else if (message.type === 'consume_files') {this.handleConsumeFiles(message);+ } else if (message.type === 'consume_messages') {+ this.handleConsumeMessages(message);+ } else if (message.type === 'consume_message_reactions') {+ this.handleConsumeMessageReactions(message);} else if (message.type === 'sync_interactions') {interactionService.syncLocalInteractions(this.account.id, message);}@@ -159,6 +172,11 @@ export class SocketConnection {transactions: new TransactionsConsumer(user.user, message.rootId),interactions: new InteractionsConsumer(user.user, message.rootId),files: new FilesConsumer(user.user, message.rootId),+ messages: new MessagesConsumer(user.user, message.rootId),+ messageReactions: new MessageReactionsConsumer(+ user.user,+ message.rootId+ ),};user.consumers.nodes.set(message.rootId, nodeConsumers);@@ -183,6 +201,11 @@ export class SocketConnection {transactions: new TransactionsConsumer(user.user, message.rootId),interactions: new InteractionsConsumer(user.user, message.rootId),files: new FilesConsumer(user.user, message.rootId),+ messages: new MessagesConsumer(user.user, message.rootId),+ messageReactions: new MessageReactionsConsumer(+ user.user,+ message.rootId+ ),};user.consumers.nodes.set(message.rootId, nodeConsumers);@@ -207,6 +230,11 @@ export class SocketConnection {transactions: new TransactionsConsumer(user.user, message.rootId),interactions: new InteractionsConsumer(user.user, message.rootId),files: new FilesConsumer(user.user, message.rootId),+ messages: new MessagesConsumer(user.user, message.rootId),+ messageReactions: new MessageReactionsConsumer(+ user.user,+ message.rootId+ ),};user.consumers.nodes.set(message.rootId, nodeConsumers);@@ -215,6 +243,66 @@ export class SocketConnection {await nodeConsumers.files.consume(message);}+ private async handleConsumeMessages(message: ConsumeMessagesMessage) {+ this.logger.info(+ `Consume messages from ${this.account.id} and user ${message.userId}`+ );++ const user = await this.getOrCreateUser(message.userId);+ if (user === null) {+ return;+ }++ let nodeConsumers = user.consumers.nodes.get(message.rootId);+ if (!nodeConsumers) {+ nodeConsumers = {+ transactions: new TransactionsConsumer(user.user, message.rootId),+ interactions: new InteractionsConsumer(user.user, message.rootId),+ files: new FilesConsumer(user.user, message.rootId),+ messages: new MessagesConsumer(user.user, message.rootId),+ messageReactions: new MessageReactionsConsumer(+ user.user,+ message.rootId+ ),+ };++ user.consumers.nodes.set(message.rootId, nodeConsumers);+ }++ await nodeConsumers.messages.consume(message);+ }++ private async handleConsumeMessageReactions(+ message: ConsumeMessageReactionsMessage+ ) {+ this.logger.info(+ `Consume message reactions from ${this.account.id} and user ${message.userId}`+ );++ const user = await this.getOrCreateUser(message.userId);+ if (user === null) {+ return;+ }++ let nodeConsumers = user.consumers.nodes.get(message.rootId);+ if (!nodeConsumers) {+ nodeConsumers = {+ transactions: new TransactionsConsumer(user.user, message.rootId),+ interactions: new InteractionsConsumer(user.user, message.rootId),+ files: new FilesConsumer(user.user, message.rootId),+ messages: new MessagesConsumer(user.user, message.rootId),+ messageReactions: new MessageReactionsConsumer(+ user.user,+ message.rootId+ ),+ };++ user.consumers.nodes.set(message.rootId, nodeConsumers);+ }++ await nodeConsumers.messageReactions.consume(message);+ }+private async getOrCreateUser(userId: string): Promise<SocketUser | null> {const existingUser = this.users.get(userId);if (existingUser) {diff --git a/apps/server/src/types/events.ts b/apps/server/src/types/events.tsindex c11d6e8a..1b524e0b 100644--- a/apps/server/src/types/events.ts+++ b/apps/server/src/types/events.ts@@ -24,6 +24,43 @@ export type NodeDeletedEvent = {workspaceId: string;};+export type MessageCreatedEvent = {+ type: 'message_created';+ messageId: string;+ rootId: string;+ workspaceId: string;+};++export type MessageUpdatedEvent = {+ type: 'message_updated';+ messageId: string;+ rootId: string;+ workspaceId: string;+};++export type MessageDeletedEvent = {+ type: 'message_deleted';+ messageId: string;+ rootId: string;+ workspaceId: string;+};++export type MessageReactionCreatedEvent = {+ type: 'message_reaction_created';+ messageId: string;+ collaboratorId: string;+ rootId: string;+ workspaceId: string;+};++export type MessageReactionDeletedEvent = {+ type: 'message_reaction_deleted';+ messageId: string;+ collaboratorId: string;+ rootId: string;+ workspaceId: string;+};+export type CollaborationCreatedEvent = {type: 'collaboration_created';collaboratorId: string;@@ -123,4 +160,9 @@ export type Event =| DeviceDeletedEvent| FileCreatedEvent| FileUpdatedEvent- | FileDeletedEvent;+ | FileDeletedEvent+ | MessageCreatedEvent+ | MessageUpdatedEvent+ | MessageDeletedEvent+ | MessageReactionCreatedEvent+ | MessageReactionDeletedEvent;diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 54ea8126..e67340d6 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -12,7 +12,6 @@ export * from './registry/database';export * from './registry/fields';export * from './registry/folder';export * from './registry/index';-export * from './registry/message';export * from './registry/page';export * from './registry/record';export * from './registry/space';@@ -20,10 +19,11 @@ export * from './registry/zod';export * from './types/accounts';export * from './types/files';export * from './types/interactions';-export * from './types/messages';+export * from './types/sockets';export * from './types/nodes';export * from './types/servers';export * from './types/sync';export * from './types/workspaces';export * from './lib/blocks';export * from './types/mutations';+export * from './types/messages';diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.tsindex 58dddd26..dba949e4 100644--- a/packages/core/src/registry/index.ts+++ b/packages/core/src/registry/index.ts@@ -3,7 +3,6 @@ import { ChatAttributes, chatModel } from './chat';import { NodeModel } from './core';import { DatabaseAttributes, databaseModel } from './database';import { FolderAttributes, folderModel } from './folder';-import { MessageAttributes, messageModel } from './message';import { PageAttributes, pageModel } from './page';import { RecordAttributes, recordModel } from './record';import { SpaceAttributes, spaceModel } from './space';@@ -48,11 +47,6 @@ export type FolderNode = NodeBase & {attributes: FolderAttributes;};-export type MessageNode = NodeBase & {- type: 'message';- attributes: MessageAttributes;-};-export type PageNode = NodeBase & {type: 'page';attributes: PageAttributes;@@ -73,7 +67,6 @@ export type NodeType =| 'chat'| 'database'| 'folder'- | 'message'| 'page'| 'record'| 'space';@@ -84,7 +77,6 @@ export type NodeAttributes =| ChannelAttributes| ChatAttributes| FolderAttributes- | MessageAttributes| PageAttributes| RecordAttributes;@@ -93,7 +85,6 @@ export type Node =| ChatNode| DatabaseNode| FolderNode- | MessageNode| PageNode| RecordNode| SpaceNode;@@ -106,7 +97,6 @@ class Registry {this.models.set('chat', chatModel);this.models.set('database', databaseModel);this.models.set('folder', folderModel);- this.models.set('message', messageModel);this.models.set('page', pageModel);this.models.set('record', recordModel);this.models.set('space', spaceModel);diff --git a/packages/core/src/registry/message.ts b/packages/core/src/registry/message.tsdeleted file mode 100644index cde1dac3..00000000--- a/packages/core/src/registry/message.ts+++ /dev/null@@ -1,75 +0,0 @@-import { isEqual } from 'lodash-es';-import { z } from 'zod';--import { blockSchema } from './block';-import { NodeModel } from './core';--import { extractText } from '../lib/blocks';--const standardMessageAttributesSchema = z.object({- type: z.literal('message'),- subtype: z.literal('standard'),- parentId: z.string(),- content: z.record(z.string(), blockSchema),- reactions: z.record(z.string(), z.array(z.string())),-});--const replyMessageAttributesSchema = z.object({- type: z.literal('message'),- subtype: z.literal('reply'),- parentId: z.string(),- content: z.record(z.string(), blockSchema),- reactions: z.record(z.string(), z.array(z.string())),- referenceId: z.string(),-});--export const messageAttributesSchema = z.discriminatedUnion('subtype', [- standardMessageAttributesSchema,- replyMessageAttributesSchema,-]);--export type MessageAttributes = z.infer<typeof messageAttributesSchema>;--export const messageModel: NodeModel = {- type: 'message',- schema: messageAttributesSchema,- getName: () => {- return undefined;- },- getText: (id, attributes) => {- if (attributes.type !== 'message') {- return undefined;- }-- return extractText(id, attributes.content);- },- canCreate: async (context, attributes) => {- if (attributes.type !== 'message') {- return false;- }-- return context.hasCollaboratorAccess();- },- canUpdate: async (context, node, attributes) => {- if (attributes.type !== 'message' || node.type !== 'message') {- return false;- }-- if (!isEqual(attributes.content, node.attributes.content)) {- return context.userId === node.createdBy;- }-- return context.hasCollaboratorAccess();- },- canDelete: async (context, node) => {- if (node.type !== 'message') {- return false;- }-- if (context.userId === node.createdBy) {- return true;- }-- return context.hasAdminAccess();- },-};diff --git a/packages/core/src/types/messages.ts b/packages/core/src/types/messages.tsindex 67851d70..b4bf90e8 100644--- a/packages/core/src/types/messages.ts+++ b/packages/core/src/types/messages.ts@@ -1,113 +1,7 @@-import { InteractionEvent } from './interactions';-import {- ServerCollaboration,- ServerFile,- ServerInteraction,- ServerTransaction,- ServerUser,-} from './sync';+import { Block } from '../registry/block';-export type TransactionsBatchMessage = {- type: 'transactions_batch';- userId: string;- rootId: string;- transactions: ServerTransaction[];-};--export type CollaborationsBatchMessage = {- type: 'collaborations_batch';- userId: string;- collaborations: ServerCollaboration[];-};--export type InteractionsBatchMessage = {- type: 'interactions_batch';- userId: string;- rootId: string;- interactions: ServerInteraction[];-};--export type UsersBatchMessage = {- type: 'users_batch';- userId: string;- users: ServerUser[];-};--export type FilesBatchMessage = {- type: 'files_batch';- userId: string;- rootId: string;- files: ServerFile[];-};--export type SyncInteractionsMessage = {- type: 'sync_interactions';- userId: string;- nodeId: string;- rootId: string;- events: InteractionEvent[];-};--export type ConsumeUsersMessage = {- type: 'consume_users';- userId: string;- cursor: string;-};+export type MessageType = 'standard';-export type ConsumeCollaborationsMessage = {- type: 'consume_collaborations';- userId: string;- cursor: string;+export type MessageContent = {+ blocks: Record<string, Block>;};--export type ConsumeInteractionsMessage = {- type: 'consume_interactions';- userId: string;- rootId: string;- cursor: string;-};--export type ConsumeTransactionsMessage = {- type: 'consume_transactions';- userId: string;- rootId: string;- cursor: string;-};--export type ConsumeFilesMessage = {- type: 'consume_files';- userId: string;- rootId: string;- cursor: string;-};--export type AccountUpdatedMessage = {- type: 'account_updated';- accountId: string;-};--export type WorkspaceUpdatedMessage = {- type: 'workspace_updated';- workspaceId: string;-};--export type WorkspaceDeletedMessage = {- type: 'workspace_deleted';- accountId: string;-};--export type Message =- | TransactionsBatchMessage- | CollaborationsBatchMessage- | InteractionsBatchMessage- | UsersBatchMessage- | SyncInteractionsMessage- | ConsumeUsersMessage- | ConsumeCollaborationsMessage- | ConsumeInteractionsMessage- | ConsumeTransactionsMessage- | AccountUpdatedMessage- | WorkspaceUpdatedMessage- | WorkspaceDeletedMessage- | FilesBatchMessage- | ConsumeFilesMessage;diff --git a/packages/core/src/types/mutations.ts b/packages/core/src/types/mutations.tsindex fe012b52..d1181cea 100644--- a/packages/core/src/types/mutations.ts+++ b/packages/core/src/types/mutations.ts@@ -1,4 +1,5 @@import { FileType } from './files';+import { MessageType } from './messages';import {LocalCreateTransaction,LocalDeleteTransaction,@@ -27,7 +28,7 @@ export type MutationBase = {export type CreateFileMutationData = {id: string;- fileType: FileType;+ type: FileType;parentId: string;rootId: string;name: string;@@ -58,10 +59,52 @@ export type ApplyDeleteTransactionMutation = MutationBase & {data: LocalDeleteTransaction;};+export type CreateMessageMutationData = {+ id: string;+ type: MessageType;+ nodeId: string;+ parentId: string;+ content: unknown;+ rootId: string;+ createdAt: string;+};++export type CreateMessageMutation = MutationBase & {+ type: 'create_message';+ data: CreateMessageMutationData;+};++export type CreateMessageReactionMutationData = {+ messageId: string;+ reaction: string;+ rootId: string;+ createdAt: string;+};++export type CreateMessageReactionMutation = MutationBase & {+ type: 'create_message_reaction';+ data: CreateMessageReactionMutationData;+};++export type DeleteMessageReactionMutationData = {+ messageId: string;+ reaction: string;+ rootId: string;+ deletedAt: string;+};++export type DeleteMessageReactionMutation = MutationBase & {+ type: 'delete_message_reaction';+ data: DeleteMessageReactionMutationData;+};+export type Mutation =| CreateFileMutation| ApplyCreateTransactionMutation| ApplyUpdateTransactionMutation- | ApplyDeleteTransactionMutation;+ | ApplyDeleteTransactionMutation+ | CreateMessageMutation+ | CreateMessageReactionMutation+ | DeleteMessageReactionMutation;export type MutationType = Mutation['type'];diff --git a/packages/core/src/types/sockets.ts b/packages/core/src/types/sockets.tsnew file mode 100644index 00000000..bbbb8c82--- /dev/null+++ b/packages/core/src/types/sockets.ts@@ -0,0 +1,147 @@+import { InteractionEvent } from './interactions';+import {+ ServerCollaboration,+ ServerFile,+ ServerInteraction,+ ServerMessage,+ ServerMessageReaction,+ ServerTransaction,+ ServerUser,+} from './sync';++export type TransactionsBatchMessage = {+ type: 'transactions_batch';+ userId: string;+ rootId: string;+ transactions: ServerTransaction[];+};++export type CollaborationsBatchMessage = {+ type: 'collaborations_batch';+ userId: string;+ collaborations: ServerCollaboration[];+};++export type InteractionsBatchMessage = {+ type: 'interactions_batch';+ userId: string;+ rootId: string;+ interactions: ServerInteraction[];+};++export type UsersBatchMessage = {+ type: 'users_batch';+ userId: string;+ users: ServerUser[];+};++export type FilesBatchMessage = {+ type: 'files_batch';+ userId: string;+ rootId: string;+ files: ServerFile[];+};++export type MessagesBatchMessage = {+ type: 'messages_batch';+ userId: string;+ rootId: string;+ messages: ServerMessage[];+};++export type MessageReactionsBatchMessage = {+ type: 'message_reactions_batch';+ userId: string;+ rootId: string;+ messageReactions: ServerMessageReaction[];+};++export type SyncInteractionsMessage = {+ type: 'sync_interactions';+ userId: string;+ nodeId: string;+ rootId: string;+ events: InteractionEvent[];+};++export type ConsumeUsersMessage = {+ type: 'consume_users';+ userId: string;+ cursor: string;+};++export type ConsumeCollaborationsMessage = {+ type: 'consume_collaborations';+ userId: string;+ cursor: string;+};++export type ConsumeInteractionsMessage = {+ type: 'consume_interactions';+ userId: string;+ rootId: string;+ cursor: string;+};++export type ConsumeTransactionsMessage = {+ type: 'consume_transactions';+ userId: string;+ rootId: string;+ cursor: string;+};++export type ConsumeFilesMessage = {+ type: 'consume_files';+ userId: string;+ rootId: string;+ cursor: string;+};++export type ConsumeMessagesMessage = {+ type: 'consume_messages';+ userId: string;+ rootId: string;+ cursor: string;+};++export type ConsumeMessageReactionsMessage = {+ type: 'consume_message_reactions';+ userId: string;+ rootId: string;+ cursor: string;+};++export type AccountUpdatedMessage = {+ type: 'account_updated';+ accountId: string;+};++export type WorkspaceUpdatedMessage = {+ type: 'workspace_updated';+ workspaceId: string;+};++export type WorkspaceDeletedMessage = {+ type: 'workspace_deleted';+ accountId: string;+};++export type Message =+ | TransactionsBatchMessage+ | CollaborationsBatchMessage+ | InteractionsBatchMessage+ | UsersBatchMessage+ | SyncInteractionsMessage+ | ConsumeUsersMessage+ | ConsumeCollaborationsMessage+ | ConsumeInteractionsMessage+ | ConsumeTransactionsMessage+ | AccountUpdatedMessage+ | WorkspaceUpdatedMessage+ | WorkspaceDeletedMessage+ | FilesBatchMessage+ | ConsumeFilesMessage+ | ConsumeMessagesMessage+ | MessagesBatchMessage+ | MessageReactionsBatchMessage+ | ConsumeMessageReactionsMessage;diff --git a/packages/core/src/types/sync.ts b/packages/core/src/types/sync.tsindex df02dc5c..4169222a 100644--- a/packages/core/src/types/sync.ts+++ b/packages/core/src/types/sync.ts@@ -1,6 +1,7 @@import { InteractionAttributes } from './interactions';import { WorkspaceRole } from './workspaces';import { FileStatus, FileType } from './files';+import { MessageContent, MessageType } from './messages';import { NodeRole } from '../registry/core';@@ -150,3 +151,31 @@ export type ServerFile = {deletedBy: string | null;version: string;};++export type ServerMessage = {+ id: string;+ type: MessageType;+ parentId: string;+ nodeId: string;+ rootId: string;+ workspaceId: string;+ content: MessageContent;+ createdAt: string;+ createdBy: string;+ updatedAt: string | null;+ updatedBy: string | null;+ deletedAt: string | null;+ deletedBy: string | null;+ version: string;+};++export type ServerMessageReaction = {+ messageId: string;+ collaboratorId: string;+ reaction: string;+ rootId: string;+ workspaceId: string;+ createdAt: string;+ deletedAt: string | null;+ version: string;+};