cf-mini-chat 0.1.25

Mini-chat module: multi-tenant AI chat
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
use std::sync::Arc;

use modkit_security::AccessScope;
use uuid::Uuid;

use crate::domain::error::DomainError;
use crate::domain::models::{NewChat, ReactionKind};

use crate::domain::repos::{
    InsertAssistantMessageParams, InsertUserMessageParams, MessageRepository as MessageRepoTrait,
};
use crate::domain::service::test_helpers::{
    MockThreadSummaryRepo, NoopOutboxEnqueuer, inmem_db, mock_db_provider, mock_enforcer,
    mock_model_resolver, mock_tenant_only_enforcer, mock_thread_summary_repo, test_security_ctx,
    test_security_ctx_with_id,
};
use crate::infra::db::repo::attachment_repo::AttachmentRepository as OrmAttachmentRepository;
use crate::infra::db::repo::chat_repo::ChatRepository as OrmChatRepository;
use crate::infra::db::repo::message_repo::MessageRepository as OrmMessageRepository;
use crate::infra::db::repo::reaction_repo::ReactionRepository as OrmReactionRepository;

use super::ReactionService;
use crate::domain::service::ChatService;

// ── Test Helpers ──

fn limit_cfg() -> modkit_db::odata::LimitCfg {
    modkit_db::odata::LimitCfg {
        default: 20,
        max: 100,
    }
}

fn build_chat_service(
    db_provider: Arc<crate::domain::service::DbProvider>,
    chat_repo: Arc<OrmChatRepository>,
) -> ChatService<OrmChatRepository, OrmAttachmentRepository, MockThreadSummaryRepo> {
    ChatService::new(
        db_provider,
        chat_repo,
        Arc::new(OrmAttachmentRepository),
        mock_thread_summary_repo(),
        Arc::new(NoopOutboxEnqueuer),
        mock_enforcer(),
        mock_model_resolver(),
    )
}

fn build_reaction_service(
    db_provider: Arc<crate::domain::service::DbProvider>,
    chat_repo: Arc<OrmChatRepository>,
) -> ReactionService<OrmReactionRepository, OrmMessageRepository, OrmChatRepository> {
    let reaction_repo = Arc::new(OrmReactionRepository);
    let message_repo = Arc::new(OrmMessageRepository::new(limit_cfg()));
    ReactionService::new(
        db_provider,
        reaction_repo,
        message_repo,
        chat_repo,
        mock_enforcer(),
    )
}

fn build_reaction_service_tenant_only_authz(
    db_provider: Arc<crate::domain::service::DbProvider>,
    chat_repo: Arc<OrmChatRepository>,
) -> ReactionService<OrmReactionRepository, OrmMessageRepository, OrmChatRepository> {
    let reaction_repo = Arc::new(OrmReactionRepository);
    let message_repo = Arc::new(OrmMessageRepository::new(limit_cfg()));
    ReactionService::new(
        db_provider,
        reaction_repo,
        message_repo,
        chat_repo,
        mock_tenant_only_enforcer(),
    )
}

/// Create a chat and insert a user + assistant message pair.
/// Returns `(chat_id, user_msg_id, assistant_msg_id)`.
async fn setup_chat_with_messages(
    db_provider: &Arc<crate::domain::service::DbProvider>,
    chat_repo: &Arc<OrmChatRepository>,
    ctx: &modkit_security::SecurityContext,
    tenant_id: Uuid,
) -> (Uuid, Uuid, Uuid) {
    let chat_svc = build_chat_service(Arc::clone(db_provider), Arc::clone(chat_repo));

    let chat = chat_svc
        .create_chat(
            ctx,
            NewChat {
                model: None,
                title: Some("Test chat".to_owned()),
                is_temporary: false,
            },
        )
        .await
        .expect("create_chat failed");

    let scope = AccessScope::for_tenant(tenant_id);
    let conn = db_provider.conn().expect("conn failed");
    let message_repo = OrmMessageRepository::new(limit_cfg());
    let request_id = Uuid::new_v4();

    let user_msg_id = Uuid::now_v7();
    message_repo
        .insert_user_message(
            &conn,
            &scope,
            InsertUserMessageParams {
                id: user_msg_id,
                tenant_id,
                chat_id: chat.id,
                request_id,
                content: "Hello".to_owned(),
            },
        )
        .await
        .expect("insert_user_message failed");

    let assistant_msg_id = Uuid::now_v7();
    message_repo
        .insert_assistant_message(
            &conn,
            &scope,
            InsertAssistantMessageParams {
                id: assistant_msg_id,
                tenant_id,
                chat_id: chat.id,
                request_id,
                content: "Hi there!".to_owned(),
                input_tokens: Some(10),
                output_tokens: Some(20),
                cache_read_input_tokens: None,
                cache_write_input_tokens: None,
                reasoning_tokens: None,
                model: Some("gpt-5.2".to_owned()),
                provider_response_id: None,
            },
        )
        .await
        .expect("insert_assistant_message failed");

    (chat.id, user_msg_id, assistant_msg_id)
}

// ── Tests ──

#[tokio::test]
async fn set_reaction_on_assistant_message() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx, tenant_id).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    let reaction = reaction_svc
        .set_reaction(&ctx, chat_id, assistant_msg_id, "like")
        .await
        .expect("set_reaction failed");

    assert_eq!(reaction.message_id, assistant_msg_id);
    assert_eq!(reaction.kind, ReactionKind::Like);
}

