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
Implement interactions for entries, messages and files
Hakan Shehu94ce64545a4d
diff --git a/apps/desktop/src/main/data/workspace/migrations.ts b/apps/desktop/src/main/data/workspace/migrations.tsindex 2ddbd8b6..5eeb2622 100644--- a/apps/desktop/src/main/data/workspace/migrations.ts+++ b/apps/desktop/src/main/data/workspace/migrations.ts@@ -77,6 +77,29 @@ const createTransactionsTable: Migration = {},};+const createEntryInteractionsTable: Migration = {+ up: async (db) => {+ await db.schema+ .createTable('entry_interactions')+ .addColumn('entry_id', 'text', (col) => col.notNull())+ .addColumn('collaborator_id', 'text', (col) => col.notNull())+ .addColumn('root_id', 'text', (col) => col.notNull())+ .addColumn('first_seen_at', 'text')+ .addColumn('last_seen_at', 'text')+ .addColumn('first_opened_at', 'text')+ .addColumn('last_opened_at', 'text')+ .addColumn('version', 'integer', (col) => col.notNull())+ .addPrimaryKeyConstraint('entry_interactions_pkey', [+ 'entry_id',+ 'collaborator_id',+ ])+ .execute();+ },+ down: async (db) => {+ await db.schema.dropTable('entry_interactions').execute();+ },+};+const createCollaborationsTable: Migration = {up: async (db) => {await db.schema@@ -138,6 +161,28 @@ const createMessageReactionsTable: Migration = {},};+const createMessageInteractionsTable: Migration = {+ up: async (db) => {+ await db.schema+ .createTable('message_interactions')+ .addColumn('message_id', 'text', (col) => col.notNull())+ .addColumn('collaborator_id', 'text', (col) => col.notNull())+ .addColumn('root_id', 'text', (col) => col.notNull())+ .addColumn('seen_at', 'text')+ .addColumn('first_opened_at', 'text')+ .addColumn('last_opened_at', 'text')+ .addColumn('version', 'integer', (col) => col.notNull())+ .addPrimaryKeyConstraint('message_interactions_pkey', [+ 'message_id',+ 'collaborator_id',+ ])+ .execute();+ },+ down: async (db) => {+ await db.schema.dropTable('message_interactions').execute();+ },+};+const createFilesTable: Migration = {up: async (db) => {await db.schema@@ -185,6 +230,28 @@ const createFileStatesTable: Migration = {},};+const createFileInteractionsTable: Migration = {+ up: async (db) => {+ await db.schema+ .createTable('file_interactions')+ .addColumn('file_id', 'text', (col) => col.notNull())+ .addColumn('collaborator_id', 'text', (col) => col.notNull())+ .addColumn('root_id', 'text', (col) => col.notNull())+ .addColumn('seen_at', 'text')+ .addColumn('first_opened_at', 'text')+ .addColumn('last_opened_at', 'text')+ .addColumn('version', 'integer', (col) => col.notNull())+ .addPrimaryKeyConstraint('file_interactions_pkey', [+ 'file_id',+ 'collaborator_id',+ ])+ .execute();+ },+ down: async (db) => {+ await db.schema.dropTable('file_interactions').execute();+ },+};+const createMutationsTable: Migration = {up: async (db) => {await db.schema@@ -308,15 +375,18 @@ const createCursorsTable: Migration = {export const workspaceDatabaseMigrations: Record<string, Migration> = {'00001_create_users_table': createUsersTable,'00002_create_entries_table': createEntriesTable,- '00003_create_transactions_table': createTransactionsTable,- '00004_create_collaborations_table': createCollaborationsTable,- '00005_create_messages_table': createMessagesTable,- '00006_create_message_reactions_table': createMessageReactionsTable,- '00007_create_files_table': createFilesTable,- '00008_create_file_states_table': createFileStatesTable,- '00009_create_mutations_table': createMutationsTable,- '00010_create_entry_paths_table': createEntryPathsTable,- '00011_create_node_names_table': createNodeNamesTable,- '00012_create_node_texts_table': createNodeTextsTable,- '00013_create_cursors_table': createCursorsTable,+ '00003_create_entry_interactions_table': createEntryInteractionsTable,+ '00004_create_transactions_table': createTransactionsTable,+ '00005_create_collaborations_table': createCollaborationsTable,+ '00006_create_messages_table': createMessagesTable,+ '00007_create_message_reactions_table': createMessageReactionsTable,+ '00008_create_message_interactions_table': createMessageInteractionsTable,+ '00009_create_files_table': createFilesTable,+ '00010_create_file_states_table': createFileStatesTable,+ '00011_create_file_interactions_table': createFileInteractionsTable,+ '00012_create_mutations_table': createMutationsTable,+ '00013_create_entry_paths_table': createEntryPathsTable,+ '00014_create_node_names_table': createNodeNamesTable,+ '00015_create_node_texts_table': createNodeTextsTable,+ '00016_create_cursors_table': createCursorsTable,};diff --git a/apps/desktop/src/main/data/workspace/schema.ts b/apps/desktop/src/main/data/workspace/schema.tsindex 902d6894..0f126ca8 100644--- a/apps/desktop/src/main/data/workspace/schema.ts+++ b/apps/desktop/src/main/data/workspace/schema.ts@@ -69,6 +69,21 @@ export type SelectTransaction = Selectable<TransactionTable>;export type CreateTransaction = Insertable<TransactionTable>;export type UpdateTransaction = Updateable<TransactionTable>;+interface EntryInteractionTable {+ entry_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, never>;+ first_seen_at: ColumnType<string | null, string | null, string | null>;+ last_seen_at: ColumnType<string | null, string | null, string | null>;+ first_opened_at: ColumnType<string | null, string | null, string | null>;+ last_opened_at: ColumnType<string | null, string | null, string | null>;+ version: ColumnType<bigint, bigint, bigint>;+}++export type SelectEntryInteraction = Selectable<EntryInteractionTable>;+export type CreateEntryInteraction = Insertable<EntryInteractionTable>;+export type UpdateEntryInteraction = Updateable<EntryInteractionTable>;+interface CollaborationTable {entry_id: ColumnType<string, string, never>;role: ColumnType<string, string, string>;@@ -113,6 +128,20 @@ export type SelectMessageReaction = Selectable<MessageReactionTable>;export type CreateMessageReaction = Insertable<MessageReactionTable>;export type UpdateMessageReaction = Updateable<MessageReactionTable>;+interface MessageInteractionTable {+ message_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, string>;+ seen_at: ColumnType<string | null, string | null, string | null>;+ first_opened_at: ColumnType<string | null, string | null, string | null>;+ last_opened_at: ColumnType<string | null, string | null, string | null>;+ version: ColumnType<bigint, bigint, bigint>;+}++export type SelectMessageInteraction = Selectable<MessageInteractionTable>;+export type CreateMessageInteraction = Insertable<MessageInteractionTable>;+export type UpdateMessageInteraction = Updateable<MessageInteractionTable>;+interface FileTable {id: ColumnType<string, string, never>;type: ColumnType<FileType, FileType, FileType>;@@ -152,6 +181,21 @@ export type SelectFileState = Selectable<FileStateTable>;export type CreateFileState = Insertable<FileStateTable>;export type UpdateFileState = Updateable<FileStateTable>;+interface FileInteractionTable {+ file_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, string>;+ first_seen_at: ColumnType<string | null, string | null, string | null>;+ last_seen_at: ColumnType<string | null, string | null, string | null>;+ first_opened_at: ColumnType<string | null, string | null, string | null>;+ last_opened_at: ColumnType<string | null, string | null, string | null>;+ version: ColumnType<bigint, bigint, bigint>;+}++export type SelectFileInteraction = Selectable<FileInteractionTable>;+export type CreateFileInteraction = Insertable<FileInteractionTable>;+export type UpdateFileInteraction = Updateable<FileInteractionTable>;+interface MutationTable {id: ColumnType<string, string, never>;type: ColumnType<MutationType, MutationType, never>;@@ -193,13 +237,16 @@ interface CursorTable {export interface WorkspaceDatabaseSchema {users: UserTable;entries: EntryTable;+ entry_interactions: EntryInteractionTable;transactions: TransactionTable;entry_paths: EntryPathTable;collaborations: CollaborationTable;messages: MessageTable;message_reactions: MessageReactionTable;+ message_interactions: MessageInteractionTable;files: FileTable;file_states: FileStateTable;+ file_interactions: FileInteractionTable;mutations: MutationTable;node_names: NodeNameTable;node_texts: NodeTextTable;diff --git a/apps/desktop/src/main/mutations/collaborators/entry-collaborator-create.ts b/apps/desktop/src/main/mutations/entries/entry-collaborator-create.tssimilarity index 94%rename from apps/desktop/src/main/mutations/collaborators/entry-collaborator-create.tsrename to apps/desktop/src/main/mutations/entries/entry-collaborator-create.tsindex 6bd3334c..7af0ed38 100644--- a/apps/desktop/src/main/mutations/collaborators/entry-collaborator-create.ts+++ b/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts@@ -5,7 +5,7 @@ import { MutationHandler } from '@/main/types';import {EntryCollaboratorCreateMutationInput,EntryCollaboratorCreateMutationOutput,-} from '@/shared/mutations/collaborators/entry-collaborator-create';+} from '@/shared/mutations/entries/entry-collaborator-create';import { MutationError } from '@/shared/mutations';export class EntryCollaboratorCreateMutationHandlerdiff --git a/apps/desktop/src/main/mutations/collaborators/entry-collaborator-delete.ts b/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.tssimilarity index 94%rename from apps/desktop/src/main/mutations/collaborators/entry-collaborator-delete.tsrename to apps/desktop/src/main/mutations/entries/entry-collaborator-delete.tsindex d48c855a..1042d2df 100644--- a/apps/desktop/src/main/mutations/collaborators/entry-collaborator-delete.ts+++ b/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts@@ -5,7 +5,7 @@ import { MutationHandler } from '@/main/types';import {EntryCollaboratorDeleteMutationInput,EntryCollaboratorDeleteMutationOutput,-} from '@/shared/mutations/collaborators/entry-collaborator-delete';+} from '@/shared/mutations/entries/entry-collaborator-delete';import { MutationError } from '@/shared/mutations';export class EntryCollaboratorDeleteMutationHandlerdiff --git a/apps/desktop/src/main/mutations/collaborators/entry-collaborator-update.ts b/apps/desktop/src/main/mutations/entries/entry-collaborator-update.tssimilarity index 94%rename from apps/desktop/src/main/mutations/collaborators/entry-collaborator-update.tsrename to apps/desktop/src/main/mutations/entries/entry-collaborator-update.tsindex 56c97a56..a0e7d5dd 100644--- a/apps/desktop/src/main/mutations/collaborators/entry-collaborator-update.ts+++ b/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts@@ -5,7 +5,7 @@ import { MutationHandler } from '@/main/types';import {EntryCollaboratorUpdateMutationInput,EntryCollaboratorUpdateMutationOutput,-} from '@/shared/mutations/collaborators/entry-collaborator-update';+} from '@/shared/mutations/entries/entry-collaborator-update';import { MutationError } from '@/shared/mutations';export class EntryCollaboratorUpdateMutationHandlerdiff --git a/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts b/apps/desktop/src/main/mutations/entries/entry-mark-opened.tsnew file mode 100644index 00000000..3fb89a84--- /dev/null+++ b/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts@@ -0,0 +1,133 @@+import { MarkEntryOpenedMutation, generateId, IdType } from '@colanode/core';++import { databaseService } from '@/main/data/database-service';+import { MutationHandler } from '@/main/types';+import {+ EntryMarkOpenedMutationInput,+ EntryMarkOpenedMutationOutput,+} from '@/shared/mutations/entries/entry-mark-opened';+import { eventBus } from '@/shared/lib/event-bus';+import { mapEntryInteraction } from '@/main/utils';++export class EntryMarkOpenedMutationHandler+ implements MutationHandler<EntryMarkOpenedMutationInput>+{+ async handleMutation(+ input: EntryMarkOpenedMutationInput+ ): Promise<EntryMarkOpenedMutationOutput> {+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const entry = await workspaceDatabase+ .selectFrom('entries')+ .selectAll()+ .where('id', '=', input.entryId)+ .executeTakeFirst();++ if (!entry) {+ return {+ success: false,+ };+ }++ const existingInteraction = await workspaceDatabase+ .selectFrom('entry_interactions')+ .selectAll()+ .where('entry_id', '=', input.entryId)+ .where('collaborator_id', '=', input.userId)+ .executeTakeFirst();++ if (existingInteraction) {+ const lastOpenedAt = existingInteraction.last_opened_at;+ if (+ lastOpenedAt &&+ lastOpenedAt > new Date(Date.now() - 5 * 60 * 1000).toISOString()+ ) {+ return {+ success: true,+ };+ }+ }++ const lastOpenedAt = new Date().toISOString();+ const firstOpenedAt = existingInteraction+ ? existingInteraction.first_opened_at+ : lastOpenedAt;++ const { createdInteraction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const createdInteraction = await trx+ .insertInto('entry_interactions')+ .returningAll()+ .values({+ entry_id: input.entryId,+ collaborator_id: input.userId,+ last_opened_at: lastOpenedAt,+ first_opened_at: firstOpenedAt,+ version: 0n,+ root_id: entry.root_id,+ })+ .onConflict((b) =>+ b.columns(['entry_id', 'collaborator_id']).doUpdateSet({+ last_opened_at: lastOpenedAt,+ first_opened_at: firstOpenedAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ throw new Error('Failed to create file interaction');+ }++ const mutation: MarkEntryOpenedMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'mark_entry_opened',+ data: {+ entryId: input.entryId,+ collaboratorId: input.userId,+ openedAt: new Date().toISOString(),+ },+ };++ 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.entryId,+ retries: 0,+ })+ .executeTakeFirst();++ return {+ createdInteraction,+ createdMutation,+ };+ });++ if (!createdInteraction || !createdMutation) {+ throw new Error('Failed to create entry interaction');+ }++ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'entry_interaction_updated',+ userId: input.userId,+ entryInteraction: mapEntryInteraction(createdInteraction),+ });++ return {+ success: true,+ };+ }+}diff --git a/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts b/apps/desktop/src/main/mutations/entries/entry-mark-seen.tsnew file mode 100644index 00000000..ae66279b--- /dev/null+++ b/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts@@ -0,0 +1,133 @@+import { MarkEntrySeenMutation, generateId, IdType } from '@colanode/core';++import { databaseService } from '@/main/data/database-service';+import { MutationHandler } from '@/main/types';+import {+ EntryMarkSeenMutationInput,+ EntryMarkSeenMutationOutput,+} from '@/shared/mutations/entries/entry-mark-seen';+import { eventBus } from '@/shared/lib/event-bus';+import { mapEntryInteraction } from '@/main/utils';++export class EntryMarkSeenMutationHandler+ implements MutationHandler<EntryMarkSeenMutationInput>+{+ async handleMutation(+ input: EntryMarkSeenMutationInput+ ): Promise<EntryMarkSeenMutationOutput> {+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const entry = await workspaceDatabase+ .selectFrom('entries')+ .selectAll()+ .where('id', '=', input.entryId)+ .executeTakeFirst();++ if (!entry) {+ return {+ success: false,+ };+ }++ const existingInteraction = await workspaceDatabase+ .selectFrom('entry_interactions')+ .selectAll()+ .where('entry_id', '=', input.entryId)+ .where('collaborator_id', '=', input.userId)+ .executeTakeFirst();++ if (existingInteraction) {+ const lastSeenAt = existingInteraction.last_seen_at;+ if (+ lastSeenAt &&+ lastSeenAt > new Date(Date.now() - 5 * 60 * 1000).toISOString()+ ) {+ return {+ success: true,+ };+ }+ }++ const lastSeenAt = new Date().toISOString();+ const firstSeenAt = existingInteraction+ ? existingInteraction.first_seen_at+ : lastSeenAt;++ const { createdInteraction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const createdInteraction = await trx+ .insertInto('entry_interactions')+ .returningAll()+ .values({+ entry_id: input.entryId,+ collaborator_id: input.userId,+ last_seen_at: lastSeenAt,+ first_seen_at: firstSeenAt,+ version: 0n,+ root_id: entry.root_id,+ })+ .onConflict((b) =>+ b.columns(['entry_id', 'collaborator_id']).doUpdateSet({+ last_seen_at: lastSeenAt,+ first_seen_at: firstSeenAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ throw new Error('Failed to create entry interaction');+ }++ const mutation: MarkEntrySeenMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'mark_entry_seen',+ data: {+ entryId: input.entryId,+ collaboratorId: input.userId,+ seenAt: new Date().toISOString(),+ },+ };++ 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.entryId,+ retries: 0,+ })+ .executeTakeFirst();++ return {+ createdInteraction,+ createdMutation,+ };+ });++ if (!createdInteraction || !createdMutation) {+ throw new Error('Failed to create entry interaction');+ }++ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'entry_interaction_updated',+ userId: input.userId,+ entryInteraction: mapEntryInteraction(createdInteraction),+ });++ return {+ success: true,+ };+ }+}diff --git a/apps/desktop/src/main/mutations/files/file-mark-opened.ts b/apps/desktop/src/main/mutations/files/file-mark-opened.tsnew file mode 100644index 00000000..def9cb0a--- /dev/null+++ b/apps/desktop/src/main/mutations/files/file-mark-opened.ts@@ -0,0 +1,133 @@+import { MarkFileOpenedMutation, generateId, IdType } from '@colanode/core';++import { databaseService } from '@/main/data/database-service';+import { MutationHandler } from '@/main/types';+import {+ FileMarkOpenedMutationInput,+ FileMarkOpenedMutationOutput,+} from '@/shared/mutations/files/file-mark-opened';+import { eventBus } from '@/shared/lib/event-bus';+import { mapFileInteraction } from '@/main/utils';++export class FileMarkOpenedMutationHandler+ implements MutationHandler<FileMarkOpenedMutationInput>+{+ async handleMutation(+ input: FileMarkOpenedMutationInput+ ): Promise<FileMarkOpenedMutationOutput> {+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const file = await workspaceDatabase+ .selectFrom('files')+ .selectAll()+ .where('id', '=', input.fileId)+ .executeTakeFirst();++ if (!file) {+ return {+ success: false,+ };+ }++ const existingInteraction = await workspaceDatabase+ .selectFrom('file_interactions')+ .selectAll()+ .where('file_id', '=', input.fileId)+ .where('collaborator_id', '=', input.userId)+ .executeTakeFirst();++ if (existingInteraction) {+ const lastOpenedAt = existingInteraction.last_opened_at;+ if (+ lastOpenedAt &&+ lastOpenedAt > new Date(Date.now() - 5 * 60 * 1000).toISOString()+ ) {+ return {+ success: true,+ };+ }+ }++ const lastOpenedAt = new Date().toISOString();+ const firstOpenedAt = existingInteraction+ ? existingInteraction.first_opened_at+ : lastOpenedAt;++ const { createdInteraction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const createdInteraction = await trx+ .insertInto('file_interactions')+ .returningAll()+ .values({+ file_id: input.fileId,+ collaborator_id: input.userId,+ last_opened_at: lastOpenedAt,+ first_opened_at: firstOpenedAt,+ version: 0n,+ root_id: file.root_id,+ })+ .onConflict((b) =>+ b.columns(['file_id', 'collaborator_id']).doUpdateSet({+ last_opened_at: lastOpenedAt,+ first_opened_at: firstOpenedAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ throw new Error('Failed to create file interaction');+ }++ const mutation: MarkFileOpenedMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'mark_file_opened',+ data: {+ fileId: input.fileId,+ collaboratorId: input.userId,+ openedAt: new Date().toISOString(),+ },+ };++ 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.fileId,+ retries: 0,+ })+ .executeTakeFirst();++ return {+ createdInteraction,+ createdMutation,+ };+ });++ if (!createdInteraction || !createdMutation) {+ throw new Error('Failed to create file interaction');+ }++ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'file_interaction_updated',+ userId: input.userId,+ fileInteraction: mapFileInteraction(createdInteraction),+ });++ return {+ success: true,+ };+ }+}diff --git a/apps/desktop/src/main/mutations/files/file-mark-seen.ts b/apps/desktop/src/main/mutations/files/file-mark-seen.tsnew file mode 100644index 00000000..0c657652--- /dev/null+++ b/apps/desktop/src/main/mutations/files/file-mark-seen.ts@@ -0,0 +1,133 @@+import { MarkFileSeenMutation, generateId, IdType } from '@colanode/core';++import { databaseService } from '@/main/data/database-service';+import { MutationHandler } from '@/main/types';+import {+ FileMarkSeenMutationInput,+ FileMarkSeenMutationOutput,+} from '@/shared/mutations/files/file-mark-seen';+import { eventBus } from '@/shared/lib/event-bus';+import { mapFileInteraction } from '@/main/utils';++export class FileMarkSeenMutationHandler+ implements MutationHandler<FileMarkSeenMutationInput>+{+ async handleMutation(+ input: FileMarkSeenMutationInput+ ): Promise<FileMarkSeenMutationOutput> {+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const file = await workspaceDatabase+ .selectFrom('files')+ .selectAll()+ .where('id', '=', input.fileId)+ .executeTakeFirst();++ if (!file) {+ return {+ success: false,+ };+ }++ const existingInteraction = await workspaceDatabase+ .selectFrom('file_interactions')+ .selectAll()+ .where('file_id', '=', input.fileId)+ .where('collaborator_id', '=', input.userId)+ .executeTakeFirst();++ if (existingInteraction) {+ const lastSeenAt = existingInteraction.last_seen_at;+ if (+ lastSeenAt &&+ lastSeenAt > new Date(Date.now() - 5 * 60 * 1000).toISOString()+ ) {+ return {+ success: true,+ };+ }+ }++ const lastSeenAt = new Date().toISOString();+ const firstSeenAt = existingInteraction+ ? existingInteraction.first_seen_at+ : lastSeenAt;++ const { createdInteraction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const createdInteraction = await trx+ .insertInto('file_interactions')+ .returningAll()+ .values({+ file_id: input.fileId,+ collaborator_id: input.userId,+ last_seen_at: lastSeenAt,+ first_seen_at: firstSeenAt,+ version: 0n,+ root_id: file.root_id,+ })+ .onConflict((b) =>+ b.columns(['file_id', 'collaborator_id']).doUpdateSet({+ last_seen_at: lastSeenAt,+ first_seen_at: firstSeenAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ throw new Error('Failed to create file interaction');+ }++ const mutation: MarkFileSeenMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'mark_file_seen',+ data: {+ fileId: input.fileId,+ collaboratorId: input.userId,+ seenAt: new Date().toISOString(),+ },+ };++ 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.fileId,+ retries: 0,+ })+ .executeTakeFirst();++ return {+ createdInteraction,+ createdMutation,+ };+ });++ if (!createdInteraction || !createdMutation) {+ throw new Error('Failed to create file interaction');+ }++ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'file_interaction_updated',+ userId: input.userId,+ fileInteraction: mapFileInteraction(createdInteraction),+ });++ return {+ success: true,+ };+ }+}diff --git a/apps/desktop/src/main/mutations/index.ts b/apps/desktop/src/main/mutations/index.tsindex 1870b679..ded38161 100644--- a/apps/desktop/src/main/mutations/index.ts+++ b/apps/desktop/src/main/mutations/index.ts@@ -18,16 +18,21 @@ import { FieldNameUpdateMutationHandler } from '@/main/mutations/databases/fieldimport { FileCreateMutationHandler } from '@/main/mutations/files/file-create';import { FileDeleteMutationHandler } from '@/main/mutations/files/file-delete';import { FileDownloadMutationHandler } from '@/main/mutations/files/file-download';+import { FileMarkOpenedMutationHandler } from '@/main/mutations/files/file-mark-opened';+import { FileMarkSeenMutationHandler } from '@/main/mutations/files/file-mark-seen';import { FolderCreateMutationHandler } from '@/main/mutations/folders/folder-create';import { FolderUpdateMutationHandler } from '@/main/mutations/folders/folder-update';import { FolderDeleteMutationHandler } from '@/main/mutations/folders/folder-delete';import { MessageCreateMutationHandler } from '@/main/mutations/messages/message-create';import { MessageDeleteMutationHandler } from '@/main/mutations/messages/message-delete';-import { EntryCollaboratorCreateMutationHandler } from '@/main/mutations/collaborators/entry-collaborator-create';-import { EntryCollaboratorDeleteMutationHandler } from '@/main/mutations/collaborators/entry-collaborator-delete';-import { EntryCollaboratorUpdateMutationHandler } from '@/main/mutations/collaborators/entry-collaborator-update';+import { EntryCollaboratorCreateMutationHandler } from '@/main/mutations/entries/entry-collaborator-create';+import { EntryCollaboratorDeleteMutationHandler } from '@/main/mutations/entries/entry-collaborator-delete';+import { EntryCollaboratorUpdateMutationHandler } from '@/main/mutations/entries/entry-collaborator-update';+import { EntryMarkOpenedMutationHandler } from '@/main/mutations/entries/entry-mark-opened';+import { EntryMarkSeenMutationHandler } from '@/main/mutations/entries/entry-mark-seen';import { MessageReactionCreateMutationHandler } from '@/main/mutations/messages/message-reaction-create';import { MessageReactionDeleteMutationHandler } from '@/main/mutations/messages/message-reaction-delete';+import { MessageMarkSeenMutationHandler } from '@/main/mutations/messages/message-mark-seen';import { PageCreateMutationHandler } from '@/main/mutations/pages/page-create';import { PageUpdateMutationHandler } from '@/main/mutations/pages/page-update';import { PageDeleteMutationHandler } from '@/main/mutations/pages/page-delete';@@ -77,11 +82,14 @@ export const mutationHandlerMap: MutationHandlerMap = {entry_collaborator_create: new EntryCollaboratorCreateMutationHandler(),entry_collaborator_delete: new EntryCollaboratorDeleteMutationHandler(),entry_collaborator_update: new EntryCollaboratorUpdateMutationHandler(),+ entry_mark_opened: new EntryMarkOpenedMutationHandler(),+ entry_mark_seen: new EntryMarkSeenMutationHandler(),page_create: new PageCreateMutationHandler(),page_delete: new PageDeleteMutationHandler(),page_content_update: new PageContentUpdateMutationHandler(),message_reaction_create: new MessageReactionCreateMutationHandler(),message_reaction_delete: new MessageReactionDeleteMutationHandler(),+ message_mark_seen: new MessageMarkSeenMutationHandler(),message_delete: new MessageDeleteMutationHandler(),record_create: new RecordCreateMutationHandler(),record_delete: new RecordDeleteMutationHandler(),@@ -105,6 +113,8 @@ export const mutationHandlerMap: MutationHandlerMap = {folder_create: new FolderCreateMutationHandler(),file_create: new FileCreateMutationHandler(),file_download: new FileDownloadMutationHandler(),+ file_mark_opened: new FileMarkOpenedMutationHandler(),+ file_mark_seen: new FileMarkSeenMutationHandler(),space_update: new SpaceUpdateMutationHandler(),account_update: new AccountUpdateMutationHandler(),view_update: new ViewUpdateMutationHandler(),diff --git a/apps/desktop/src/main/mutations/messages/message-mark-seen.ts b/apps/desktop/src/main/mutations/messages/message-mark-seen.tsnew file mode 100644index 00000000..1c05d119--- /dev/null+++ b/apps/desktop/src/main/mutations/messages/message-mark-seen.ts@@ -0,0 +1,123 @@+import { MarkMessageSeenMutation, generateId, IdType } from '@colanode/core';++import { databaseService } from '@/main/data/database-service';+import { MutationHandler } from '@/main/types';+import {+ MessageMarkSeenMutationInput,+ MessageMarkSeenMutationOutput,+} from '@/shared/mutations/messages/message-mark-seen';+import { eventBus } from '@/shared/lib/event-bus';+import { mapMessageInteraction } from '@/main/utils';++export class MessageMarkSeenMutationHandler+ implements MutationHandler<MessageMarkSeenMutationInput>+{+ async handleMutation(+ input: MessageMarkSeenMutationInput+ ): Promise<MessageMarkSeenMutationOutput> {+ const workspaceDatabase = await databaseService.getWorkspaceDatabase(+ input.userId+ );++ const message = await workspaceDatabase+ .selectFrom('messages')+ .selectAll()+ .where('id', '=', input.messageId)+ .executeTakeFirst();++ if (!message) {+ return {+ success: false,+ };+ }++ const existingInteraction = await workspaceDatabase+ .selectFrom('message_interactions')+ .selectAll()+ .where('message_id', '=', input.messageId)+ .where('collaborator_id', '=', input.userId)+ .executeTakeFirst();++ if (existingInteraction && existingInteraction.seen_at !== null) {+ return {+ success: true,+ };+ }++ const { createdInteraction, createdMutation } = await workspaceDatabase+ .transaction()+ .execute(async (trx) => {+ const createdInteraction = await trx+ .insertInto('message_interactions')+ .returningAll()+ .values({+ message_id: input.messageId,+ collaborator_id: input.userId,+ seen_at: new Date().toISOString(),+ version: 0n,+ root_id: message.root_id,+ })+ .onConflict((b) =>+ b+ .columns(['message_id', 'collaborator_id'])+ .doUpdateSet({+ seen_at: new Date().toISOString(),+ })+ .where('seen_at', 'is', null)+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ throw new Error('Failed to create message interaction');+ }++ const mutation: MarkMessageSeenMutation = {+ id: generateId(IdType.Mutation),+ createdAt: new Date().toISOString(),+ type: 'mark_message_seen',+ data: {+ messageId: input.messageId,+ collaboratorId: input.userId,+ seenAt: new Date().toISOString(),+ },+ };++ 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();++ return {+ createdInteraction,+ createdMutation,+ };+ });++ if (!createdInteraction || !createdMutation) {+ throw new Error('Failed to create message interaction');+ }++ eventBus.publish({+ type: 'mutation_created',+ userId: input.userId,+ });++ eventBus.publish({+ type: 'message_interaction_updated',+ userId: input.userId,+ messageInteraction: mapMessageInteraction(createdInteraction),+ });++ return {+ success: true,+ };+ }+}diff --git a/apps/desktop/src/main/services/entry-service.ts b/apps/desktop/src/main/services/entry-service.tsindex 9d9562fe..a339cbfa 100644--- a/apps/desktop/src/main/services/entry-service.ts+++ b/apps/desktop/src/main/services/entry-service.ts@@ -12,6 +12,7 @@ import {SyncDeleteTransactionData,SyncTransactionData,SyncUpdateTransactionData,+ SyncEntryInteractionData,} from '@colanode/core';import { decodeState, YDoc } from '@colanode/crdt';@@ -23,7 +24,12 @@ import {SelectEntry,SelectTransaction,} from '@/main/data/workspace/schema';-import { fetchEntryAncestors, mapEntry, mapTransaction } from '@/main/utils';+import {+ fetchEntryAncestors,+ mapEntry,+ mapEntryInteraction,+ mapTransaction,+} from '@/main/utils';import { eventBus } from '@/shared/lib/event-bus';const UPDATE_RETRIES_LIMIT = 20;@@ -1296,7 +1302,69 @@ class EntryService {.execute();}- async fetchWorkspace(userId: string): Promise<SelectWorkspace> {+ public async syncServerEntryInteraction(+ userId: string,+ entryInteraction: SyncEntryInteractionData+ ) {+ const workspaceDatabase =+ await databaseService.getWorkspaceDatabase(userId);++ const existingEntryInteraction = await workspaceDatabase+ .selectFrom('entry_interactions')+ .selectAll()+ .where('entry_id', '=', entryInteraction.entryId)+ .executeTakeFirst();++ const version = BigInt(entryInteraction.version);+ if (existingEntryInteraction) {+ if (existingEntryInteraction.version === version) {+ this.debug(+ `Server entry interaction for entry ${entryInteraction.entryId} is already synced`+ );+ return;+ }+ }++ const createdEntryInteraction = await workspaceDatabase+ .insertInto('entry_interactions')+ .returningAll()+ .values({+ entry_id: entryInteraction.entryId,+ root_id: entryInteraction.rootId,+ collaborator_id: entryInteraction.collaboratorId,+ first_seen_at: entryInteraction.firstSeenAt,+ last_seen_at: entryInteraction.lastSeenAt,+ last_opened_at: entryInteraction.lastOpenedAt,+ first_opened_at: entryInteraction.firstOpenedAt,+ version,+ })+ .onConflict((b) =>+ b.columns(['entry_id', 'collaborator_id']).doUpdateSet({+ last_seen_at: entryInteraction.lastSeenAt,+ first_seen_at: entryInteraction.firstSeenAt,+ last_opened_at: entryInteraction.lastOpenedAt,+ first_opened_at: entryInteraction.firstOpenedAt,+ version,+ })+ )+ .executeTakeFirst();++ if (!createdEntryInteraction) {+ return;+ }++ eventBus.publish({+ type: 'entry_interaction_updated',+ userId,+ entryInteraction: mapEntryInteraction(createdEntryInteraction),+ });++ this.debug(+ `Server entry interaction for entry ${entryInteraction.entryId} has been synced`+ );+ }++ private async fetchWorkspace(userId: string): Promise<SelectWorkspace> {const workspace = await databaseService.appDatabase.selectFrom('workspaces').selectAll()diff --git a/apps/desktop/src/main/services/file-service.ts b/apps/desktop/src/main/services/file-service.tsindex f615418a..8fc1cabe 100644--- a/apps/desktop/src/main/services/file-service.ts+++ b/apps/desktop/src/main/services/file-service.ts@@ -4,6 +4,7 @@ import {CreateUploadOutput,extractFileType,SyncFileData,+ SyncFileInteractionData,} from '@colanode/core';import axios from 'axios';import mime from 'mime-types';@@ -19,6 +20,7 @@ import {fetchWorkspaceCredentials,getWorkspaceFilesDirectoryPath,mapFile,+ mapFileInteraction,mapFileState,} from '@/main/utils';import { eventBus } from '@/shared/lib/event-bus';@@ -522,6 +524,68 @@ class FileService {this.debug(`Server file ${file.id} has been synced`);}++ public async syncServerFileInteraction(+ userId: string,+ fileInteraction: SyncFileInteractionData+ ) {+ const workspaceDatabase =+ await databaseService.getWorkspaceDatabase(userId);++ const existingFileInteraction = await workspaceDatabase+ .selectFrom('file_interactions')+ .selectAll()+ .where('file_id', '=', fileInteraction.fileId)+ .executeTakeFirst();++ const version = BigInt(fileInteraction.version);+ if (existingFileInteraction) {+ if (existingFileInteraction.version === version) {+ this.debug(+ `Server file interaction for file ${fileInteraction.fileId} is already synced`+ );+ return;+ }+ }++ const createdFileInteraction = await workspaceDatabase+ .insertInto('file_interactions')+ .returningAll()+ .values({+ file_id: fileInteraction.fileId,+ root_id: fileInteraction.rootId,+ collaborator_id: fileInteraction.collaboratorId,+ first_seen_at: fileInteraction.firstSeenAt,+ last_seen_at: fileInteraction.lastSeenAt,+ last_opened_at: fileInteraction.lastOpenedAt,+ first_opened_at: fileInteraction.firstOpenedAt,+ version,+ })+ .onConflict((b) =>+ b.columns(['file_id', 'collaborator_id']).doUpdateSet({+ last_seen_at: fileInteraction.lastSeenAt,+ first_seen_at: fileInteraction.firstSeenAt,+ last_opened_at: fileInteraction.lastOpenedAt,+ first_opened_at: fileInteraction.firstOpenedAt,+ version,+ })+ )+ .executeTakeFirst();++ if (!createdFileInteraction) {+ return;+ }++ eventBus.publish({+ type: 'file_interaction_updated',+ userId,+ fileInteraction: mapFileInteraction(createdFileInteraction),+ });++ this.debug(+ `Server file interaction for file ${fileInteraction.fileId} has been synced`+ );+ }}export const fileService = new FileService();diff --git a/apps/desktop/src/main/services/message-service.ts b/apps/desktop/src/main/services/message-service.tsindex f6500451..526830c7 100644--- a/apps/desktop/src/main/services/message-service.ts+++ b/apps/desktop/src/main/services/message-service.ts@@ -1,6 +1,14 @@-import { SyncMessageData, SyncMessageReactionData } from '@colanode/core';--import { mapMessage, mapMessageReaction } from '@/main/utils';+import {+ SyncMessageData,+ SyncMessageInteractionData,+ SyncMessageReactionData,+} from '@colanode/core';++import {+ mapMessage,+ mapMessageInteraction,+ mapMessageReaction,+} from '@/main/utils';import { databaseService } from '@/main/data/database-service';import { createDebugger } from '@/main/debugger';import { eventBus } from '@/shared/lib/event-bus';@@ -156,6 +164,66 @@ class MessageService {`Server message reaction for message ${messageReaction.messageId} has been synced`);}++ public async syncServerMessageInteraction(+ userId: string,+ messageInteraction: SyncMessageInteractionData+ ) {+ const workspaceDatabase =+ await databaseService.getWorkspaceDatabase(userId);++ const existingMessageInteraction = await workspaceDatabase+ .selectFrom('message_interactions')+ .selectAll()+ .where('message_id', '=', messageInteraction.messageId)+ .executeTakeFirst();++ const version = BigInt(messageInteraction.version);+ if (existingMessageInteraction) {+ if (existingMessageInteraction.version === version) {+ this.debug(+ `Server message interaction for message ${messageInteraction.messageId} is already synced`+ );+ return;+ }+ }++ const createdMessageInteraction = await workspaceDatabase+ .insertInto('message_interactions')+ .returningAll()+ .values({+ message_id: messageInteraction.messageId,+ collaborator_id: messageInteraction.collaboratorId,+ root_id: messageInteraction.rootId,+ seen_at: messageInteraction.seenAt,+ last_opened_at: messageInteraction.lastOpenedAt,+ first_opened_at: messageInteraction.firstOpenedAt,+ version,+ })+ .onConflict((b) =>+ b.columns(['message_id', 'collaborator_id']).doUpdateSet({+ seen_at: messageInteraction.seenAt,+ last_opened_at: messageInteraction.lastOpenedAt,+ first_opened_at: messageInteraction.firstOpenedAt,+ version,+ })+ )+ .executeTakeFirst();++ if (!createdMessageInteraction) {+ return;+ }++ eventBus.publish({+ type: 'message_interaction_updated',+ userId,+ messageInteraction: mapMessageInteraction(createdMessageInteraction),+ });++ this.debug(+ `Server message interaction for message ${messageInteraction.messageId} has been synced`+ );+ }}export const messageService = new MessageService();diff --git a/apps/desktop/src/main/services/sync-service.ts b/apps/desktop/src/main/services/sync-service.tsindex cff5b04e..44d319f0 100644--- a/apps/desktop/src/main/services/sync-service.ts+++ b/apps/desktop/src/main/services/sync-service.ts@@ -11,6 +11,9 @@ import { TransactionSynchronizer } from '@/main/synchronizers/transactions';import { MessageSynchronizer } from '@/main/synchronizers/messages';import { MessageReactionSynchronizer } from '@/main/synchronizers/message-reactions';import { FileSynchronizer } from '@/main/synchronizers/files';+import { EntryInteractionSynchronizer } from '@/main/synchronizers/entry-interactions';+import { FileInteractionSynchronizer } from '@/main/synchronizers/file-interactions';+import { MessageInteractionSynchronizer } from '@/main/synchronizers/message-interactions';class SyncService {private readonly debug = createDebugger('service:sync');@@ -164,6 +167,33 @@ class SyncService {);}+ if (input.type === 'entry_interactions') {+ return new EntryInteractionSynchronizer(+ userId,+ accountId,+ input,+ workspaceDatabase+ );+ }++ if (input.type === 'file_interactions') {+ return new FileInteractionSynchronizer(+ userId,+ accountId,+ input,+ workspaceDatabase+ );+ }++ if (input.type === 'message_interactions') {+ return new MessageInteractionSynchronizer(+ userId,+ accountId,+ input,+ workspaceDatabase+ );+ }+return null;}@@ -192,6 +222,21 @@ class SyncService {type: 'files',rootId,});++ await this.initSynchronizer(userId, accountId, workspaceDatabase, {+ type: 'entry_interactions',+ rootId,+ });++ await this.initSynchronizer(userId, accountId, workspaceDatabase, {+ type: 'file_interactions',+ rootId,+ });++ await this.initSynchronizer(userId, accountId, workspaceDatabase, {+ type: 'message_interactions',+ rootId,+ });}private removeRootNodeSynchronizers(userId: string, rootId: string) {@@ -230,6 +275,27 @@ class SyncService {) {this.synchronizers.delete(key);}++ if (+ synchronizer.input.type === 'entry_interactions' &&+ synchronizer.input.rootId === rootId+ ) {+ this.synchronizers.delete(key);+ }++ if (+ synchronizer.input.type === 'file_interactions' &&+ synchronizer.input.rootId === rootId+ ) {+ this.synchronizers.delete(key);+ }++ if (+ synchronizer.input.type === 'message_interactions' &&+ synchronizer.input.rootId === rootId+ ) {+ this.synchronizers.delete(key);+ }}}}diff --git a/apps/desktop/src/main/synchronizers/entry-interactions.ts b/apps/desktop/src/main/synchronizers/entry-interactions.tsnew file mode 100644index 00000000..645107ba--- /dev/null+++ b/apps/desktop/src/main/synchronizers/entry-interactions.ts@@ -0,0 +1,17 @@+import {+ SyncEntryInteractionsInput,+ SyncEntryInteractionData,+} from '@colanode/core';++import { BaseSynchronizer } from '@/main/synchronizers/base';+import { entryService } from '@/main/services/entry-service';++export class EntryInteractionSynchronizer extends BaseSynchronizer<SyncEntryInteractionsInput> {+ protected async process(data: SyncEntryInteractionData): Promise<void> {+ await entryService.syncServerEntryInteraction(this.userId, data);+ }++ protected get cursorKey(): string {+ return `entry_interactions:${this.input.rootId}`;+ }+}diff --git a/apps/desktop/src/main/synchronizers/file-interactions.ts b/apps/desktop/src/main/synchronizers/file-interactions.tsnew file mode 100644index 00000000..71dd4ccd--- /dev/null+++ b/apps/desktop/src/main/synchronizers/file-interactions.ts@@ -0,0 +1,17 @@+import {+ SyncFileInteractionsInput,+ SyncFileInteractionData,+} from '@colanode/core';++import { BaseSynchronizer } from '@/main/synchronizers/base';+import { fileService } from '@/main/services/file-service';++export class FileInteractionSynchronizer extends BaseSynchronizer<SyncFileInteractionsInput> {+ protected async process(data: SyncFileInteractionData): Promise<void> {+ await fileService.syncServerFileInteraction(this.userId, data);+ }++ protected get cursorKey(): string {+ return `file_interactions:${this.input.rootId}`;+ }+}diff --git a/apps/desktop/src/main/synchronizers/message-interactions.ts b/apps/desktop/src/main/synchronizers/message-interactions.tsnew file mode 100644index 00000000..2d99a04e--- /dev/null+++ b/apps/desktop/src/main/synchronizers/message-interactions.ts@@ -0,0 +1,17 @@+import {+ SyncMessageInteractionsInput,+ SyncMessageInteractionData,+} from '@colanode/core';++import { BaseSynchronizer } from '@/main/synchronizers/base';+import { messageService } from '@/main/services/message-service';++export class MessageInteractionSynchronizer extends BaseSynchronizer<SyncMessageInteractionsInput> {+ protected async process(data: SyncMessageInteractionData): Promise<void> {+ await messageService.syncServerMessageInteraction(this.userId, data);+ }++ protected get cursorKey(): string {+ return `message_interactions:${this.input.rootId}`;+ }+}diff --git a/apps/desktop/src/main/utils.ts b/apps/desktop/src/main/utils.tsindex f09f1d83..049d5d26 100644--- a/apps/desktop/src/main/utils.ts+++ b/apps/desktop/src/main/utils.ts@@ -28,13 +28,21 @@ import {SelectTransaction,SelectUser,WorkspaceDatabaseSchema,+ SelectMessageInteraction,+ SelectFileInteraction,+ SelectEntryInteraction,} from '@/main/data/workspace/schema';import { Account } from '@/shared/types/accounts';import { Server } from '@/shared/types/servers';import { User } from '@/shared/types/users';-import { File, FileState } from '@/shared/types/files';+import { File, FileInteraction, FileState } from '@/shared/types/files';import { Workspace, WorkspaceCredentials } from '@/shared/types/workspaces';-import { MessageNode, MessageReaction } from '@/shared/types/messages';+import {+ MessageInteraction,+ MessageNode,+ MessageReaction,+} from '@/shared/types/messages';+import { EntryInteraction } from '@/shared/types/entries';export const appPath = app.getPath('userData');@@ -280,6 +288,19 @@ export const mapMessageReaction = (};};+export const mapMessageInteraction = (+ row: SelectMessageInteraction+): MessageInteraction => {+ return {+ messageId: row.message_id,+ collaboratorId: row.collaborator_id,+ rootId: row.root_id,+ seenAt: row.seen_at,+ lastOpenedAt: row.last_opened_at,+ version: row.version,+ };+};+export const mapFile = (row: SelectFile): File => {return {id: row.id,@@ -313,3 +334,33 @@ export const mapFileState = (row: SelectFileState): FileState => {updatedAt: row.updated_at,};};++export const mapFileInteraction = (+ row: SelectFileInteraction+): FileInteraction => {+ return {+ fileId: row.file_id,+ collaboratorId: row.collaborator_id,+ rootId: row.root_id,+ lastSeenAt: row.last_seen_at,+ firstSeenAt: row.first_seen_at,+ lastOpenedAt: row.last_opened_at,+ firstOpenedAt: row.first_opened_at,+ version: row.version,+ };+};++export const mapEntryInteraction = (+ row: SelectEntryInteraction+): EntryInteraction => {+ return {+ entryId: row.entry_id,+ collaboratorId: row.collaborator_id,+ rootId: row.root_id,+ lastSeenAt: row.last_seen_at,+ firstSeenAt: row.first_seen_at,+ lastOpenedAt: row.last_opened_at,+ firstOpenedAt: row.first_opened_at,+ version: row.version,+ };+};diff --git a/apps/desktop/src/renderer/components/channels/channel-body.tsx b/apps/desktop/src/renderer/components/channels/channel-body.tsxindex 4d2fe622..f80a5bed 100644--- a/apps/desktop/src/renderer/components/channels/channel-body.tsx+++ b/apps/desktop/src/renderer/components/channels/channel-body.tsx@@ -15,20 +15,10 @@ export const ChannelBody = ({ channel, role }: ChannelBodyProps) => {const radar = useRadar();useEffect(() => {- radar.markAsOpened(- workspace.userId,- channel.id,- channel.type,- channel.transactionId- );+ radar.markEntryAsOpened(workspace.userId, channel.id);const interval = setInterval(() => {- radar.markAsOpened(- workspace.userId,- channel.id,- channel.type,- channel.transactionId- );+ radar.markEntryAsOpened(workspace.userId, channel.id);}, 60000);return () => clearInterval(interval);diff --git a/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx b/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsxindex d0f330f9..00e13afe 100644--- a/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx+++ b/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx@@ -25,12 +25,7 @@ export const ChannelSidebarItem = ({ channel }: ChannelSidebarItemProps) => {rootMargin="20px"onChange={(inView) => {if (inView) {- radar.markAsSeen(- workspace.userId,- channel.id,- channel.type,- channel.transactionId- );+ radar.markEntryAsSeen(workspace.userId, channel.id);}}}className={cn(diff --git a/apps/desktop/src/renderer/components/chats/chat-body.tsx b/apps/desktop/src/renderer/components/chats/chat-body.tsxindex 0d15ea99..aae312c8 100644--- a/apps/desktop/src/renderer/components/chats/chat-body.tsx+++ b/apps/desktop/src/renderer/components/chats/chat-body.tsx@@ -15,20 +15,10 @@ export const ChatBody = ({ chat, role }: ChatBodyProps) => {const radar = useRadar();useEffect(() => {- radar.markAsOpened(- workspace.userId,- chat.id,- chat.type,- chat.transactionId- );+ radar.markEntryAsOpened(workspace.userId, chat.id);const interval = setInterval(() => {- radar.markAsOpened(- workspace.userId,- chat.id,- chat.type,- chat.transactionId- );+ radar.markEntryAsOpened(workspace.userId, chat.id);}, 60000);return () => clearInterval(interval);diff --git a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsxindex 68b1b402..cb2bd5f5 100644--- a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx+++ b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx@@ -41,12 +41,7 @@ export const ChatSidebarItem = ({ chat }: ChatSidebarItemProps) => {rootMargin="20px"onChange={(inView) => {if (inView) {- radar.markAsSeen(- workspace.userId,- chat.id,- chat.type,- chat.transactionId- );+ radar.markEntryAsSeen(workspace.userId, chat.id);}}}className={cn(diff --git a/apps/desktop/src/renderer/components/databases/database-body.tsx b/apps/desktop/src/renderer/components/databases/database-body.tsxindex 4a5e4b09..cc5148eb 100644--- a/apps/desktop/src/renderer/components/databases/database-body.tsx+++ b/apps/desktop/src/renderer/components/databases/database-body.tsx@@ -16,20 +16,10 @@ export const DatabaseBody = ({ database, role }: DatabaseBodyProps) => {const radar = useRadar();useEffect(() => {- radar.markAsOpened(- workspace.userId,- database.id,- database.type,- database.transactionId- );+ radar.markEntryAsOpened(workspace.userId, database.id);const interval = setInterval(() => {- radar.markAsOpened(- workspace.userId,- database.id,- database.type,- database.transactionId- );+ radar.markEntryAsOpened(workspace.userId, database.id);}, 60000);return () => clearInterval(interval);diff --git a/apps/desktop/src/renderer/components/folders/folder-body.tsx b/apps/desktop/src/renderer/components/folders/folder-body.tsxindex f50023ca..7a8e73ff 100644--- a/apps/desktop/src/renderer/components/folders/folder-body.tsx+++ b/apps/desktop/src/renderer/components/folders/folder-body.tsx@@ -119,20 +119,10 @@ export const FolderBody = ({ folder }: FolderBodyProps) => {};useEffect(() => {- radar.markAsOpened(- workspace.userId,- folder.id,- folder.type,- folder.transactionId- );+ radar.markEntryAsOpened(workspace.userId, folder.id);const interval = setInterval(() => {- radar.markAsOpened(- workspace.userId,- folder.id,- folder.type,- folder.transactionId- );+ radar.markEntryAsOpened(workspace.userId, folder.id);}, 60000);return () => clearInterval(interval);diff --git a/apps/desktop/src/renderer/components/messages/message.tsx b/apps/desktop/src/renderer/components/messages/message.tsxindex 9a47a143..09c25ee5 100644--- a/apps/desktop/src/renderer/components/messages/message.tsx+++ b/apps/desktop/src/renderer/components/messages/message.tsx@@ -6,8 +6,8 @@ import { MessageAuthorName } from '@/renderer/components/messages/message-authorimport { MessageContent } from '@/renderer/components/messages/message-content';import { MessageReactions } from '@/renderer/components/messages/message-reactions';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;@@ -33,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 (@@ -60,12 +60,7 @@ export const Message = ({ message, previousMessage }: MessageProps) => {rootMargin="50px"onChange={(inView) => {if (inView) {- // radar.markAsSeen(- // workspace.userId,- // message.id,- // message.type,- // message.transactionId- // );+ radar.markMessageAsSeen(workspace.userId, message.id);}}}>diff --git a/apps/desktop/src/renderer/components/pages/page-body.tsx b/apps/desktop/src/renderer/components/pages/page-body.tsxindex 3a7c62a6..f0084a01 100644--- a/apps/desktop/src/renderer/components/pages/page-body.tsx+++ b/apps/desktop/src/renderer/components/pages/page-body.tsx@@ -42,20 +42,10 @@ export const PageBody = ({ page, role }: PageBodyProps) => {);useEffect(() => {- radar.markAsOpened(- workspace.userId,- page.id,- page.type,- page.transactionId- );+ radar.markEntryAsOpened(workspace.userId, page.id);const interval = setInterval(() => {- radar.markAsOpened(- workspace.userId,- page.id,- page.type,- page.transactionId- );+ radar.markEntryAsOpened(workspace.userId, page.id);}, 60000);return () => clearInterval(interval);diff --git a/apps/desktop/src/renderer/components/records/record-body.tsx b/apps/desktop/src/renderer/components/records/record-body.tsxindex 51c69754..5b71320c 100644--- a/apps/desktop/src/renderer/components/records/record-body.tsx+++ b/apps/desktop/src/renderer/components/records/record-body.tsx@@ -60,20 +60,10 @@ export const RecordBody = ({);useEffect(() => {- radar.markAsOpened(- workspace.userId,- record.id,- record.type,- record.transactionId- );+ radar.markEntryAsOpened(workspace.userId, record.id);const interval = setInterval(() => {- radar.markAsOpened(- workspace.userId,- record.id,- record.type,- record.transactionId- );+ radar.markEntryAsOpened(workspace.userId, record.id);}, 60000);return () => clearInterval(interval);diff --git a/apps/desktop/src/renderer/contexts/radar.ts b/apps/desktop/src/renderer/contexts/radar.tsindex 9b483bb5..1485ffec 100644--- a/apps/desktop/src/renderer/contexts/radar.ts+++ b/apps/desktop/src/renderer/contexts/radar.ts@@ -1,5 +1,4 @@import { createContext, useContext } from 'react';-import { EntryType } from '@colanode/core';import {AccountReadState,@@ -13,18 +12,11 @@ interface RadarContext {getWorkspaceState: (userId: string) => WorkspaceReadState;getChatState: (userId: string, entryId: string) => ChatReadState;getChannelState: (userId: string, entryIdId: string) => ChannelReadState;- markAsSeen: (- userId: string,- entryId: string,- entryType: EntryType,- transactionId: string- ) => void;- markAsOpened: (- userId: string,- entryId: string,- entryType: EntryType,- transactionId: string- ) => void;+ markMessageAsSeen: (userId: string, messageId: string) => void;+ markFileAsSeen: (userId: string, fileId: string) => void;+ markFileAsOpened: (userId: string, fileId: string) => void;+ markEntryAsSeen: (userId: string, entryId: string) => void;+ markEntryAsOpened: (userId: string, entryId: string) => void;}export const RadarContext = createContext<RadarContext>({} as RadarContext);diff --git a/apps/desktop/src/renderer/radar-provider.tsx b/apps/desktop/src/renderer/radar-provider.tsxindex 5f0cb739..a8546dd9 100644--- a/apps/desktop/src/renderer/radar-provider.tsx+++ b/apps/desktop/src/renderer/radar-provider.tsx@@ -80,31 +80,40 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {mentionsCount: 0,};},- markAsSeen: (userId, entryId, entryType, transactionId) => {- console.log('markAsSeen', userId, entryId, entryType, transactionId);- // window.colanode.executeMutation({- // type: 'mark_entry_as_seen',- // entryId,- // entryType,- // transactionId,- // userId,- // });+ markMessageAsSeen: (userId, messageId) => {+ window.colanode.executeMutation({+ type: 'message_mark_seen',+ messageId,+ userId,+ });+ },+ markFileAsSeen: (userId, fileId) => {+ window.colanode.executeMutation({+ type: 'file_mark_seen',+ fileId,+ userId,+ });},- markAsOpened: (userId, entryId, entryType, transactionId) => {- console.log(- 'markAsOpened',+ markFileAsOpened: (userId, fileId) => {+ window.colanode.executeMutation({+ type: 'file_mark_opened',+ fileId,userId,+ });+ },+ markEntryAsSeen: (userId, entryId) => {+ window.colanode.executeMutation({+ type: 'entry_mark_seen',entryId,- entryType,- transactionId- );- // window.colanode.executeMutation({- // type: 'mark_entry_as_opened',- // entryId,- // entryType,- // transactionId,- // userId,- // });+ userId,+ });+ },+ markEntryAsOpened: (userId, entryId) => {+ window.colanode.executeMutation({+ type: 'entry_mark_opened',+ entryId,+ userId,+ });},}}>diff --git a/apps/desktop/src/shared/mutations/collaborators/entry-collaborator-create.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.tssimilarity index 100%rename from apps/desktop/src/shared/mutations/collaborators/entry-collaborator-create.tsrename to apps/desktop/src/shared/mutations/entries/entry-collaborator-create.tsdiff --git a/apps/desktop/src/shared/mutations/collaborators/entry-collaborator-delete.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.tssimilarity index 100%rename from apps/desktop/src/shared/mutations/collaborators/entry-collaborator-delete.tsrename to apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.tsdiff --git a/apps/desktop/src/shared/mutations/collaborators/entry-collaborator-update.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.tssimilarity index 100%rename from apps/desktop/src/shared/mutations/collaborators/entry-collaborator-update.tsrename to apps/desktop/src/shared/mutations/entries/entry-collaborator-update.tsdiff --git a/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts b/apps/desktop/src/shared/mutations/entries/entry-mark-opened.tsnew file mode 100644index 00000000..0da4d82a--- /dev/null+++ b/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts@@ -0,0 +1,18 @@+export type EntryMarkOpenedMutationInput = {+ type: 'entry_mark_opened';+ userId: string;+ entryId: string;+};++export type EntryMarkOpenedMutationOutput = {+ success: boolean;+};++declare module '@/shared/mutations' {+ interface MutationMap {+ entry_mark_opened: {+ input: EntryMarkOpenedMutationInput;+ output: EntryMarkOpenedMutationOutput;+ };+ }+}diff --git a/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts b/apps/desktop/src/shared/mutations/entries/entry-mark-seen.tsnew file mode 100644index 00000000..361b576a--- /dev/null+++ b/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts@@ -0,0 +1,18 @@+export type EntryMarkSeenMutationInput = {+ type: 'entry_mark_seen';+ userId: string;+ entryId: string;+};++export type EntryMarkSeenMutationOutput = {+ success: boolean;+};++declare module '@/shared/mutations' {+ interface MutationMap {+ entry_mark_seen: {+ input: EntryMarkSeenMutationInput;+ output: EntryMarkSeenMutationOutput;+ };+ }+}diff --git a/apps/desktop/src/shared/mutations/files/file-mark-opened.ts b/apps/desktop/src/shared/mutations/files/file-mark-opened.tsnew file mode 100644index 00000000..c8ae6eb1--- /dev/null+++ b/apps/desktop/src/shared/mutations/files/file-mark-opened.ts@@ -0,0 +1,18 @@+export type FileMarkOpenedMutationInput = {+ type: 'file_mark_opened';+ userId: string;+ fileId: string;+};++export type FileMarkOpenedMutationOutput = {+ success: boolean;+};++declare module '@/shared/mutations' {+ interface MutationMap {+ file_mark_opened: {+ input: FileMarkOpenedMutationInput;+ output: FileMarkOpenedMutationOutput;+ };+ }+}diff --git a/apps/desktop/src/shared/mutations/files/file-mark-seen.ts b/apps/desktop/src/shared/mutations/files/file-mark-seen.tsnew file mode 100644index 00000000..31a7ab80--- /dev/null+++ b/apps/desktop/src/shared/mutations/files/file-mark-seen.ts@@ -0,0 +1,18 @@+export type FileMarkSeenMutationInput = {+ type: 'file_mark_seen';+ userId: string;+ fileId: string;+};++export type FileMarkSeenMutationOutput = {+ success: boolean;+};++declare module '@/shared/mutations' {+ interface MutationMap {+ file_mark_seen: {+ input: FileMarkSeenMutationInput;+ output: FileMarkSeenMutationOutput;+ };+ }+}diff --git a/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts b/apps/desktop/src/shared/mutations/messages/message-mark-seen.tsnew file mode 100644index 00000000..9baac3d0--- /dev/null+++ b/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts@@ -0,0 +1,18 @@+export type MessageMarkSeenMutationInput = {+ type: 'message_mark_seen';+ userId: string;+ messageId: string;+};++export type MessageMarkSeenMutationOutput = {+ success: boolean;+};++declare module '@/shared/mutations' {+ interface MutationMap {+ message_mark_seen: {+ input: MessageMarkSeenMutationInput;+ output: MessageMarkSeenMutationOutput;+ };+ }+}diff --git a/apps/desktop/src/shared/types/entries.ts b/apps/desktop/src/shared/types/entries.tsindex ecbe897a..ec888b61 100644--- a/apps/desktop/src/shared/types/entries.ts+++ b/apps/desktop/src/shared/types/entries.ts@@ -5,3 +5,14 @@ export type EntryCollaborator = {collaboratorId: string;role: EntryRole;};++export type EntryInteraction = {+ entryId: string;+ collaboratorId: string;+ rootId: string;+ lastSeenAt: string | null;+ firstSeenAt: string | null;+ lastOpenedAt: string | null;+ firstOpenedAt: string | null;+ version: bigint;+};diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.tsindex 3189d0f2..2d742803 100644--- a/apps/desktop/src/shared/types/events.ts+++ b/apps/desktop/src/shared/types/events.ts@@ -1,12 +1,17 @@import { Entry } from '@colanode/core';-import { MessageNode, MessageReaction } from '@/shared/types/messages';+import { EntryInteraction } from '@/shared/types/entries';+import {+ MessageInteraction,+ MessageNode,+ MessageReaction,+} from '@/shared/types/messages';import { Account } from '@/shared/types/accounts';import { Interaction } from '@/shared/types/interactions';import { Server } from '@/shared/types/servers';import { Workspace } from '@/shared/types/workspaces';import { User } from '@/shared/types/users';-import { File, FileState } from '@/shared/types/files';+import { File, FileInteraction, FileState } from '@/shared/types/files';export type UserCreatedEvent = {type: 'user_created';@@ -44,6 +49,12 @@ export type EntryDeletedEvent = {entry: Entry;};+export type EntryInteractionUpdatedEvent = {+ type: 'entry_interaction_updated';+ userId: string;+ entryInteraction: EntryInteraction;+};+export type MessageCreatedEvent = {type: 'message_created';userId: string;@@ -74,6 +85,12 @@ export type MessageReactionDeletedEvent = {messageReaction: MessageReaction;};+export type MessageInteractionUpdatedEvent = {+ type: 'message_interaction_updated';+ userId: string;+ messageInteraction: MessageInteraction;+};+export type FileCreatedEvent = {type: 'file_created';userId: string;@@ -110,6 +127,12 @@ export type FileStateDeletedEvent = {fileState: FileState;};+export type FileInteractionUpdatedEvent = {+ type: 'file_interaction_updated';+ userId: string;+ fileInteraction: FileInteraction;+};+export type AccountCreatedEvent = {type: 'account_created';account: Account;@@ -207,11 +230,13 @@ export type Event =| EntryCreatedEvent| EntryUpdatedEvent| EntryDeletedEvent+ | EntryInteractionUpdatedEvent| MessageCreatedEvent| MessageUpdatedEvent| MessageDeletedEvent| MessageReactionCreatedEvent| MessageReactionDeletedEvent+ | MessageInteractionUpdatedEvent| AccountCreatedEvent| AccountUpdatedEvent| AccountDeletedEvent@@ -226,6 +251,7 @@ export type Event =| FileStateCreatedEvent| FileStateUpdatedEvent| FileStateDeletedEvent+ | FileInteractionUpdatedEvent| QueryResultUpdatedEvent| RadarDataUpdatedEvent| MutationCreatedEventdiff --git a/apps/desktop/src/shared/types/files.ts b/apps/desktop/src/shared/types/files.tsindex ccd37341..0aa0ae70 100644--- a/apps/desktop/src/shared/types/files.ts+++ b/apps/desktop/src/shared/types/files.ts@@ -48,3 +48,14 @@ export type FileWithState = File & {uploadProgress: number;uploadStatus: UploadStatus;};++export type FileInteraction = {+ fileId: string;+ collaboratorId: string;+ rootId: string;+ lastSeenAt: string | null;+ firstSeenAt: string | null;+ lastOpenedAt: string | null;+ firstOpenedAt: string | null;+ version: bigint;+};diff --git a/apps/desktop/src/shared/types/messages.ts b/apps/desktop/src/shared/types/messages.tsindex e8a3d6a0..a2aa579f 100644--- a/apps/desktop/src/shared/types/messages.ts+++ b/apps/desktop/src/shared/types/messages.ts@@ -26,3 +26,12 @@ export type MessageReactionsCount = {count: number;reacted: boolean;};++export type MessageInteraction = {+ messageId: string;+ collaboratorId: string;+ rootId: string;+ seenAt: string | null;+ lastOpenedAt: string | null;+ version: bigint;+};diff --git a/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.ts b/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.tsindex eafed537..d43c0233 100644--- a/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.ts+++ b/apps/server/src/controllers/client/workspaces/mutations/mutations-sync.ts@@ -11,6 +11,11 @@ import {CreateMessageMutation,CreateMessageReactionMutation,DeleteMessageReactionMutation,+ MarkEntrySeenMutation,+ MarkEntryOpenedMutation,+ MarkMessageSeenMutation,+ MarkFileSeenMutation,+ MarkFileOpenedMutation,} from '@colanode/core';import { SelectUser } from '@/data/schema';@@ -63,6 +68,16 @@ const handleMutation = async (return await handleCreateMessageReaction(user, mutation);} else if (mutation.type === 'delete_message_reaction') {return await handleDeleteMessageReaction(user, mutation);+ } else if (mutation.type === 'mark_entry_seen') {+ return await handleMarkEntrySeenMutation(user, mutation);+ } else if (mutation.type === 'mark_entry_opened') {+ return await handleMarkEntryOpenedMutation(user, mutation);+ } else if (mutation.type === 'mark_message_seen') {+ return await handleMarkMessageSeenMutation(user, mutation);+ } else if (mutation.type === 'mark_file_seen') {+ return await handleMarkFileSeenMutation(user, mutation);+ } else if (mutation.type === 'mark_file_opened') {+ return await markFileOpenedMutation(user, mutation);} else {return 'error';}@@ -156,3 +171,43 @@ const handleDeleteMessageReaction = async (const output = await messageService.deleteMessageReaction(user, mutation);return output ? 'success' : 'error';};++const handleMarkEntrySeenMutation = async (+ user: SelectUser,+ mutation: MarkEntrySeenMutation+): Promise<SyncMutationStatus> => {+ const output = await entryService.markEntryAsSeen(user, mutation);+ return output ? 'success' : 'error';+};++const handleMarkEntryOpenedMutation = async (+ user: SelectUser,+ mutation: MarkEntryOpenedMutation+): Promise<SyncMutationStatus> => {+ const output = await entryService.markEntryAsOpened(user, mutation);+ return output ? 'success' : 'error';+};++const handleMarkMessageSeenMutation = async (+ user: SelectUser,+ mutation: MarkMessageSeenMutation+): Promise<SyncMutationStatus> => {+ const output = await messageService.markMessageAsSeen(user, mutation);+ return output ? 'success' : 'error';+};++const handleMarkFileSeenMutation = async (+ user: SelectUser,+ mutation: MarkFileSeenMutation+): Promise<SyncMutationStatus> => {+ const output = await fileService.markFileAsSeen(user, mutation);+ return output ? 'success' : 'error';+};++const markFileOpenedMutation = async (+ user: SelectUser,+ mutation: MarkFileOpenedMutation+): Promise<SyncMutationStatus> => {+ const output = await fileService.markFileAsOpened(user, mutation);+ return output ? 'success' : 'error';+};diff --git a/apps/server/src/data/migrations.ts b/apps/server/src/data/migrations.tsindex 501a33c8..6165405c 100644--- a/apps/server/src/data/migrations.ts+++ b/apps/server/src/data/migrations.ts@@ -252,6 +252,65 @@ const createCollaborationsTable: Migration = {},};+const createEntryInteractionsTable: Migration = {+ up: async (db) => {+ await sql`+ CREATE SEQUENCE IF NOT EXISTS entry_interactions_version_sequence+ START WITH 1000000000+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+ `.execute(db);++ await db.schema+ .createTable('entry_interactions')+ .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('first_seen_at', 'timestamptz')+ .addColumn('last_seen_at', 'timestamptz')+ .addColumn('first_opened_at', 'timestamptz')+ .addColumn('last_opened_at', 'timestamptz')+ .addColumn('version', 'bigint', (col) =>+ col+ .notNull()+ .defaultTo(sql`nextval('entry_interactions_version_sequence')`)+ )+ .addPrimaryKeyConstraint('entry_interactions_pkey', [+ 'entry_id',+ 'collaborator_id',+ ])+ .execute();++ await sql`+ CREATE OR REPLACE FUNCTION update_entry_interaction_version() RETURNS TRIGGER AS $$+ BEGIN+ NEW.version = nextval('entry_interactions_version_sequence');+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql;++ CREATE TRIGGER trg_update_entry_interaction_version+ BEFORE UPDATE ON entry_interactions+ FOR EACH ROW+ EXECUTE FUNCTION update_entry_interaction_version();+ `.execute(db);+ },+ down: async (db) => {+ await sql`+ DROP TRIGGER IF EXISTS trg_update_entry_interaction_version ON entry_interactions;+ DROP FUNCTION IF EXISTS update_entry_interaction_version();+ `.execute(db);++ await db.schema.dropTable('entry_interactions').execute();+ await sql`DROP SEQUENCE IF EXISTS entry_interactions_version_sequence`.execute(+ db+ );+ },+};+const createMessagesTable: Migration = {up: async (db) => {await sql`@@ -362,6 +421,64 @@ const createMessageReactionsTable: Migration = {},};+const createMessageInteractionsTable: Migration = {+ up: async (db) => {+ await sql`+ CREATE SEQUENCE IF NOT EXISTS message_interactions_version_sequence+ START WITH 1000000000+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+ `.execute(db);++ await db.schema+ .createTable('message_interactions')+ .addColumn('message_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('seen_at', 'timestamptz')+ .addColumn('first_opened_at', 'timestamptz')+ .addColumn('last_opened_at', 'timestamptz')+ .addColumn('version', 'bigint', (col) =>+ col+ .notNull()+ .defaultTo(sql`nextval('message_interactions_version_sequence')`)+ )+ .addPrimaryKeyConstraint('message_interactions_pkey', [+ 'message_id',+ 'collaborator_id',+ ])+ .execute();++ await sql`+ CREATE OR REPLACE FUNCTION update_message_interaction_version() RETURNS TRIGGER AS $$+ BEGIN+ NEW.version = nextval('message_interactions_version_sequence');+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql;++ CREATE TRIGGER trg_update_message_interaction_version+ BEFORE UPDATE ON message_interactions+ FOR EACH ROW+ EXECUTE FUNCTION update_message_interaction_version();+ `.execute(db);+ },+ down: async (db) => {+ await sql`+ DROP TRIGGER IF EXISTS trg_update_message_interaction_version ON message_interactions;+ DROP FUNCTION IF EXISTS update_message_interaction_version();+ `.execute(db);++ await db.schema.dropTable('message_interactions').execute();+ await sql`DROP SEQUENCE IF EXISTS message_interactions_version_sequence`.execute(+ db+ );+ },+};+const createFilesTable: Migration = {up: async (db) => {await sql`@@ -423,6 +540,65 @@ const createFilesTable: Migration = {},};+const createFileInteractionsTable: Migration = {+ up: async (db) => {+ await sql`+ CREATE SEQUENCE IF NOT EXISTS file_interactions_version_sequence+ START WITH 1000000000+ INCREMENT BY 1+ NO MINVALUE+ NO MAXVALUE+ CACHE 1;+ `.execute(db);++ await db.schema+ .createTable('file_interactions')+ .addColumn('file_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())+ .addColumn('first_seen_at', 'timestamptz')+ .addColumn('last_seen_at', 'timestamptz')+ .addColumn('first_opened_at', 'timestamptz')+ .addColumn('last_opened_at', 'timestamptz')+ .addColumn('version', 'bigint', (col) =>+ col+ .notNull()+ .defaultTo(sql`nextval('file_interactions_version_sequence')`)+ )+ .addPrimaryKeyConstraint('file_interactions_pkey', [+ 'file_id',+ 'collaborator_id',+ ])+ .execute();++ await sql`+ CREATE OR REPLACE FUNCTION update_file_interaction_version() RETURNS TRIGGER AS $$+ BEGIN+ NEW.version = nextval('file_interactions_version_sequence');+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql;++ CREATE TRIGGER trg_update_file_interaction_version+ BEFORE UPDATE ON file_interactions+ FOR EACH ROW+ EXECUTE FUNCTION update_file_interaction_version();+ `.execute(db);+ },+ down: async (db) => {+ await sql`+ DROP TRIGGER IF EXISTS trg_update_file_interaction_version ON file_interactions;+ DROP FUNCTION IF EXISTS update_file_interaction_version();+ `.execute(db);++ await db.schema.dropTable('file_interactions').execute();+ await sql`DROP SEQUENCE IF EXISTS file_interactions_version_sequence`.execute(+ db+ );+ },+};+const createEntryPathsTable: Migration = {up: async (db) => {await db.schema@@ -504,9 +680,12 @@ export const databaseMigrations: Record<string, Migration> = {'00004_create_users_table': createUsersTable,'00005_create_entries_table': createEntriesTable,'00006_create_transactions_table': createTransactionsTable,- '00007_create_messages_table': createMessagesTable,- '00008_create_message_reactions_table': createMessageReactionsTable,- '00009_create_files_table': createFilesTable,- '00010_create_collaborations_table': createCollaborationsTable,- '00011_create_entry_paths_table': createEntryPathsTable,+ '00007_create_entry_interactions_table': createEntryInteractionsTable,+ '00008_create_messages_table': createMessagesTable,+ '00009_create_message_reactions_table': createMessageReactionsTable,+ '00010_create_message_interactions_table': createMessageInteractionsTable,+ '00011_create_files_table': createFilesTable,+ '00012_create_file_interactions_table': createFileInteractionsTable,+ '00013_create_collaborations_table': createCollaborationsTable,+ '00014_create_entry_paths_table': createEntryPathsTable,};diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.tsindex 5953f77a..48ac0857 100644--- a/apps/server/src/data/schema.ts+++ b/apps/server/src/data/schema.ts@@ -146,6 +146,22 @@ export type SelectTransaction = Selectable<TransactionTable>;export type CreateTransaction = Insertable<TransactionTable>;export type UpdateTransaction = Updateable<TransactionTable>;+interface EntryInteractionTable {+ entry_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, never>;+ workspace_id: ColumnType<string, string, never>;+ first_seen_at: ColumnType<Date | null, Date | null, Date | null>;+ last_seen_at: ColumnType<Date | null, Date | null, Date | null>;+ first_opened_at: ColumnType<Date | null, Date | null, Date | null>;+ last_opened_at: ColumnType<Date | null, Date | null, Date | null>;+ version: ColumnType<bigint, never, never>;+}++export type SelectEntryInteraction = Selectable<EntryInteractionTable>;+export type CreateEntryInteraction = Insertable<EntryInteractionTable>;+export type UpdateEntryInteraction = Updateable<EntryInteractionTable>;+interface MessageTable {id: ColumnType<string, string, never>;type: ColumnType<MessageType, MessageType, MessageType>;@@ -182,6 +198,21 @@ export type SelectMessageReaction = Selectable<MessageReactionTable>;export type CreateMessageReaction = Insertable<MessageReactionTable>;export type UpdateMessageReaction = Updateable<MessageReactionTable>;+interface MessageInteractionTable {+ message_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, never>;+ workspace_id: ColumnType<string, string, never>;+ seen_at: ColumnType<Date | null, Date | null, Date | null>;+ first_opened_at: ColumnType<Date | null, Date | null, Date | null>;+ last_opened_at: ColumnType<Date | null, Date | null, Date | null>;+ version: ColumnType<bigint, never, never>;+}++export type SelectMessageInteraction = Selectable<MessageInteractionTable>;+export type CreateMessageInteraction = Insertable<MessageInteractionTable>;+export type UpdateMessageInteraction = Updateable<MessageInteractionTable>;+interface FileTable {id: ColumnType<string, string, never>;type: ColumnType<FileType, FileType, FileType>;@@ -208,6 +239,22 @@ export type SelectFile = Selectable<FileTable>;export type CreateFile = Insertable<FileTable>;export type UpdateFile = Updateable<FileTable>;+interface FileInteractionTable {+ file_id: ColumnType<string, string, never>;+ collaborator_id: ColumnType<string, string, never>;+ root_id: ColumnType<string, string, never>;+ workspace_id: ColumnType<string, string, never>;+ first_seen_at: ColumnType<Date | null, Date | null, Date | null>;+ last_seen_at: ColumnType<Date | null, Date | null, Date | null>;+ first_opened_at: ColumnType<Date | null, Date | null, Date | null>;+ last_opened_at: ColumnType<Date | null, Date | null, Date | null>;+ version: ColumnType<bigint, never, never>;+}++export type SelectFileInteraction = Selectable<FileInteractionTable>;+export type CreateFileInteraction = Insertable<FileInteractionTable>;+export type UpdateFileInteraction = Updateable<FileInteractionTable>;+interface EntryPathTable {ancestor_id: ColumnType<string, string, never>;descendant_id: ColumnType<string, string, never>;@@ -226,9 +273,12 @@ export interface DatabaseSchema {users: UserTable;entries: EntryTable;transactions: TransactionTable;+ entry_interactions: EntryInteractionTable;+ collaborations: CollaborationTable;messages: MessageTable;message_reactions: MessageReactionTable;- collaborations: CollaborationTable;+ message_interactions: MessageInteractionTable;files: FileTable;+ file_interactions: FileInteractionTable;entry_paths: EntryPathTable;}diff --git a/apps/server/src/services/entry-service.ts b/apps/server/src/services/entry-service.tsindex 8d4444bd..d7e4e73f 100644--- a/apps/server/src/services/entry-service.ts+++ b/apps/server/src/services/entry-service.ts@@ -6,6 +6,10 @@ import {EntryMutationContext,EntryRole,registry,+ MarkEntrySeenMutation,+ MarkEntryOpenedMutation,+ extractEntryRole,+ hasViewerAccess,} from '@colanode/core';import { decodeState, YDoc } from '@colanode/crdt';import { Transaction } from 'kysely';@@ -657,6 +661,168 @@ class EntryService {};}+ public async markEntryAsSeen(+ user: SelectUser,+ mutation: MarkEntrySeenMutation+ ): Promise<boolean> {+ const entry = await database+ .selectFrom('entries')+ .select(['id', 'root_id', 'workspace_id'])+ .where('id', '=', mutation.data.entryId)+ .executeTakeFirst();++ if (!entry) {+ return false;+ }++ const root = await database+ .selectFrom('entries')+ .selectAll()+ .where('id', '=', entry.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootEntry = mapEntry(root);+ const role = extractEntryRole(rootEntry, user.id);+ if (!hasViewerAccess(role)) {+ return false;+ }++ const existingInteraction = await database+ .selectFrom('entry_interactions')+ .selectAll()+ .where('entry_id', '=', mutation.data.entryId)+ .where('collaborator_id', '=', user.id)+ .executeTakeFirst();++ if (+ existingInteraction &&+ existingInteraction.last_seen_at !== null &&+ existingInteraction.last_seen_at <= new Date(mutation.data.seenAt)+ ) {+ return true;+ }++ const lastSeenAt = new Date(mutation.data.seenAt);+ const firstSeenAt = existingInteraction?.first_seen_at ?? lastSeenAt;+ const createdInteraction = await database+ .insertInto('entry_interactions')+ .returningAll()+ .values({+ entry_id: mutation.data.entryId,+ collaborator_id: user.id,+ first_seen_at: firstSeenAt,+ last_seen_at: lastSeenAt,+ root_id: root.id,+ workspace_id: root.workspace_id,+ })+ .onConflict((b) =>+ b.columns(['entry_id', 'collaborator_id']).doUpdateSet({+ last_seen_at: lastSeenAt,+ first_seen_at: firstSeenAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ return false;+ }++ eventBus.publish({+ type: 'entry_interaction_updated',+ entryId: createdInteraction.entry_id,+ collaboratorId: createdInteraction.collaborator_id,+ rootId: createdInteraction.root_id,+ workspaceId: createdInteraction.workspace_id,+ });++ return true;+ }++ public async markEntryAsOpened(+ user: SelectUser,+ mutation: MarkEntryOpenedMutation+ ): Promise<boolean> {+ const entry = await database+ .selectFrom('entries')+ .select(['id', 'root_id', 'workspace_id'])+ .where('id', '=', mutation.data.entryId)+ .executeTakeFirst();++ if (!entry) {+ return false;+ }++ const root = await database+ .selectFrom('entries')+ .selectAll()+ .where('id', '=', entry.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootEntry = mapEntry(root);+ const role = extractEntryRole(rootEntry, user.id);+ if (!hasViewerAccess(role)) {+ return false;+ }++ const existingInteraction = await database+ .selectFrom('entry_interactions')+ .selectAll()+ .where('entry_id', '=', mutation.data.entryId)+ .where('collaborator_id', '=', user.id)+ .executeTakeFirst();++ if (+ existingInteraction &&+ existingInteraction.last_opened_at !== null &&+ existingInteraction.last_opened_at <= new Date(mutation.data.openedAt)+ ) {+ return true;+ }++ const lastOpenedAt = new Date(mutation.data.openedAt);+ const firstOpenedAt = existingInteraction?.first_opened_at ?? lastOpenedAt;+ const createdInteraction = await database+ .insertInto('entry_interactions')+ .returningAll()+ .values({+ entry_id: mutation.data.entryId,+ collaborator_id: user.id,+ first_opened_at: firstOpenedAt,+ last_opened_at: lastOpenedAt,+ root_id: root.id,+ workspace_id: root.workspace_id,+ })+ .onConflict((b) =>+ b.columns(['entry_id', 'collaborator_id']).doUpdateSet({+ last_opened_at: lastOpenedAt,+ first_opened_at: firstOpenedAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ return false;+ }++ eventBus.publish({+ type: 'entry_interaction_updated',+ entryId: createdInteraction.entry_id,+ collaboratorId: createdInteraction.collaborator_id,+ rootId: createdInteraction.root_id,+ workspaceId: createdInteraction.workspace_id,+ });++ return true;+ }+private async applyDatabaseCreateTransaction(attributes: EntryAttributes,entry: CreateEntry,diff --git a/apps/server/src/services/file-service.ts b/apps/server/src/services/file-service.tsindex 9627f22e..ae1631e1 100644--- a/apps/server/src/services/file-service.ts+++ b/apps/server/src/services/file-service.ts@@ -3,6 +3,9 @@ import {extractEntryRole,FileStatus,hasCollaboratorAccess,+ hasViewerAccess,+ MarkFileOpenedMutation,+ MarkFileSeenMutation,} from '@colanode/core';import { database } from '@/data/database';@@ -74,6 +77,168 @@ class FileService {return true;}++ public async markFileAsSeen(+ user: SelectUser,+ mutation: MarkFileSeenMutation+ ): Promise<boolean> {+ const file = await database+ .selectFrom('files')+ .select(['id', 'root_id', 'workspace_id'])+ .where('id', '=', mutation.data.fileId)+ .executeTakeFirst();++ if (!file) {+ return false;+ }++ const root = await database+ .selectFrom('entries')+ .selectAll()+ .where('id', '=', file.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootEntry = mapEntry(root);+ const role = extractEntryRole(rootEntry, user.id);+ if (!hasViewerAccess(role)) {+ return false;+ }++ const existingInteraction = await database+ .selectFrom('file_interactions')+ .selectAll()+ .where('file_id', '=', mutation.data.fileId)+ .where('collaborator_id', '=', user.id)+ .executeTakeFirst();++ if (+ existingInteraction &&+ existingInteraction.last_seen_at !== null &&+ existingInteraction.last_seen_at <= new Date(mutation.data.seenAt)+ ) {+ return true;+ }++ const lastSeenAt = new Date(mutation.data.seenAt);+ const firstSeenAt = existingInteraction?.first_seen_at ?? lastSeenAt;+ const createdInteraction = await database+ .insertInto('file_interactions')+ .returningAll()+ .values({+ file_id: mutation.data.fileId,+ collaborator_id: user.id,+ first_seen_at: firstSeenAt,+ last_seen_at: lastSeenAt,+ root_id: root.id,+ workspace_id: root.workspace_id,+ })+ .onConflict((b) =>+ b.columns(['file_id', 'collaborator_id']).doUpdateSet({+ last_seen_at: lastSeenAt,+ first_seen_at: firstSeenAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ return false;+ }++ eventBus.publish({+ type: 'file_interaction_updated',+ fileId: createdInteraction.file_id,+ collaboratorId: createdInteraction.collaborator_id,+ rootId: createdInteraction.root_id,+ workspaceId: createdInteraction.workspace_id,+ });++ return true;+ }++ public async markFileAsOpened(+ user: SelectUser,+ mutation: MarkFileOpenedMutation+ ): Promise<boolean> {+ const file = await database+ .selectFrom('files')+ .select(['id', 'root_id', 'workspace_id'])+ .where('id', '=', mutation.data.fileId)+ .executeTakeFirst();++ if (!file) {+ return false;+ }++ const root = await database+ .selectFrom('entries')+ .selectAll()+ .where('id', '=', file.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootEntry = mapEntry(root);+ const role = extractEntryRole(rootEntry, user.id);+ if (!hasViewerAccess(role)) {+ return false;+ }++ const existingInteraction = await database+ .selectFrom('file_interactions')+ .selectAll()+ .where('file_id', '=', mutation.data.fileId)+ .where('collaborator_id', '=', user.id)+ .executeTakeFirst();++ if (+ existingInteraction &&+ existingInteraction.last_opened_at !== null &&+ existingInteraction.last_opened_at <= new Date(mutation.data.openedAt)+ ) {+ return true;+ }++ const lastOpenedAt = new Date(mutation.data.openedAt);+ const firstOpenedAt = existingInteraction?.first_opened_at ?? lastOpenedAt;+ const createdInteraction = await database+ .insertInto('file_interactions')+ .returningAll()+ .values({+ file_id: mutation.data.fileId,+ collaborator_id: user.id,+ first_opened_at: firstOpenedAt,+ last_opened_at: lastOpenedAt,+ root_id: root.id,+ workspace_id: root.workspace_id,+ })+ .onConflict((b) =>+ b.columns(['file_id', 'collaborator_id']).doUpdateSet({+ last_opened_at: lastOpenedAt,+ first_opened_at: firstOpenedAt,+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ return false;+ }++ eventBus.publish({+ type: 'file_interaction_updated',+ fileId: createdInteraction.file_id,+ collaboratorId: createdInteraction.collaborator_id,+ rootId: createdInteraction.root_id,+ workspaceId: createdInteraction.workspace_id,+ });++ return true;+ }}export const fileService = new FileService();diff --git a/apps/server/src/services/message-service.ts b/apps/server/src/services/message-service.tsindex b97de55d..ae45b924 100644--- a/apps/server/src/services/message-service.ts+++ b/apps/server/src/services/message-service.ts@@ -4,6 +4,8 @@ import {DeleteMessageReactionMutation,extractEntryRole,hasCollaboratorAccess,+ hasViewerAccess,+ MarkMessageSeenMutation,} from '@colanode/core';import { database } from '@/data/database';@@ -189,6 +191,83 @@ class MessageService {return true;}++ public async markMessageAsSeen(+ user: SelectUser,+ mutation: MarkMessageSeenMutation+ ): 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('entries')+ .selectAll()+ .where('id', '=', message.root_id)+ .executeTakeFirst();++ if (!root) {+ return false;+ }++ const rootEntry = mapEntry(root);+ const role = extractEntryRole(rootEntry, user.id);+ if (!hasViewerAccess(role)) {+ return false;+ }++ const existingInteraction = await database+ .selectFrom('message_interactions')+ .selectAll()+ .where('message_id', '=', mutation.data.messageId)+ .where('collaborator_id', '=', user.id)+ .executeTakeFirst();++ if (+ existingInteraction &&+ existingInteraction.seen_at !== null &&+ existingInteraction.seen_at <= new Date(mutation.data.seenAt)+ ) {+ return true;+ }++ const createdInteraction = await database+ .insertInto('message_interactions')+ .returningAll()+ .values({+ message_id: mutation.data.messageId,+ collaborator_id: user.id,+ seen_at: new Date(mutation.data.seenAt),+ root_id: root.id,+ workspace_id: root.workspace_id,+ })+ .onConflict((b) =>+ b.columns(['message_id', 'collaborator_id']).doUpdateSet({+ seen_at: new Date(mutation.data.seenAt),+ })+ )+ .executeTakeFirst();++ if (!createdInteraction) {+ return false;+ }++ eventBus.publish({+ type: 'message_interaction_updated',+ messageId: createdInteraction.message_id,+ collaboratorId: createdInteraction.collaborator_id,+ rootId: createdInteraction.root_id,+ workspaceId: createdInteraction.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 f4ddd01e..8cb12d72 100644--- a/apps/server/src/services/socket-connection.ts+++ b/apps/server/src/services/socket-connection.ts@@ -25,6 +25,9 @@ import { FileSynchronizer } from '@/synchronizers/files';import { MessageSynchronizer } from '@/synchronizers/messages';import { MessageReactionSynchronizer } from '@/synchronizers/message-reactions';import { TransactionSynchronizer } from '@/synchronizers/transactions';+import { MessageInteractionSynchronizer } from '@/synchronizers/message-interactions';+import { EntryInteractionSynchronizer } from '@/synchronizers/entry-interactions';+import { FileInteractionSynchronizer } from '@/synchronizers/file-interactions';type SocketUser = {user: ConnectedUser;@@ -168,6 +171,39 @@ export class SocketConnection {message.input,cursor);+ } else if (message.input.type === 'message_interactions') {+ if (!user.rootIds.has(message.input.rootId)) {+ return null;+ }++ return new MessageInteractionSynchronizer(+ message.id,+ user.user,+ message.input,+ cursor+ );+ } else if (message.input.type === 'entry_interactions') {+ if (!user.rootIds.has(message.input.rootId)) {+ return null;+ }++ return new EntryInteractionSynchronizer(+ message.id,+ user.user,+ message.input,+ cursor+ );+ } else if (message.input.type === 'file_interactions') {+ if (!user.rootIds.has(message.input.rootId)) {+ return null;+ }++ return new FileInteractionSynchronizer(+ message.id,+ user.user,+ message.input,+ cursor+ );}return null;diff --git a/apps/server/src/synchronizers/entry-interactions.ts b/apps/server/src/synchronizers/entry-interactions.tsnew file mode 100644index 00000000..4001d3f7--- /dev/null+++ b/apps/server/src/synchronizers/entry-interactions.ts@@ -0,0 +1,94 @@+import {+ SynchronizerOutputMessage,+ SyncEntryInteractionsInput,+ SyncEntryInteractionData,+} from '@colanode/core';++import { BaseSynchronizer } from '@/synchronizers/base';+import { Event } from '@/types/events';+import { database } from '@/data/database';+import { SelectEntryInteraction } from '@/data/schema';++export class EntryInteractionSynchronizer extends BaseSynchronizer<SyncEntryInteractionsInput> {+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncEntryInteractionsInput> | null> {+ const entryInteractions = await this.fetchEntryInteractions();+ if (entryInteractions.length === 0) {+ return null;+ }++ return this.buildMessage(entryInteractions);+ }++ public async fetchDataFromEvent(+ event: Event+ ): Promise<SynchronizerOutputMessage<SyncEntryInteractionsInput> | null> {+ if (!this.shouldFetch(event)) {+ return null;+ }++ const entryInteractions = await this.fetchEntryInteractions();+ if (entryInteractions.length === 0) {+ return null;+ }++ return this.buildMessage(entryInteractions);+ }++ private async fetchEntryInteractions() {+ if (this.status === 'fetching') {+ return [];+ }++ this.status = 'fetching';+ const entryInteractions = await database+ .selectFrom('entry_interactions')+ .selectAll()+ .where('root_id', '=', this.input.rootId)+ .where('version', '>', this.cursor)+ .orderBy('version', 'asc')+ .limit(20)+ .execute();++ this.status = 'pending';+ return entryInteractions;+ }++ private buildMessage(+ unsyncedEntryInteractions: SelectEntryInteraction[]+ ): SynchronizerOutputMessage<SyncEntryInteractionsInput> {+ const items: SyncEntryInteractionData[] = unsyncedEntryInteractions.map(+ (entryInteraction) => ({+ entryId: entryInteraction.entry_id,+ collaboratorId: entryInteraction.collaborator_id,+ firstSeenAt: entryInteraction.first_seen_at?.toISOString() ?? null,+ lastSeenAt: entryInteraction.last_seen_at?.toISOString() ?? null,+ firstOpenedAt: entryInteraction.first_opened_at?.toISOString() ?? null,+ lastOpenedAt: entryInteraction.last_opened_at?.toISOString() ?? null,+ rootId: entryInteraction.root_id,+ workspaceId: entryInteraction.workspace_id,+ version: entryInteraction.version.toString(),+ })+ );++ return {+ type: 'synchronizer_output',+ userId: this.user.userId,+ id: this.id,+ items: items.map((item) => ({+ cursor: item.version,+ data: item,+ })),+ };+ }++ private shouldFetch(event: Event) {+ if (+ event.type === 'entry_interaction_updated' &&+ event.rootId === this.input.rootId+ ) {+ return true;+ }++ return false;+ }+}diff --git a/apps/server/src/synchronizers/file-interactions.ts b/apps/server/src/synchronizers/file-interactions.tsnew file mode 100644index 00000000..031d865d--- /dev/null+++ b/apps/server/src/synchronizers/file-interactions.ts@@ -0,0 +1,94 @@+import {+ SynchronizerOutputMessage,+ SyncFileInteractionsInput,+ SyncFileInteractionData,+} from '@colanode/core';++import { BaseSynchronizer } from '@/synchronizers/base';+import { Event } from '@/types/events';+import { database } from '@/data/database';+import { SelectFileInteraction } from '@/data/schema';++export class FileInteractionSynchronizer extends BaseSynchronizer<SyncFileInteractionsInput> {+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncFileInteractionsInput> | null> {+ const fileInteractions = await this.fetchFileInteractions();+ if (fileInteractions.length === 0) {+ return null;+ }++ return this.buildMessage(fileInteractions);+ }++ public async fetchDataFromEvent(+ event: Event+ ): Promise<SynchronizerOutputMessage<SyncFileInteractionsInput> | null> {+ if (!this.shouldFetch(event)) {+ return null;+ }++ const fileInteractions = await this.fetchFileInteractions();+ if (fileInteractions.length === 0) {+ return null;+ }++ return this.buildMessage(fileInteractions);+ }++ private async fetchFileInteractions() {+ if (this.status === 'fetching') {+ return [];+ }++ this.status = 'fetching';+ const fileInteractions = await database+ .selectFrom('file_interactions')+ .selectAll()+ .where('root_id', '=', this.input.rootId)+ .where('version', '>', this.cursor)+ .orderBy('version', 'asc')+ .limit(20)+ .execute();++ this.status = 'pending';+ return fileInteractions;+ }++ private buildMessage(+ unsyncedFileInteractions: SelectFileInteraction[]+ ): SynchronizerOutputMessage<SyncFileInteractionsInput> {+ const items: SyncFileInteractionData[] = unsyncedFileInteractions.map(+ (fileInteraction) => ({+ fileId: fileInteraction.file_id,+ collaboratorId: fileInteraction.collaborator_id,+ firstSeenAt: fileInteraction.first_seen_at?.toISOString() ?? null,+ lastSeenAt: fileInteraction.last_seen_at?.toISOString() ?? null,+ firstOpenedAt: fileInteraction.first_opened_at?.toISOString() ?? null,+ lastOpenedAt: fileInteraction.last_opened_at?.toISOString() ?? null,+ rootId: fileInteraction.root_id,+ workspaceId: fileInteraction.workspace_id,+ version: fileInteraction.version.toString(),+ })+ );++ return {+ type: 'synchronizer_output',+ userId: this.user.userId,+ id: this.id,+ items: items.map((item) => ({+ cursor: item.version,+ data: item,+ })),+ };+ }++ private shouldFetch(event: Event) {+ if (+ event.type === 'file_interaction_updated' &&+ event.rootId === this.input.rootId+ ) {+ return true;+ }++ return false;+ }+}diff --git a/apps/server/src/synchronizers/message-interactions.ts b/apps/server/src/synchronizers/message-interactions.tsnew file mode 100644index 00000000..99881863--- /dev/null+++ b/apps/server/src/synchronizers/message-interactions.ts@@ -0,0 +1,94 @@+import {+ SynchronizerOutputMessage,+ SyncMessageInteractionsInput,+ SyncMessageInteractionData,+} from '@colanode/core';++import { BaseSynchronizer } from '@/synchronizers/base';+import { Event } from '@/types/events';+import { database } from '@/data/database';+import { SelectMessageInteraction } from '@/data/schema';++export class MessageInteractionSynchronizer extends BaseSynchronizer<SyncMessageInteractionsInput> {+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncMessageInteractionsInput> | null> {+ const messageInteractions = await this.fetchMessageInteractions();+ if (messageInteractions.length === 0) {+ return null;+ }++ return this.buildMessage(messageInteractions);+ }++ public async fetchDataFromEvent(+ event: Event+ ): Promise<SynchronizerOutputMessage<SyncMessageInteractionsInput> | null> {+ if (!this.shouldFetch(event)) {+ return null;+ }++ const messageInteractions = await this.fetchMessageInteractions();+ if (messageInteractions.length === 0) {+ return null;+ }++ return this.buildMessage(messageInteractions);+ }++ private async fetchMessageInteractions() {+ if (this.status === 'fetching') {+ return [];+ }++ this.status = 'fetching';+ const messageInteractions = await database+ .selectFrom('message_interactions')+ .selectAll()+ .where('root_id', '=', this.input.rootId)+ .where('version', '>', this.cursor)+ .orderBy('version', 'asc')+ .limit(20)+ .execute();++ this.status = 'pending';+ return messageInteractions;+ }++ private buildMessage(+ unsyncedMessageInteractions: SelectMessageInteraction[]+ ): SynchronizerOutputMessage<SyncMessageInteractionsInput> {+ const items: SyncMessageInteractionData[] = unsyncedMessageInteractions.map(+ (messageInteraction) => ({+ messageId: messageInteraction.message_id,+ collaboratorId: messageInteraction.collaborator_id,+ seenAt: messageInteraction.seen_at?.toISOString() ?? null,+ firstOpenedAt:+ messageInteraction.first_opened_at?.toISOString() ?? null,+ lastOpenedAt: messageInteraction.last_opened_at?.toISOString() ?? null,+ rootId: messageInteraction.root_id,+ workspaceId: messageInteraction.workspace_id,+ version: messageInteraction.version.toString(),+ })+ );++ return {+ type: 'synchronizer_output',+ userId: this.user.userId,+ id: this.id,+ items: items.map((item) => ({+ cursor: item.version,+ data: item,+ })),+ };+ }++ private shouldFetch(event: Event) {+ if (+ event.type === 'message_interaction_updated' &&+ event.rootId === this.input.rootId+ ) {+ return true;+ }++ return false;+ }+}diff --git a/apps/server/src/types/events.ts b/apps/server/src/types/events.tsindex f52b758a..a7b33a60 100644--- a/apps/server/src/types/events.ts+++ b/apps/server/src/types/events.ts@@ -24,6 +24,14 @@ export type EntryDeletedEvent = {workspaceId: string;};+export type EntryInteractionUpdatedEvent = {+ type: 'entry_interaction_updated';+ entryId: string;+ collaboratorId: string;+ rootId: string;+ workspaceId: string;+};+export type MessageCreatedEvent = {type: 'message_created';messageId: string;@@ -61,6 +69,14 @@ export type MessageReactionDeletedEvent = {workspaceId: string;};+export type MessageInteractionUpdatedEvent = {+ type: 'message_interaction_updated';+ messageId: string;+ collaboratorId: string;+ rootId: string;+ workspaceId: string;+};+export type CollaborationCreatedEvent = {type: 'collaboration_created';collaboratorId: string;@@ -96,10 +112,10 @@ export type FileDeletedEvent = {workspaceId: string;};-export type InteractionUpdatedEvent = {- type: 'interaction_updated';- userId: string;- entryId: string;+export type FileInteractionUpdatedEvent = {+ type: 'file_interaction_updated';+ fileId: string;+ collaboratorId: string;rootId: string;workspaceId: string;};@@ -150,7 +166,7 @@ export type Event =| EntryDeletedEvent| CollaborationCreatedEvent| CollaborationUpdatedEvent- | InteractionUpdatedEvent+ | EntryInteractionUpdatedEvent| UserCreatedEvent| UserUpdatedEvent| AccountUpdatedEvent@@ -161,8 +177,10 @@ export type Event =| FileCreatedEvent| FileUpdatedEvent| FileDeletedEvent+ | FileInteractionUpdatedEvent| MessageCreatedEvent| MessageUpdatedEvent| MessageDeletedEvent| MessageReactionCreatedEvent- | MessageReactionDeletedEvent;+ | MessageReactionDeletedEvent+ | MessageInteractionUpdatedEvent;diff --git a/packages/core/src/synchronizers/entry-interactions.ts b/packages/core/src/synchronizers/entry-interactions.tsnew file mode 100644index 00000000..37de7b44--- /dev/null+++ b/packages/core/src/synchronizers/entry-interactions.ts@@ -0,0 +1,25 @@+export type SyncEntryInteractionsInput = {+ type: 'entry_interactions';+ rootId: string;+};++export type SyncEntryInteractionData = {+ entryId: string;+ collaboratorId: string;+ firstSeenAt: string | null;+ lastSeenAt: string | null;+ firstOpenedAt: string | null;+ lastOpenedAt: string | null;+ rootId: string;+ workspaceId: string;+ version: string;+};++declare module '@colanode/core' {+ interface SynchronizerMap {+ entry_interactions: {+ input: SyncEntryInteractionsInput;+ data: SyncEntryInteractionData;+ };+ }+}diff --git a/packages/core/src/synchronizers/file-interactions.ts b/packages/core/src/synchronizers/file-interactions.tsnew file mode 100644index 00000000..4bb69cc4--- /dev/null+++ b/packages/core/src/synchronizers/file-interactions.ts@@ -0,0 +1,25 @@+export type SyncFileInteractionsInput = {+ type: 'file_interactions';+ rootId: string;+};++export type SyncFileInteractionData = {+ fileId: string;+ collaboratorId: string;+ firstSeenAt: string | null;+ lastSeenAt: string | null;+ firstOpenedAt: string | null;+ lastOpenedAt: string | null;+ rootId: string;+ workspaceId: string;+ version: string;+};++declare module '@colanode/core' {+ interface SynchronizerMap {+ file_interactions: {+ input: SyncFileInteractionsInput;+ data: SyncFileInteractionData;+ };+ }+}diff --git a/packages/core/src/synchronizers/index.ts b/packages/core/src/synchronizers/index.tsindex 9233402a..ef13ec1c 100644--- a/packages/core/src/synchronizers/index.ts+++ b/packages/core/src/synchronizers/index.ts@@ -3,6 +3,9 @@ export * from './transactions';export * from './users';export * from './files';export * from './message-reactions';+export * from './message-interactions';+export * from './file-interactions';+export * from './entry-interactions';export * from './collaborations';// eslint-disable-next-line @typescript-eslint/no-empty-object-typediff --git a/packages/core/src/synchronizers/message-interactions.ts b/packages/core/src/synchronizers/message-interactions.tsnew file mode 100644index 00000000..56ac9c40--- /dev/null+++ b/packages/core/src/synchronizers/message-interactions.ts@@ -0,0 +1,24 @@+export type SyncMessageInteractionsInput = {+ type: 'message_interactions';+ rootId: string;+};++export type SyncMessageInteractionData = {+ messageId: string;+ collaboratorId: string;+ seenAt: string | null;+ firstOpenedAt: string | null;+ lastOpenedAt: string | null;+ rootId: string;+ workspaceId: string;+ version: string;+};++declare module '@colanode/core' {+ interface SynchronizerMap {+ message_interactions: {+ input: SyncMessageInteractionsInput;+ data: SyncMessageInteractionData;+ };+ }+}diff --git a/packages/core/src/types/mutations.ts b/packages/core/src/types/mutations.tsindex 72c7bcf7..ba353f95 100644--- a/packages/core/src/types/mutations.ts+++ b/packages/core/src/types/mutations.ts@@ -87,6 +87,17 @@ export type CreateMessageReactionMutation = MutationBase & {data: CreateMessageReactionMutationData;};+export type MarkMessageSeenMutationData = {+ messageId: string;+ collaboratorId: string;+ seenAt: string;+};++export type MarkMessageSeenMutation = MutationBase & {+ type: 'mark_message_seen';+ data: MarkMessageSeenMutationData;+};+export type DeleteMessageReactionMutationData = {messageId: string;reaction: string;@@ -99,6 +110,50 @@ export type DeleteMessageReactionMutation = MutationBase & {data: DeleteMessageReactionMutationData;};+export type MarkFileSeenMutationData = {+ fileId: string;+ collaboratorId: string;+ seenAt: string;+};++export type MarkFileSeenMutation = MutationBase & {+ type: 'mark_file_seen';+ data: MarkFileSeenMutationData;+};++export type MarkFileOpenedMutationData = {+ fileId: string;+ collaboratorId: string;+ openedAt: string;+};++export type MarkFileOpenedMutation = MutationBase & {+ type: 'mark_file_opened';+ data: MarkFileOpenedMutationData;+};++export type MarkEntrySeenMutationData = {+ entryId: string;+ collaboratorId: string;+ seenAt: string;+};++export type MarkEntrySeenMutation = MutationBase & {+ type: 'mark_entry_seen';+ data: MarkEntrySeenMutationData;+};++export type MarkEntryOpenedMutationData = {+ entryId: string;+ collaboratorId: string;+ openedAt: string;+};++export type MarkEntryOpenedMutation = MutationBase & {+ type: 'mark_entry_opened';+ data: MarkEntryOpenedMutationData;+};+export type Mutation =| CreateFileMutation| ApplyCreateTransactionMutation@@ -106,6 +161,11 @@ export type Mutation =| ApplyDeleteTransactionMutation| CreateMessageMutation| CreateMessageReactionMutation- | DeleteMessageReactionMutation;+ | DeleteMessageReactionMutation+ | MarkMessageSeenMutation+ | MarkFileSeenMutation+ | MarkFileOpenedMutation+ | MarkEntrySeenMutation+ | MarkEntryOpenedMutation;export type MutationType = Mutation['type'];