#[tokio::test]
async fn set_reaction_on_user_message_rejected() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let (chat_id, user_msg_id, _assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx, tenant_id).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    let result = reaction_svc
        .set_reaction(&ctx, chat_id, user_msg_id, "like")
        .await;

    assert!(result.is_err(), "Should reject reaction on user message");
    assert!(
        matches!(
            result.unwrap_err(),
            DomainError::InvalidReactionTarget { .. }
        ),
        "Expected InvalidReactionTarget"
    );
}

#[tokio::test]
async fn set_reaction_upsert_replaces() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx, tenant_id).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    // First: set "like"
    let r1 = reaction_svc
        .set_reaction(&ctx, chat_id, assistant_msg_id, "like")
        .await
        .expect("set_reaction like failed");
    assert_eq!(r1.kind, ReactionKind::Like);

    // Second: set "dislike" — should replace
    let r2 = reaction_svc
        .set_reaction(&ctx, chat_id, assistant_msg_id, "dislike")
        .await
        .expect("set_reaction dislike failed");
    assert_eq!(r2.kind, ReactionKind::Dislike);
}

#[tokio::test]
async fn set_reaction_invalid_value_rejected() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx, tenant_id).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    let result = reaction_svc
        .set_reaction(&ctx, chat_id, assistant_msg_id, "love")
        .await;

    assert!(result.is_err(), "Should reject invalid reaction value");
    assert!(
        matches!(result.unwrap_err(), DomainError::Validation { .. }),
        "Expected Validation error"
    );
}

#[tokio::test]
async fn delete_reaction_happy_path() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx, tenant_id).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    // Set reaction first
    reaction_svc
        .set_reaction(&ctx, chat_id, assistant_msg_id, "like")
        .await
        .expect("set_reaction failed");

    // Delete reaction
    reaction_svc
        .delete_reaction(&ctx, chat_id, assistant_msg_id)
        .await
        .expect("delete_reaction failed");
}

#[tokio::test]
async fn delete_reaction_idempotent() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx, tenant_id).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    // Delete without prior reaction — should still succeed
    reaction_svc
        .delete_reaction(&ctx, chat_id, assistant_msg_id)
        .await
        .expect("delete_reaction should be idempotent");
}

#[tokio::test]
async fn set_reaction_chat_not_found() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let reaction_svc = build_reaction_service(db_provider, chat_repo);

    let ctx = test_security_ctx(Uuid::new_v4());
    let random_chat_id = Uuid::new_v4();
    let random_msg_id = Uuid::new_v4();

    let result = reaction_svc
        .set_reaction(&ctx, random_chat_id, random_msg_id, "like")
        .await;

    assert!(result.is_err(), "Expected error for non-existent chat");
    assert!(
        matches!(result.unwrap_err(), DomainError::ChatNotFound { .. }),
        "Expected ChatNotFound"
    );
}

#[tokio::test]
async fn set_reaction_message_not_found() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let ctx = test_security_ctx(tenant_id);

    let chat_svc = build_chat_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));
    let chat = chat_svc
        .create_chat(
            &ctx,
            NewChat {
                model: None,
                title: Some("Test chat".to_owned()),
                is_temporary: false,
            },
        )
        .await
        .expect("create_chat failed");

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    let random_msg_id = Uuid::new_v4();
    let result = reaction_svc
        .set_reaction(&ctx, chat.id, random_msg_id, "like")
        .await;

    assert!(result.is_err(), "Expected error for non-existent message");
    assert!(
        matches!(result.unwrap_err(), DomainError::MessageNotFound { .. }),
        "Expected MessageNotFound"
    );
}

#[tokio::test]
async fn set_reaction_cross_tenant_rejected() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_a = Uuid::new_v4();
    let tenant_b = Uuid::new_v4();
    let ctx_a = test_security_ctx(tenant_a);
    let ctx_b = test_security_ctx(tenant_b);

    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx_a, tenant_a).await;

    let reaction_svc = build_reaction_service(Arc::clone(&db_provider), Arc::clone(&chat_repo));

    // Tenant B tries to react to Tenant A's chat message
    let result = reaction_svc
        .set_reaction(&ctx_b, chat_id, assistant_msg_id, "like")
        .await;

    assert!(result.is_err(), "Cross-tenant reaction must fail");
    assert!(
        matches!(result.unwrap_err(), DomainError::ChatNotFound { .. }),
        "Expected ChatNotFound for cross-tenant access"
    );
}

// ── Tenant-only AuthZ: user isolation via ensure_owner ──

#[tokio::test]
async fn set_reaction_tenant_only_authz_cross_owner_not_found() {
    let db = inmem_db().await;
    let db_provider = mock_db_provider(db);
    let chat_repo = Arc::new(OrmChatRepository::new(limit_cfg()));

    let tenant_id = Uuid::new_v4();
    let user_a = Uuid::new_v4();
    let user_b = Uuid::new_v4();
    let ctx_a = test_security_ctx_with_id(tenant_id, user_a);
    let ctx_b = test_security_ctx_with_id(tenant_id, user_b);

    // User A creates a chat with messages (using permissive enforcer for setup)
    let (chat_id, _user_msg_id, assistant_msg_id) =
        setup_chat_with_messages(&db_provider, &chat_repo, &ctx_a, tenant_id).await;

    // User B (same tenant) tries to react via tenant-only enforcer
    let reaction_svc =
        build_reaction_service_tenant_only_authz(Arc::clone(&db_provider), Arc::clone(&chat_repo));
    let result = reaction_svc
        .set_reaction(&ctx_b, chat_id, assistant_msg_id, "like")
        .await;

    assert!(
        result.is_err(),
        "Cross-owner reaction must fail with tenant-only authz"
    );
    assert!(
        matches!(result.unwrap_err(), DomainError::ChatNotFound { .. }),
        "Expected ChatNotFound for cross-owner access with tenant-only authz"
    );
}