forge
Explore
Log in

Don't you dare go Hollow

Rename thread/message off the mail collision

Browse files at this commit

92b232bc938c3a8a21efb7b07bb8f529db6a4983Ahmet Kaan GümüşParent: fff77ce
  • style
    • rename thread/message off the mail collision
Show full message
🎨 style(chatbot): rename thread/message off the mail collision

The AI chatbot's storage and web layer reused "conversation" and
"chat_message", the latter one underscore away from the human-to-human
mail `message` feature — every reader had to disambiguate two unrelated
tables by eye.

Rename the whole chatbot feature to a `chatbot_*` vocabulary:

  conversation  -> chatbot_thread    (ChatbotThread*, CHATBOT_THREAD_*)
  chat_message  -> chatbot_message   (ChatbotMessage*, CHATBOT_MESSAGE_*)
  /chat/conversations -> /chatbot/threads
  max_chat_conversations -> max_chatbot_threads
  max_chat_message_len   -> max_chatbot_message_len
  chat_history_turns     -> chatbot_history_turns
  RATE_LIMIT_CHAT_PER_MINUTE -> RATE_LIMIT_CHATBOT_PER_MINUTE
  DTO conversation_id -> thread_id

The out-of-process AI-service wire contract is deliberately untouched:
ai/chat.rs payload types, AI_CHAT_CAPABILITY ("chat.reply"), the serde
field names and the hab/1 ALPN stay as-is — other-language services
match on those literals. ai/chat.rs remains "the chat.reply payloads",
a separate concern from the chatbot feature it feeds.

Clean break, no row migration (pre-customer, FE not yet synced): old
conversation/chat_message rows in the volume are abandoned. Frontend
must adopt the new routes, the thread_id field, and the renamed
settings keys.
.env.examplemodified+1 -1
@@ -35,7 +35,7 @@ RUST_LOG=info,hezarfen_backend=debug
3535 # Chatbot messages per minute, per USER (not per IP) — the tier that rations
3636 # the AI service, so a shared-IP classroom can't spend one student's budget on
3737 # another's. 0 disables it, like the tiers above.
38-# RATE_LIMIT_CHAT_PER_MINUTE=20
38+# RATE_LIMIT_CHATBOT_PER_MINUTE=20
3939
4040 # Key rate limits by the rightmost X-Forwarded-For entry instead of the TCP
4141 # peer address. Enable ONLY behind a reverse proxy that appends the client IP
README.mdmodified+34 -34
@@ -95,7 +95,7 @@ stream on that one connection — no correlation ids, no head-of-line blocking.
9595 The bridge's certificate is published at `GET /ai/certificate` so a service can
9696 pin it before dialling (see "AI bridge (QUIC)").
9797 The first thing riding that bridge is the **chatbot**: every signed-in user
98-(`parent` included) keeps private conversations with an AI service, free-form —
98+(`parent` included) keeps private threads with an AI service, free-form —
9999 no rule tables, no canned answers, the backend only owns auth, limits,
100100 persistence and the payload format. Sending is asynchronous because an
101101 inference outlives a request: the turn plus an empty `pending` answer are
@@ -234,7 +234,7 @@ a `Retry-After` header (seconds). Set a limit to `0` to disable that tier —
234234 useful for load tests.
235235
236236 Sending a chatbot message adds a third tier, and it is keyed by **user id**,
237-not by IP (`RATE_LIMIT_CHAT_PER_MINUTE`, default 20), because an inference
237+not by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference
238238 costs the school real money and a shared-IP classroom must not spend one
239239 student's budget on another's. `0` disables it like the other two. It is
240240 charged before anything is written, so a `429` leaves no trace (see
@@ -576,21 +576,21 @@ their existing shapes: the student exam-room reads
576576 | GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` |
577577 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
578578 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |
579-| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chat_history_turns`, `max_chat_conversations`, `max_chat_message_len` |
579+| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes`, `chatbot_history_turns`, `max_chatbot_threads`, `max_chatbot_message_len` |
580580 | PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `400` on "Invalid lists, bands, file limit, or chat limits"; `409` when a removed exam kind still has graded exams (see "Per-school policy") |
581581 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
582582 | GET | `/terms` | student | List terms, newest first · paged |
583583 | GET | `/terms/{id}` | student | Get one term |
584584 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |
585585 | DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course still links to it |
586-| POST | `/chat/conversations` | student | `{title?}` — start a chatbot conversation (every role incl. `parent`, always private to its owner); `409` at `max_chat_conversations` |
587-| GET | `/chat/conversations` | student | The caller's conversations, newest activity first · paged |
588-| PATCH | `/chat/conversations/{id}` | student | `{title}` — rename own conversation (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |
589-| DELETE | `/chat/conversations/{id}` | student | Delete own conversation and every message in it (someone else's is a `404`, never a `403`) |
590-| GET | `/chat/conversations/{id}/messages` | student | The conversation's turns, oldest first — user and assistant rows alike · paged |
591-| POST | `/chat/conversations/{id}/messages` | student | `{content}` (≤ `max_chat_message_len`) — send a turn; `202 {message_id, status: "pending"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` — nothing is written; `429` + `Retry-After` on the send tier) |
592-| GET | `/chat/conversations/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |
593-| GET | `/chat/conversations/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` — or one `error` — and close; an already-finished answer replays (see "Chatbot") |
586+| POST | `/chatbot/threads` | student | `{title?}` — start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |
587+| GET | `/chatbot/threads` | student | The caller's threads, newest activity first · paged |
588+| PATCH | `/chatbot/threads/{id}` | student | `{title}` — rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread |
589+| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) |
590+| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first — user and assistant rows alike · paged |
591+| POST | `/chatbot/threads/{id}/messages` | student | `{content}` (≤ `max_chatbot_message_len`) — send a turn; `202 {message_id, status: "pending"}`, the answer is fetched after (`503` when no AI service offers `chat.reply` — nothing is written; `429` + `Retry-After` on the send tier) |
592+| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |
593+| GET | `/chatbot/threads/{id}/messages/{mid}/stream` | student | **SSE** on the same row: `delta` chunks then one `done` — or one `error` — and close; an already-finished answer replays (see "Chatbot") |
594594
595595 `status` must be one of the school's attendance statuses (`GET /settings`);
596596 the core four `present | absent | late | excused` always exist, plus whatever
@@ -904,16 +904,16 @@ editable `settings` singleton (`GET /settings` for any signed-in user,
904904 exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;
905905 a server hard cap — uploads buffer in memory), default `5242880` (5 MiB).
906906 Checked at upload time only: lowering it never touches already-stored files.
907-- **`chat_history_turns`** — how many prior **messages** of a conversation the
907+- **`chatbot_history_turns`** — how many prior **messages** of a thread the
908908 chatbot is given as context, `1`–`50` (default `10`). The unit is messages,
909909 not exchanges: a question and its answer are two, so the default remembers
910910 five question/answer pairs. Every one of them is re-sent on every reply, so
911911 the number is both what the bot remembers and what each answer costs.
912-- **`max_chat_conversations`** — how many chatbot conversations one user may
912+- **`max_chatbot_threads`** — how many chatbot threads one user may
913913 keep, `1`–`500` (default `50`); at the cap the user deletes an old one
914914 first. Storage protection, not a usage quota — that is the per-minute
915915 message limit.
916-- **`max_chat_message_len`** — character limit on one chat message,
916+- **`max_chatbot_message_len`** — character limit on one chat message,
917917 `100`–`8000` (default `4000`); the ceiling is a server hard cap, because
918918 the message and its history must fit one bridge frame.
919919
@@ -1564,18 +1564,18 @@ only as trustworthy as that HTTP hop. On an untrusted network set
15641564
15651565 ## Chatbot
15661566
1567-Every signed-in user — `parent` included — keeps private conversations with an
1567+Every signed-in user — `parent` included — keeps private threads with an
15681568 AI service. The backend is a **relay**: it owns auth, the limits, the thread,
15691569 the payload format, and the last look at the answer before anyone sees it; the
15701570 words are the service's. There are deliberately **no rule, intent or
1571-canned-answer tables** — the conversation is free-form, and a school that wants
1571+canned-answer tables** — the thread is free-form, and a school that wants
15721572 different behaviour changes its AI service, not this backend. A thread is
15731573 private to its owner: no teacher, no admin, nobody reads someone else's, and
1574-another user's conversation is a `404`, never a `403`.
1574+another user's thread is a `404`, never a `403`.
15751575
15761576 ### Sending is two-phase, and that is the point
15771577
1578-`POST /chat/conversations/{id}/messages` answers `202 {message_id, status:
1578+`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:
15791579 "pending"}` instead of the answer, because an inference outlives a normal
15801580 request (and the request-timeout layer that guards every handler). Before the
15811581 AI is even called, two rows are written: the user's turn, and an **empty
@@ -1586,9 +1586,9 @@ outlives the HTTP request.
15861586
15871587 The client then reads that row either way it likes:
15881588
1589-- **poll** `GET /chat/conversations/{id}/messages/{mid}` — `pending` until it
1589+- **poll** `GET /chatbot/threads/{id}/messages/{mid}` — `pending` until it
15901590 settles, then `complete` with `content` or `failed` with `error_code`;
1591-- **stream** `GET /chat/conversations/{id}/messages/{mid}/stream` — the same
1591+- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` — the same
15921592 row over Server-Sent Events.
15931593
15941594 Both read the same row, so they can never disagree, in any state.
@@ -1622,7 +1622,7 @@ unchanged frontend.
16221622 ### The message DTO
16231623
16241624 ```json
1625-{ "id": "01J8…", "conversation_id": "01J8…", "role": "assistant",
1625+{ "id": "01J8…", "thread_id": "01J8…", "role": "assistant",
16261626 "status": "complete", "content": "…", "truncated": false, "error_code": null,
16271627 "created_at": 1761820800000, "completed_at": 1761820803120 }
16281628 ```
@@ -1631,7 +1631,7 @@ unchanged frontend.
16311631 `failed` (a user turn is always `complete`). `content` is empty while pending,
16321632 `error_code` is set only when failed, `completed_at` is `null` until the turn
16331633 settles. `truncated` is `true` when `content` is only the first part of what
1634-the assistant answered — the rest was over `max_chat_message_len` and was cut;
1634+the assistant answered — the rest was over `max_chatbot_message_len` and was cut;
16351635 it is always `false` for a user turn and for a failed one. Show it: a clipped
16361636 answer that looks whole is worse than one the reader knows is clipped. The same
16371637 DTO is what the SSE `done` event carries, so the streaming and polling reads
@@ -1642,10 +1642,10 @@ agree about `truncated` exactly as they do about every other field.
16421642 | code | when |
16431643 | --- | --- |
16441644 | `202` | the turn was accepted; the answer is on its way |
1645-| `400` | empty message, or longer than the school's `max_chat_message_len` |
1646-| `404` | no such conversation or message — or not the caller's |
1647-| `409` | already at `max_chat_conversations`; delete a thread first |
1648-| `429` | over `RATE_LIMIT_CHAT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |
1645+| `400` | empty message, or longer than the school's `max_chatbot_message_len` |
1646+| `404` | no such thread or message — or not the caller's |
1647+| `409` | already at `max_chatbot_threads`; delete a thread first |
1648+| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |
16491649 | `503` | no connected service offers `chat.reply` — **nothing was written**, retry later |
16501650
16511651 The `503` ordering matters: the bridge is checked before the rows exist, so an
@@ -1666,7 +1666,7 @@ three independent mechanisms:
16661666
16671667 Two more verdicts come from inspecting the answer: an **empty** reply is
16681668 reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a
1669-bug), and an **over-long** one is truncated to `max_chat_message_len` — a
1669+bug), and an **over-long** one is truncated to `max_chatbot_message_len` — a
16701670 clipped answer still helps, a discarded one does not — with `truncated: true`
16711671 on the stored turn, so the clip is never passed off as the whole answer.
16721672
@@ -1689,14 +1689,14 @@ Requests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:
16891689 ```
16901690
16911691 `history` is **oldest first** (index 0 is furthest back), optional (absent or
1692-`[]` = a fresh conversation), and **excludes** the new message — that one is
1693-`message`. It carries the last `chat_history_turns` **settled messages** —
1692+`[]` = a fresh thread), and **excludes** the new message — that one is
1693+`message`. It carries the last `chatbot_history_turns` **settled messages** —
16941694 entries, not exchanges: the default `10` is five question/answer pairs, and
16951695 `history` is exactly that many entries long whenever the thread holds enough
16961696 of them. Only settled turns count: a failed answer is skipped and the window
16971697 reaches further back for a usable one, rather than coming up short. All of it
16981698 is re-sent on every request, which is why the service may be stateless: it can
1699-restart, scale out, or be replaced mid-conversation without losing context.
1699+restart, scale out, or be replaced mid-thread without losing context.
17001700
17011701 The answer is a `Response::Ok` whose payload is:
17021702
@@ -1770,10 +1770,10 @@ src/
17701770 subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum)
17711771 term.rs TermId · TermName · Term (school term window)
17721772 settings.rs ExamKindDef · GradeBand · Settings (per-school policy)
1773- conversation.rs ConversationId · ConversationTitle · Conversation (one
1773+ chatbot_thread.rs ChatbotThreadId · ChatbotThreadTitle · ChatbotThread (one
17741774 chatbot thread, private to its owner)
1775- chat_message.rs ChatMessageId · ChatContent · MessageRole · MessageStatus ·
1776- ChatMessage (one turn; the assistant row is written
1775+ chatbot_message.rs ChatbotMessageId · ChatContent · MessageRole · MessageStatus ·
1776+ ChatbotMessage (one turn; the assistant row is written
17771777 `pending` before the AI call and settled after)
17781778 appointment_slot.rs AppointmentSlotId · SlotSeries · SlotNote ·
17791779 AppointmentSlot (a teacher's published availability; a
@@ -1807,7 +1807,7 @@ src/
18071807 auth.rs users.rs notes.rs messages.rs events.rs appointments.rs
18081808 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
18091809 marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs
1810- ai.rs chat.rs
1810+ ai.rs chatbot.rs
18111811 ```
18121812
18131813 Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory
src/ai/mod.rsmodified+1 -1
@@ -18,7 +18,7 @@
1818 //! * [`tls`] — the listener's certificate
1919 //!
2020 //! The transport is generic; the features land on top of it. So far that is
21-//! the chatbot (`web::chat`), which routes on the `chat.reply` capability.
21+//! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability.
2222
2323 pub mod chat;
2424 pub mod error;
src/config.rsmodified+6 -6
@@ -10,7 +10,7 @@ pub const DEFAULT_API_RATE_LIMIT: u32 = 300;
1010 /// Default chatbot messages per minute *per user*. Sits far above a human
1111 /// typing while still blunting a scripted fan-out at the AI service behind the
1212 /// bridge — which is the cost this tier rations, not this process.
13-pub const DEFAULT_CHAT_RATE_LIMIT: u32 = 20;
13+pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20;
1414
1515 /// Runtime configuration, sourced from environment variables (see `.env.example`).
1616 #[derive(Clone, Debug)]
@@ -33,10 +33,10 @@ pub struct Config {
3333 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.
3434 pub rate_limit: RateLimitConfig,
3535 /// Chatbot messages one user may send per minute
36- /// (`RATE_LIMIT_CHAT_PER_MINUTE`). `0` disables the tier. Kept out of
36+ /// (`RATE_LIMIT_CHATBOT_PER_MINUTE`). `0` disables the tier. Kept out of
3737 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
3838 /// keyed by user and is enforced inside the handler.
39- pub chat_per_minute: u32,
39+ pub chatbot_per_minute: u32,
4040 /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are
4141 /// set, an admin account with these credentials is created at boot if the
4242 /// username doesn't exist yet. Blank values count as unset.
@@ -82,9 +82,9 @@ impl Config {
8282 ),
8383 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),
8484 },
85- chat_per_minute: parse_limit(
86- env::var("RATE_LIMIT_CHAT_PER_MINUTE").ok(),
87- DEFAULT_CHAT_RATE_LIMIT,
85+ chatbot_per_minute: parse_limit(
86+ env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(),
87+ DEFAULT_CHATBOT_RATE_LIMIT,
8888 ),
8989 admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()),
9090 admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()),
src/constant.rsmodified+17 -17
@@ -291,31 +291,31 @@ pub const AI_CHAT_CAPABILITY: &str = "chat.reply";
291291 /// Hard ceiling on one chat message's characters — the newtype bound, above
292292 /// which no school setting can reach. Sized for a pasted question with its
293293 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.
294-pub const MAX_CHAT_MESSAGE_LEN: usize = 8_000;
294+pub const MAX_CHATBOT_MESSAGE_LEN: usize = 8_000;
295295
296-/// The school-adjustable per-message character cap (`max_chat_message_len` in
296+/// The school-adjustable per-message character cap (`max_chatbot_message_len` in
297297 /// settings): its default and the inclusive range a manager may set. The
298-/// ceiling is [`MAX_CHAT_MESSAGE_LEN`] — a longer prompt costs the AI service
298+/// ceiling is [`MAX_CHATBOT_MESSAGE_LEN`] — a longer prompt costs the AI service
299299 /// context it needs for the history.
300-pub const DEFAULT_MAX_CHAT_MESSAGE_LEN: i64 = 4_000;
301-pub const MIN_MAX_CHAT_MESSAGE_LEN: i64 = 100;
302-pub const MAX_MAX_CHAT_MESSAGE_LEN: i64 = MAX_CHAT_MESSAGE_LEN as i64;
300+pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000;
301+pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100;
302+pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64;
303303
304-/// How many prior user/assistant turns of a conversation are replayed to the
305-/// AI service as context (`chat_history_turns` in settings): its default and
304+/// How many prior user/assistant turns of a thread are replayed to the
305+/// AI service as context (`chatbot_history_turns` in settings): its default and
306306 /// the inclusive range a manager may set. Every turn is re-sent on every
307307 /// request, so the ceiling bounds both the frame size and the inference cost.
308-pub const DEFAULT_CHAT_HISTORY_TURNS: i64 = 10;
309-pub const MIN_CHAT_HISTORY_TURNS: i64 = 1;
310-pub const MAX_CHAT_HISTORY_TURNS: i64 = 50;
308+pub const DEFAULT_CHATBOT_HISTORY_TURNS: i64 = 10;
309+pub const MIN_CHATBOT_HISTORY_TURNS: i64 = 1;
310+pub const MAX_CHATBOT_HISTORY_TURNS: i64 = 50;
311311
312-/// How many conversations one user may keep (`max_chat_conversations` in
312+/// How many threads one user may keep (`max_chatbot_threads` in
313313 /// settings): its default and the inclusive range a manager may set. Reached,
314-/// the user deletes an old conversation before starting a new one — the cap is
314+/// the user deletes an old thread before starting a new one — the cap is
315315 /// storage protection, not a usage quota.
316-pub const DEFAULT_MAX_CHAT_CONVERSATIONS: i64 = 50;
317-pub const MIN_MAX_CHAT_CONVERSATIONS: i64 = 1;
318-pub const MAX_MAX_CHAT_CONVERSATIONS: i64 = 500;
316+pub const DEFAULT_MAX_CHATBOT_THREADS: i64 = 50;
317+pub const MIN_MAX_CHATBOT_THREADS: i64 = 1;
318+pub const MAX_MAX_CHATBOT_THREADS: i64 = 500;
319319
320320 /// How often the chat stream re-reads a `pending` assistant message while it
321321 /// waits for the answer. The reply lands in the database from whichever task
@@ -327,7 +327,7 @@ pub const CHAT_STREAM_POLL_MS: u64 = 200;
327327 /// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may
328328 /// raise), because the answering task normally stamps the failure itself —
329329 /// this only catches the row whose task died with the process.
330-pub const CHAT_PENDING_STALE_SECS: i64 = 300;
330+pub const CHATBOT_PENDING_STALE_SECS: i64 = 300;
331331
332332 /// How long a dialling AI service has to complete its `Hello`/`Welcome`
333333 /// exchange before the connection is dropped. Short: the handshake is one
src/database.rsmodified+34 -34
@@ -54,8 +54,8 @@ pub const HOMEWORK_TABLE: &str = "homework";
5454 pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";
5555 pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
5656 pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
57-pub const CONVERSATION_TABLE: &str = "conversation";
58-pub const CHAT_MESSAGE_TABLE: &str = "chat_message";
57+pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread";
58+pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";
5959 pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
6060 pub const APPOINTMENT_TABLE: &str = "appointment";
6161
@@ -120,30 +120,30 @@ const MIGRATION: &str = "
120120 DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;
121121 DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;
122122
123- -- Chatbot relay (2026-07-23): a `conversation` groups the turns, one
124- -- `chat_message` is one turn. `user_id` rides on the message too so an
123+ -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
124+ -- `chatbot_message` is one turn. `user_id` rides on the message too so an
125125 -- ownership check needs no join. An assistant turn is born `pending` and
126126 -- is completed (or failed) by the task holding the AI-bridge stream —
127127 -- hence the BACKFILL sweep, since that task dies with the process.
128- DEFINE TABLE IF NOT EXISTS conversation SCHEMAFULL;
129- DEFINE FIELD IF NOT EXISTS user_id ON conversation TYPE record<user> READONLY;
130- DEFINE FIELD IF NOT EXISTS title ON conversation TYPE option<string>;
131- DEFINE FIELD IF NOT EXISTS created_at ON conversation TYPE int READONLY;
132- DEFINE FIELD IF NOT EXISTS updated_at ON conversation TYPE int;
133- DEFINE INDEX IF NOT EXISTS conversation_user_updated ON conversation FIELDS user_id, updated_at;
134-
135- DEFINE TABLE IF NOT EXISTS chat_message SCHEMAFULL;
136- DEFINE FIELD IF NOT EXISTS conversation_id ON chat_message TYPE record<conversation> READONLY;
137- DEFINE FIELD IF NOT EXISTS user_id ON chat_message TYPE record<user> READONLY;
138- DEFINE FIELD IF NOT EXISTS role ON chat_message TYPE string READONLY;
139- DEFINE FIELD IF NOT EXISTS content ON chat_message TYPE string;
140- DEFINE FIELD IF NOT EXISTS status ON chat_message TYPE string;
141- DEFINE FIELD IF NOT EXISTS truncated ON chat_message TYPE bool DEFAULT false;
142- DEFINE FIELD IF NOT EXISTS error_code ON chat_message TYPE option<string>;
143- DEFINE FIELD IF NOT EXISTS created_at ON chat_message TYPE int READONLY;
144- DEFINE FIELD IF NOT EXISTS completed_at ON chat_message TYPE option<int>;
145- DEFINE INDEX IF NOT EXISTS chat_message_conversation_created ON chat_message FIELDS conversation_id, created_at;
146- DEFINE INDEX IF NOT EXISTS chat_message_user ON chat_message FIELDS user_id;
128+ DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL;
129+ DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY;
130+ DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>;
131+ DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY;
132+ DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int;
133+ DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at;
134+
135+ DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL;
136+ DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record<chatbot_thread> READONLY;
137+ DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY;
138+ DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY;
139+ DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string;
140+ DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string;
141+ DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false;
142+ DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
143+ DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
144+ DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
145+ DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
146+ DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
147147
148148 DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
149149 DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
@@ -346,9 +346,9 @@ const MIGRATION: &str = "
346346 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
347347 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
348348 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;
349- DEFINE FIELD IF NOT EXISTS chat_history_turns ON settings TYPE option<int>;
350- DEFINE FIELD IF NOT EXISTS max_chat_conversations ON settings TYPE option<int>;
351- DEFINE FIELD IF NOT EXISTS max_chat_message_len ON settings TYPE option<int>;
349+ DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
350+ DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;
351+ DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
352352
353353 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
354354 -- submit files + optional text, a teacher grades a status + optional mark.
@@ -471,12 +471,12 @@ const BACKFILL: &str = "
471471 -- Turns written before the clipped-answer flag existed (2026-07-23): the
472472 -- clip was silent then, so nothing can be recovered — they read as whole,
473473 -- which is what they were presented as all along.
474- UPDATE chat_message SET truncated = false WHERE truncated = NONE;
474+ UPDATE chatbot_message SET truncated = false WHERE truncated = NONE;
475475
476476 -- An assistant turn is answered by an in-process task, so a restart leaves
477477 -- its row `pending` with nobody left to complete it: fail it at boot rather
478- -- than let a reader wait out `CHAT_PENDING_STALE_SECS` on every load.
479- UPDATE chat_message SET status = 'failed', error_code = 'interrupted',
478+ -- than let a reader wait out `CHATBOT_PENDING_STALE_SECS` on every load.
479+ UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
480480 completed_at = time::unix(time::now()) * 1000 WHERE status = 'pending';
481481
482482 -- Promotion out of student now deletes the user's enrollments (2026-07-18);
@@ -546,14 +546,14 @@ pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
546546 #[cfg(test)]
547547 mod tests {
548548 #[tokio::test]
549- async fn boot_fails_chat_messages_left_pending() {
549+ async fn boot_fails_chatbot_messages_left_pending() {
550550 let db = super::init_mem().await.unwrap();
551551 db.query(
552552 "CREATE user:u SET username = 'u', password_hash = 'x';
553- CREATE conversation:c SET user_id = user:u, created_at = 1, updated_at = 1;
554- CREATE chat_message:m SET conversation_id = conversation:c, user_id = user:u,
553+ CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1;
554+ CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
555555 role = 'assistant', content = '', status = 'pending', created_at = 1;
556- CREATE chat_message:done SET conversation_id = conversation:c, user_id = user:u,
556+ CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u,
557557 role = 'assistant', content = 'hi', status = 'complete', created_at = 1;",
558558 )
559559 .await
@@ -566,7 +566,7 @@ mod tests {
566566 super::migrate(&db).await.unwrap();
567567
568568 let mut rows = db
569- .query("SELECT id, status, error_code, completed_at FROM chat_message ORDER BY id")
569+ .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id")
570570 .await
571571 .unwrap();
572572 let rows: Vec<serde_json::Value> = rows.take(0).unwrap();
src/domain/chat_message.rs → src/domain/chatbot_message.rsrenamed+71 -71
@@ -5,7 +5,7 @@
55 //! a code) — and if that task dies with the process, the boot sweep in
66 //! `database.rs` fails the row instead.
77 //!
8-//! `user_id` is duplicated from the conversation onto every message so an
8+//! `user_id` is duplicated from the thread onto every message so an
99 //! ownership check is one read, with no join.
1010
1111 use std::sync::{LazyLock, Mutex};
@@ -13,9 +13,9 @@ use std::sync::{LazyLock, Mutex};
1313 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1414 use ulid::{Generator, Ulid};
1515
16-use crate::constant::{CHAT_PENDING_STALE_SECS, MAX_CHAT_MESSAGE_LEN};
16+use crate::constant::{CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN};
1717 use crate::database::{CHAT_MESSAGE_TABLE, Database};
18-use crate::domain::conversation::ConversationId;
18+use crate::domain::chatbot_thread::ChatbotThreadId;
1919 use crate::domain::timestamp::Timestamp;
2020 use crate::domain::user::UserId;
2121 use crate::error::{AppError, ValidationError};
@@ -33,7 +33,7 @@ const MAX_ERROR_CODE_LEN: usize = 64;
3333 /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random
3434 /// low bits sort arbitrarily among ids minted in the same millisecond, this
3535 /// increments the previous id — so the `id` tie-break in the `ORDER BY` of
36-/// [`ChatMessage::list_for_conversation`] / [`ChatMessage::list_tail`] is the
36+/// [`ChatbotMessage::list_for_thread`] / [`ChatbotMessage::list_tail`] is the
3737 /// order the rows were written. The user prompt and the assistant row one POST
3838 /// writes back-to-back routinely share a millisecond, and a random tie-break
3939 /// there renders the answer *above* its own question — and hands the AI
@@ -41,9 +41,9 @@ const MAX_ERROR_CODE_LEN: usize = 64;
4141 static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
4242
4343 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
44-pub struct ChatMessageId(RecordId);
44+pub struct ChatbotMessageId(RecordId);
4545
46-impl ChatMessageId {
46+impl ChatbotMessageId {
4747 pub fn generate() -> Self {
4848 let mut ids = IDS.lock().expect("chat id generator poisoned");
4949 // The only error is overflow of the random bits *within* one
@@ -115,13 +115,13 @@ impl MessageStatus {
115115 }
116116
117117 /// One turn's text. The hard ceiling only — the school-adjustable
118-/// `max_chat_message_len` is the web layer's to enforce, below this.
118+/// `max_chatbot_message_len` is the web layer's to enforce, below this.
119119 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
120120 pub struct ChatContent(String);
121121
122122 impl ChatContent {
123123 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
124- validate_required("content", value, MAX_CHAT_MESSAGE_LEN)?;
124+ validate_required("content", value, MAX_CHATBOT_MESSAGE_LEN)?;
125125 Ok(Self(value.to_string()))
126126 }
127127
@@ -137,9 +137,9 @@ impl ChatContent {
137137 }
138138
139139 #[derive(Debug, Clone, SurrealValue)]
140-pub struct ChatMessage {
141- id: ChatMessageId,
142- conversation_id: ConversationId,
140+pub struct ChatbotMessage {
141+ id: ChatbotMessageId,
142+ thread_id: ChatbotThreadId,
143143 user_id: UserId,
144144 role: MessageRole,
145145 content: ChatContent,
@@ -153,13 +153,13 @@ pub struct ChatMessage {
153153 completed_at: Option<Timestamp>,
154154 }
155155
156-impl ChatMessage {
157- pub fn get_id(&self) -> &ChatMessageId {
156+impl ChatbotMessage {
157+ pub fn get_id(&self) -> &ChatbotMessageId {
158158 &self.id
159159 }
160160
161- pub fn get_conversation_id(&self) -> &ConversationId {
162- &self.conversation_id
161+ pub fn get_thread_id(&self) -> &ChatbotThreadId {
162+ &self.thread_id
163163 }
164164
165165 pub fn get_user_id(&self) -> &UserId {
@@ -194,7 +194,7 @@ impl ChatMessage {
194194 self.completed_at
195195 }
196196
197- /// A row still `pending` past [`CHAT_PENDING_STALE_SECS`] has lost the task
197+ /// A row still `pending` past [`CHATBOT_PENDING_STALE_SECS`] has lost the task
198198 /// that owed it an answer; present it as failed.
199199 ///
200200 /// Read-time projection, not a lazy write-back: the read paths (poll loop,
@@ -204,7 +204,7 @@ impl ChatMessage {
204204 /// (a dead process) already happens once, at boot. The stored row stays
205205 /// truthful; only the answer handed to the caller is projected.
206206 fn projected(mut self) -> Self {
207- let stale_at = self.created_at.as_millis() + CHAT_PENDING_STALE_SECS * 1_000;
207+ let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000;
208208 if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at {
209209 self.status = MessageStatus::Failed;
210210 self.error_code = Some(STALE_ERROR_CODE.to_string());
@@ -212,24 +212,24 @@ impl ChatMessage {
212212 self
213213 }
214214
215- async fn insert(message: ChatMessage, db: &Database) -> Result<ChatMessage, AppError> {
216- let created: Option<ChatMessage> = db.create(message.id.record()).content(message).await?;
215+ async fn insert(message: ChatbotMessage, db: &Database) -> Result<ChatbotMessage, AppError> {
216+ let created: Option<ChatbotMessage> = db.create(message.id.record()).content(message).await?;
217217 created.ok_or_else(|| AppError::Internal("failed to create chat message".into()))
218218 }
219219
220220 /// Append the user's prompt. Nothing is awaited for it, so it is born
221221 /// complete.
222222 pub async fn append_user(
223- conversation: &ConversationId,
223+ thread: &ChatbotThreadId,
224224 user: &UserId,
225225 content: ChatContent,
226226 db: &Database,
227- ) -> Result<ChatMessage, AppError> {
227+ ) -> Result<ChatbotMessage, AppError> {
228228 let now = Timestamp::now();
229229 Self::insert(
230- ChatMessage {
231- id: ChatMessageId::generate(),
232- conversation_id: conversation.clone(),
230+ ChatbotMessage {
231+ id: ChatbotMessageId::generate(),
232+ thread_id: thread.clone(),
233233 user_id: user.clone(),
234234 role: MessageRole::User,
235235 content,
@@ -247,14 +247,14 @@ impl ChatMessage {
247247 /// Reserve the assistant's answer *before* the AI call: the row exists,
248248 /// empty and `pending`, so a reload finds the turn and can wait on it.
249249 pub async fn append_pending_assistant(
250- conversation: &ConversationId,
250+ thread: &ChatbotThreadId,
251251 user: &UserId,
252252 db: &Database,
253- ) -> Result<ChatMessage, AppError> {
253+ ) -> Result<ChatbotMessage, AppError> {
254254 Self::insert(
255- ChatMessage {
256- id: ChatMessageId::generate(),
257- conversation_id: conversation.clone(),
255+ ChatbotMessage {
256+ id: ChatbotMessageId::generate(),
257+ thread_id: thread.clone(),
258258 user_id: user.clone(),
259259 role: MessageRole::Assistant,
260260 content: ChatContent::empty(),
@@ -271,22 +271,22 @@ impl ChatMessage {
271271
272272 /// The whole thread, oldest first — the order both the UI and the AI
273273 /// history payload read in.
274- pub async fn list_for_conversation(
275- conversation: &ConversationId,
274+ pub async fn list_for_thread(
275+ thread: &ChatbotThreadId,
276276 db: &Database,
277- ) -> Result<Vec<ChatMessage>, AppError> {
277+ ) -> Result<Vec<ChatbotMessage>, AppError> {
278278 let mut result = db
279279 .query(
280- "SELECT * FROM chat_message WHERE conversation_id = $conv \
280+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
281281 ORDER BY created_at ASC, id ASC",
282282 )
283- .bind(("conv", conversation.record()))
283+ .bind(("conv", thread.record()))
284284 .await?
285285 .check()?;
286286 Ok(result
287- .take::<Vec<ChatMessage>>(0)?
287+ .take::<Vec<ChatbotMessage>>(0)?
288288 .into_iter()
289- .map(ChatMessage::projected)
289+ .map(ChatbotMessage::projected)
290290 .collect())
291291 }
292292
@@ -294,23 +294,23 @@ impl ChatMessage {
294294 /// AI service as context. Taken newest-first in the database (so the
295295 /// `LIMIT` keeps the *recent* end) and flipped back here.
296296 pub async fn list_tail(
297- conversation: &ConversationId,
297+ thread: &ChatbotThreadId,
298298 limit: usize,
299299 db: &Database,
300- ) -> Result<Vec<ChatMessage>, AppError> {
300+ ) -> Result<Vec<ChatbotMessage>, AppError> {
301301 let mut result = db
302302 .query(
303- "SELECT * FROM chat_message WHERE conversation_id = $conv \
303+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
304304 ORDER BY created_at DESC, id DESC LIMIT $limit",
305305 )
306- .bind(("conv", conversation.record()))
306+ .bind(("conv", thread.record()))
307307 .bind(("limit", limit as i64))
308308 .await?
309309 .check()?;
310- let mut messages: Vec<ChatMessage> = result
311- .take::<Vec<ChatMessage>>(0)?
310+ let mut messages: Vec<ChatbotMessage> = result
311+ .take::<Vec<ChatbotMessage>>(0)?
312312 .into_iter()
313- .map(ChatMessage::projected)
313+ .map(ChatbotMessage::projected)
314314 .collect();
315315 messages.reverse();
316316 Ok(messages)
@@ -323,35 +323,35 @@ impl ChatMessage {
323323 /// instead of reaching further back. No projection is applied — it only
324324 /// ever rewrites a `pending` row, and none is selected here.
325325 pub async fn list_settled_tail(
326- conversation: &ConversationId,
326+ thread: &ChatbotThreadId,
327327 limit: usize,
328328 db: &Database,
329- ) -> Result<Vec<ChatMessage>, AppError> {
329+ ) -> Result<Vec<ChatbotMessage>, AppError> {
330330 let mut result = db
331331 .query(
332- "SELECT * FROM chat_message WHERE conversation_id = $conv \
332+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
333333 AND status = 'complete' AND content != '' \
334334 ORDER BY created_at DESC, id DESC LIMIT $limit",
335335 )
336- .bind(("conv", conversation.record()))
336+ .bind(("conv", thread.record()))
337337 .bind(("limit", limit as i64))
338338 .await?
339339 .check()?;
340- let mut messages: Vec<ChatMessage> = result.take(0)?;
340+ let mut messages: Vec<ChatbotMessage> = result.take(0)?;
341341 messages.reverse();
342342 Ok(messages)
343343 }
344344
345345 /// Read one turn only if `user` owns it — the poll loop's read.
346346 pub async fn read_for(
347- id: &ChatMessageId,
347+ id: &ChatbotMessageId,
348348 user: &UserId,
349349 db: &Database,
350- ) -> Result<Option<ChatMessage>, AppError> {
351- let message: Option<ChatMessage> = db.select(id.record()).await?;
350+ ) -> Result<Option<ChatbotMessage>, AppError> {
351+ let message: Option<ChatbotMessage> = db.select(id.record()).await?;
352352 Ok(message
353353 .filter(|message| &message.user_id == user)
354- .map(ChatMessage::projected))
354+ .map(ChatbotMessage::projected))
355355 }
356356
357357 /// Land the answer, recording whether it had to be clipped to fit the
@@ -359,32 +359,32 @@ impl ChatMessage {
359359 /// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a
360360 /// timeout) already failed, and two answers can't both apply.
361361 pub async fn complete(
362- id: &ChatMessageId,
362+ id: &ChatbotMessageId,
363363 text: ChatContent,
364364 truncated: bool,
365365 db: &Database,
366- ) -> Result<ChatMessage, AppError> {
366+ ) -> Result<ChatbotMessage, AppError> {
367367 Self::settle(id, Some(text), truncated, None, db).await
368368 }
369369
370370 /// Mark the answer failed with a short code (`unavailable`, the service's
371- /// own error code, …). Same pending gate as [`ChatMessage::complete`].
371+ /// own error code, …). Same pending gate as [`ChatbotMessage::complete`].
372372 pub async fn fail(
373- id: &ChatMessageId,
373+ id: &ChatbotMessageId,
374374 error_code: &str,
375375 db: &Database,
376- ) -> Result<ChatMessage, AppError> {
376+ ) -> Result<ChatbotMessage, AppError> {
377377 // A failed turn has no text, so there is nothing that could be clipped.
378378 Self::settle(id, None, false, Some(error_code), db).await
379379 }
380380
381381 async fn settle(
382- id: &ChatMessageId,
382+ id: &ChatbotMessageId,
383383 text: Option<ChatContent>,
384384 truncated: bool,
385385 error_code: Option<&str>,
386386 db: &Database,
387- ) -> Result<ChatMessage, AppError> {
387+ ) -> Result<ChatbotMessage, AppError> {
388388 let status = if text.is_some() {
389389 MessageStatus::Complete
390390 } else {
@@ -407,7 +407,7 @@ impl ChatMessage {
407407 .await?
408408 .check()?;
409409 result
410- .take::<Vec<ChatMessage>>(0)?
410+ .take::<Vec<ChatbotMessage>>(0)?
411411 .into_iter()
412412 .next()
413413 .ok_or(AppError::NotFound)
@@ -422,8 +422,8 @@ mod tests {
422422 #[tokio::test]
423423 async fn content_is_required_and_capped() {
424424 assert!(ChatContent::try_new("").is_err());
425- assert!(ChatContent::try_new(&"x".repeat(MAX_CHAT_MESSAGE_LEN)).is_ok());
426- assert!(ChatContent::try_new(&"x".repeat(MAX_CHAT_MESSAGE_LEN + 1)).is_err());
425+ assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN)).is_ok());
426+ assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err());
427427 }
428428
429429 #[tokio::test]
@@ -455,24 +455,24 @@ mod tests {
455455 // inverted a fifth of the pairs; here every pair must read back
456456 // question-then-answer, from both read paths.
457457 let db = crate::database::init_mem().await.unwrap();
458- let conversation = ConversationId::from_key("c");
458+ let thread = ChatbotThreadId::from_key("c");
459459 let user = UserId::from_key("u");
460460 const TURNS: usize = 200;
461461
462462 for turn in 0..TURNS {
463463 let content = ChatContent::try_new(&format!("soru {turn}")).unwrap();
464- ChatMessage::append_user(&conversation, &user, content, &db)
464+ ChatbotMessage::append_user(&thread, &user, content, &db)
465465 .await
466466 .unwrap();
467- ChatMessage::append_pending_assistant(&conversation, &user, &db)
467+ ChatbotMessage::append_pending_assistant(&thread, &user, &db)
468468 .await
469469 .unwrap();
470470 }
471471
472- let whole = ChatMessage::list_for_conversation(&conversation, &db)
472+ let whole = ChatbotMessage::list_for_thread(&thread, &db)
473473 .await
474474 .unwrap();
475- let tail = ChatMessage::list_tail(&conversation, TURNS * 2, &db)
475+ let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)
476476 .await
477477 .unwrap();
478478 for messages in [&whole, &tail] {
@@ -488,9 +488,9 @@ mod tests {
488488 #[tokio::test]
489489 async fn stale_pending_projects_as_failed() {
490490 let aged = |secs: i64| {
491- ChatMessage {
492- id: ChatMessageId::generate(),
493- conversation_id: ConversationId::from_key("c"),
491+ ChatbotMessage {
492+ id: ChatbotMessageId::generate(),
493+ thread_id: ChatbotThreadId::from_key("c"),
494494 user_id: UserId::from_key("u"),
495495 role: MessageRole::Assistant,
496496 content: ChatContent::empty(),
@@ -507,7 +507,7 @@ mod tests {
507507 assert_eq!(fresh.get_status(), MessageStatus::Pending);
508508 assert_eq!(fresh.get_error_code(), None);
509509
510- let stale = aged(CHAT_PENDING_STALE_SECS + 1);
510+ let stale = aged(CHATBOT_PENDING_STALE_SECS + 1);
511511 assert_eq!(stale.get_status(), MessageStatus::Failed);
512512 assert_eq!(stale.get_error_code(), Some(STALE_ERROR_CODE));
513513 }
src/domain/conversation.rs → src/domain/chatbot_thread.rsrenamed+59 -59
@@ -1,40 +1,40 @@
11 //! A chatbot thread. It only groups turns and carries the ordering key the
22 //! list view sorts on: `updated_at` moves on every new turn, so a user's
3-//! conversations list newest-activity-first. The turns themselves live in
4-//! [`crate::domain::chat_message`], and deleting a conversation cascades them.
3+//! threads list newest-activity-first. The turns themselves live in
4+//! [`crate::domain::chatbot_message`], and deleting a thread cascades them.
55
66 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
77 use tokio::sync::Mutex;
88 use ulid::Ulid;
99
10-use crate::database::{CONVERSATION_TABLE, Database};
10+use crate::database::{CHATBOT_THREAD_TABLE, Database};
1111 use crate::domain::settings::Settings;
1212 use crate::domain::timestamp::Timestamp;
1313 use crate::domain::user::UserId;
1414 use crate::error::{AppError, ValidationError};
1515 use crate::validate::validate_required;
1616
17-/// Serializes thread creation so the `max_chat_conversations` check (count,
17+/// Serializes thread creation so the `max_chatbot_threads` check (count,
1818 /// then write) can't over-admit under concurrency — the database's optimistic
1919 /// transactions don't serialize cross-record counts against concurrent
2020 /// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`.
21-static CONVERSATION_LOCK: Mutex<()> = Mutex::const_new(());
21+static CHATBOT_THREAD_LOCK: Mutex<()> = Mutex::const_new(());
2222
2323 /// Bound on a thread's display name. Local to this module because
2424 /// `constant.rs` is another task's file; move it there with the rest of the
2525 /// chat limits when they are next touched.
26-const MAX_CONVERSATION_TITLE_LEN: usize = 200;
26+const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
2727
2828 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
29-pub struct ConversationId(RecordId);
29+pub struct ChatbotThreadId(RecordId);
3030
31-impl ConversationId {
31+impl ChatbotThreadId {
3232 pub fn generate() -> Self {
33- Self(RecordId::new(CONVERSATION_TABLE, Ulid::new().to_string()))
33+ Self(RecordId::new(CHATBOT_THREAD_TABLE, Ulid::new().to_string()))
3434 }
3535
3636 pub fn from_key(key: &str) -> Self {
37- Self(RecordId::new(CONVERSATION_TABLE, key))
37+ Self(RecordId::new(CHATBOT_THREAD_TABLE, key))
3838 }
3939
4040 pub fn record(&self) -> RecordId {
@@ -50,13 +50,13 @@ impl ConversationId {
5050 }
5151
5252 /// A user-chosen thread name. Required-and-bounded here; "untitled" is
53-/// `Option<ConversationTitle>` on the row.
53+/// `Option<ChatbotThreadTitle>` on the row.
5454 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
55-pub struct ConversationTitle(String);
55+pub struct ChatbotThreadTitle(String);
5656
57-impl ConversationTitle {
57+impl ChatbotThreadTitle {
5858 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
59- validate_required("title", value, MAX_CONVERSATION_TITLE_LEN)?;
59+ validate_required("title", value, MAX_CHATBOT_THREAD_TITLE_LEN)?;
6060 Ok(Self(value.to_string()))
6161 }
6262
@@ -66,16 +66,16 @@ impl ConversationTitle {
6666 }
6767
6868 #[derive(Debug, Clone, SurrealValue)]
69-pub struct Conversation {
70- id: ConversationId,
69+pub struct ChatbotThread {
70+ id: ChatbotThreadId,
7171 user_id: UserId,
72- title: Option<ConversationTitle>,
72+ title: Option<ChatbotThreadTitle>,
7373 created_at: Timestamp,
7474 updated_at: Timestamp,
7575 }
7676
77-impl Conversation {
78- pub fn get_id(&self) -> &ConversationId {
77+impl ChatbotThread {
78+ pub fn get_id(&self) -> &ChatbotThreadId {
7979 &self.id
8080 }
8181
@@ -83,7 +83,7 @@ impl Conversation {
8383 &self.user_id
8484 }
8585
86- pub fn get_title(&self) -> Option<&ConversationTitle> {
86+ pub fn get_title(&self) -> Option<&ChatbotThreadTitle> {
8787 self.title.as_ref()
8888 }
8989
@@ -97,62 +97,62 @@ impl Conversation {
9797
9898 pub async fn create(
9999 user: &UserId,
100- title: Option<ConversationTitle>,
100+ title: Option<ChatbotThreadTitle>,
101101 db: &Database,
102- ) -> Result<Conversation, AppError> {
102+ ) -> Result<ChatbotThread, AppError> {
103103 let now = Timestamp::now();
104- let conversation = Conversation {
105- id: ConversationId::generate(),
104+ let thread = ChatbotThread {
105+ id: ChatbotThreadId::generate(),
106106 user_id: user.clone(),
107107 title,
108108 created_at: now,
109109 updated_at: now,
110110 };
111- let created: Option<Conversation> = db
112- .create(conversation.id.record())
113- .content(conversation)
111+ let created: Option<ChatbotThread> = db
112+ .create(thread.id.record())
113+ .content(thread)
114114 .await?;
115- created.ok_or_else(|| AppError::Internal("failed to create conversation".into()))
115+ created.ok_or_else(|| AppError::Internal("failed to create thread".into()))
116116 }
117117
118118 /// Start a thread unless `user` is already at the school's
119- /// `max_chat_conversations`. The whole check-then-write runs under
120- /// [`CONVERSATION_LOCK`], and the cap is re-read inside it, since neither
119+ /// `max_chatbot_threads`. The whole check-then-write runs under
120+ /// [`CHATBOT_THREAD_LOCK`], and the cap is re-read inside it, since neither
121121 /// the transaction model nor a caller-supplied number survives a concurrent
122122 /// settings PATCH.
123123 pub async fn create_capped(
124124 user: &UserId,
125- title: Option<ConversationTitle>,
125+ title: Option<ChatbotThreadTitle>,
126126 db: &Database,
127- ) -> Result<Conversation, AppError> {
128- let _guard = CONVERSATION_LOCK.lock().await;
129- let cap = Settings::load(db).await?.get_max_chat_conversations();
127+ ) -> Result<ChatbotThread, AppError> {
128+ let _guard = CHATBOT_THREAD_LOCK.lock().await;
129+ let cap = Settings::load(db).await?.get_max_chatbot_threads();
130130 if Self::count_for_user(user, db).await? as i64 >= cap {
131131 return Err(AppError::Conflict(
132- "you have reached the school's limit on saved conversations — delete one first",
132+ "you have reached the school's limit on saved threads — delete one first",
133133 ));
134134 }
135135 Self::create(user, title, db).await
136136 }
137137
138138 /// A user's threads, most recently active first — the sort the
139- /// `conversation_user_updated` index exists for.
139+ /// `chatbot_thread_user_updated` index exists for.
140140 pub async fn list_for_user(
141141 user: &UserId,
142142 db: &Database,
143- ) -> Result<Vec<Conversation>, AppError> {
143+ ) -> Result<Vec<ChatbotThread>, AppError> {
144144 let mut result = db
145- .query("SELECT * FROM conversation WHERE user_id = $usr ORDER BY updated_at DESC")
145+ .query("SELECT * FROM chatbot_thread WHERE user_id = $usr ORDER BY updated_at DESC")
146146 .bind(("usr", user.record()))
147147 .await?
148148 .check()?;
149- Ok(result.take::<Vec<Conversation>>(0)?)
149+ Ok(result.take::<Vec<ChatbotThread>>(0)?)
150150 }
151151
152- /// How many threads `user` keeps — the `max_chat_conversations` cap check.
152+ /// How many threads `user` keeps — the `max_chatbot_threads` cap check.
153153 pub async fn count_for_user(user: &UserId, db: &Database) -> Result<usize, AppError> {
154154 let mut result = db
155- .query("SELECT VALUE count() FROM conversation WHERE user_id = $usr GROUP ALL")
155+ .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL")
156156 .bind(("usr", user.record()))
157157 .await?
158158 .check()?;
@@ -167,17 +167,17 @@ impl Conversation {
167167 /// Read a thread only if `user` owns it — a foreign id reads as absent, so
168168 /// the web layer answers 404 rather than leaking that it exists.
169169 pub async fn read_for(
170- id: &ConversationId,
170+ id: &ChatbotThreadId,
171171 user: &UserId,
172172 db: &Database,
173- ) -> Result<Option<Conversation>, AppError> {
174- let conversation: Option<Conversation> = db.select(id.record()).await?;
175- Ok(conversation.filter(|conversation| &conversation.user_id == user))
173+ ) -> Result<Option<ChatbotThread>, AppError> {
174+ let thread: Option<ChatbotThread> = db.select(id.record()).await?;
175+ Ok(thread.filter(|thread| &thread.user_id == user))
176176 }
177177
178178 /// Stamp new activity. Field-scoped: a rename may be landing concurrently,
179179 /// and a whole-row save would clobber it.
180- pub async fn touch(&self, db: &Database) -> Result<Conversation, AppError> {
180+ pub async fn touch(&self, db: &Database) -> Result<ChatbotThread, AppError> {
181181 let mut result = db
182182 .query("UPDATE $id SET updated_at = $now RETURN AFTER")
183183 .bind(("id", self.id.record()))
@@ -185,7 +185,7 @@ impl Conversation {
185185 .await?
186186 .check()?;
187187 result
188- .take::<Vec<Conversation>>(0)?
188+ .take::<Vec<ChatbotThread>>(0)?
189189 .into_iter()
190190 .next()
191191 .ok_or(AppError::NotFound)
@@ -193,12 +193,12 @@ impl Conversation {
193193
194194 /// Rename the thread (`None` clears the name back to untitled), stamping
195195 /// the edit as activity. Field-scoped for the same reason as
196- /// [`Conversation::touch`]: a turn may be landing concurrently.
196+ /// [`ChatbotThread::touch`]: a turn may be landing concurrently.
197197 pub async fn rename(
198198 &self,
199- title: Option<ConversationTitle>,
199+ title: Option<ChatbotThreadTitle>,
200200 db: &Database,
201- ) -> Result<Conversation, AppError> {
201+ ) -> Result<ChatbotThread, AppError> {
202202 let mut result = db
203203 .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER")
204204 .bind(("id", self.id.record()))
@@ -207,27 +207,27 @@ impl Conversation {
207207 .await?
208208 .check()?;
209209 result
210- .take::<Vec<Conversation>>(0)?
210+ .take::<Vec<ChatbotThread>>(0)?
211211 .into_iter()
212212 .next()
213213 .ok_or(AppError::NotFound)
214214 }
215215
216216 /// Delete the thread and every turn in it — one transaction, so a crash
217- /// can't orphan messages under a vanished conversation.
218- pub async fn delete(self, db: &Database) -> Result<Conversation, AppError> {
217+ /// can't orphan messages under a vanished thread.
218+ pub async fn delete(self, db: &Database) -> Result<ChatbotThread, AppError> {
219219 let mut result = db
220220 .query(
221221 "BEGIN TRANSACTION;
222- DELETE chat_message WHERE conversation_id = $conv;
222+ DELETE chatbot_message WHERE thread_id = $conv;
223223 DELETE $conv RETURN BEFORE;
224224 COMMIT TRANSACTION;",
225225 )
226226 .bind(("conv", self.id.record()))
227227 .await?
228228 .check()?;
229- // BEGIN is slot 0; the conversation's own DELETE is slot 2.
230- let deleted: Option<Conversation> = result.take::<Vec<Conversation>>(2)?.into_iter().next();
229+ // BEGIN is slot 0; the thread's own DELETE is slot 2.
230+ let deleted: Option<ChatbotThread> = result.take::<Vec<ChatbotThread>>(2)?.into_iter().next();
231231 deleted.ok_or(AppError::NotFound)
232232 }
233233 }
@@ -239,10 +239,10 @@ mod tests {
239239 #[tokio::test]
240240 async fn title_is_required_and_bounded() {
241241 assert_eq!(
242- ConversationTitle::try_new("Fizik").unwrap().as_str(),
242+ ChatbotThreadTitle::try_new("Fizik").unwrap().as_str(),
243243 "Fizik"
244244 );
245- assert!(ConversationTitle::try_new(" ").is_err());
246- assert!(ConversationTitle::try_new(&"x".repeat(201)).is_err());
245+ assert!(ChatbotThreadTitle::try_new(" ").is_err());
246+ assert!(ChatbotThreadTitle::try_new(&"x".repeat(201)).is_err());
247247 }
248248 }
src/domain/mod.rsmodified+2 -2
@@ -6,8 +6,8 @@ pub mod answer_image;
66 pub mod appointment;
77 pub mod appointment_slot;
88 pub mod attendance;
9-pub mod chat_message;
10-pub mod conversation;
9+pub mod chatbot_message;
10+pub mod chatbot_thread;
1111 pub mod course;
1212 pub mod course_session;
1313 pub mod enrollment;
src/domain/settings.rsmodified+77 -77
@@ -14,12 +14,12 @@
1414 use surrealdb::types::{RecordId, SurrealValue};
1515
1616 use crate::constant::{
17- DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHAT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,
18- DEFAULT_MAX_CHAT_CONVERSATIONS, DEFAULT_MAX_CHAT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES,
19- MAX_CHAT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK,
20- MAX_MAX_CHAT_CONVERSATIONS, MAX_MAX_CHAT_MESSAGE_LEN, MAX_MAX_FILE_BYTES,
21- MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHAT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,
22- MIN_MARK, MIN_MAX_CHAT_CONVERSATIONS, MIN_MAX_CHAT_MESSAGE_LEN, MIN_MAX_FILE_BYTES,
17+ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,
18+ DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES,
19+ MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK,
20+ MAX_MAX_CHATBOT_THREADS, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_FILE_BYTES,
21+ MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,
22+ MIN_MARK, MIN_MAX_CHATBOT_THREADS, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_FILE_BYTES,
2323 };
2424 use crate::database::{Database, SETTINGS_TABLE};
2525 use crate::error::{AppError, ValidationError};
@@ -118,9 +118,9 @@ pub struct Settings {
118118 /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`.
119119 max_file_bytes: Option<i64>,
120120 /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`.
121- chat_history_turns: Option<i64>,
122- max_chat_conversations: Option<i64>,
123- max_chat_message_len: Option<i64>,
121+ chatbot_history_turns: Option<i64>,
122+ max_chatbot_threads: Option<i64>,
123+ max_chatbot_message_len: Option<i64>,
124124 }
125125
126126 /// Everything [`Settings::try_new`] validates, in one struct — the knobs
@@ -132,9 +132,9 @@ pub struct SettingsParams {
132132 pub attendance_statuses: Vec<String>,
133133 pub grade_bands: Vec<GradeBand>,
134134 pub max_file_bytes: i64,
135- pub chat_history_turns: i64,
136- pub max_chat_conversations: i64,
137- pub max_chat_message_len: i64,
135+ pub chatbot_history_turns: i64,
136+ pub max_chatbot_threads: i64,
137+ pub max_chatbot_message_len: i64,
138138 }
139139
140140 impl Settings {
@@ -156,9 +156,9 @@ impl Settings {
156156 attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(),
157157 grade_bands: Vec::new(),
158158 max_file_bytes: None,
159- chat_history_turns: None,
160- max_chat_conversations: None,
161- max_chat_message_len: None,
159+ chatbot_history_turns: None,
160+ max_chatbot_threads: None,
161+ max_chatbot_message_len: None,
162162 }
163163 }
164164
@@ -170,9 +170,9 @@ impl Settings {
170170 attendance_statuses: self.attendance_statuses.clone(),
171171 grade_bands: self.grade_bands.clone(),
172172 max_file_bytes: self.get_max_file_bytes(),
173- chat_history_turns: self.get_chat_history_turns(),
174- max_chat_conversations: self.get_max_chat_conversations(),
175- max_chat_message_len: self.get_max_chat_message_len(),
173+ chatbot_history_turns: self.get_chatbot_history_turns(),
174+ max_chatbot_threads: self.get_max_chatbot_threads(),
175+ max_chatbot_message_len: self.get_max_chatbot_message_len(),
176176 }
177177 }
178178
@@ -190,9 +190,9 @@ impl Settings {
190190 attendance_statuses,
191191 grade_bands,
192192 max_file_bytes,
193- chat_history_turns,
194- max_chat_conversations,
195- max_chat_message_len,
193+ chatbot_history_turns,
194+ max_chatbot_threads,
195+ max_chatbot_message_len,
196196 } = params;
197197 in_range(
198198 "max_file_bytes",
@@ -201,21 +201,21 @@ impl Settings {
201201 "must be between 1024 (1 KiB) and 26214400 (25 MiB)",
202202 )?;
203203 in_range(
204- "chat_history_turns",
205- chat_history_turns,
206- MIN_CHAT_HISTORY_TURNS..=MAX_CHAT_HISTORY_TURNS,
204+ "chatbot_history_turns",
205+ chatbot_history_turns,
206+ MIN_CHATBOT_HISTORY_TURNS..=MAX_CHATBOT_HISTORY_TURNS,
207207 "must be between 1 and 50",
208208 )?;
209209 in_range(
210- "max_chat_conversations",
211- max_chat_conversations,
212- MIN_MAX_CHAT_CONVERSATIONS..=MAX_MAX_CHAT_CONVERSATIONS,
210+ "max_chatbot_threads",
211+ max_chatbot_threads,
212+ MIN_MAX_CHATBOT_THREADS..=MAX_MAX_CHATBOT_THREADS,
213213 "must be between 1 and 500",
214214 )?;
215215 in_range(
216- "max_chat_message_len",
217- max_chat_message_len,
218- MIN_MAX_CHAT_MESSAGE_LEN..=MAX_MAX_CHAT_MESSAGE_LEN,
216+ "max_chatbot_message_len",
217+ max_chatbot_message_len,
218+ MIN_MAX_CHATBOT_MESSAGE_LEN..=MAX_MAX_CHATBOT_MESSAGE_LEN,
219219 "must be between 100 and 8000 characters",
220220 )?;
221221 // Per-entry rules (name shape, weight range) hold structurally on any
@@ -267,9 +267,9 @@ impl Settings {
267267 attendance_statuses,
268268 grade_bands,
269269 max_file_bytes: Some(max_file_bytes),
270- chat_history_turns: Some(chat_history_turns),
271- max_chat_conversations: Some(max_chat_conversations),
272- max_chat_message_len: Some(max_chat_message_len),
270+ chatbot_history_turns: Some(chatbot_history_turns),
271+ max_chatbot_threads: Some(max_chatbot_threads),
272+ max_chatbot_message_len: Some(max_chatbot_message_len),
273273 })
274274 }
275275
@@ -302,25 +302,25 @@ impl Settings {
302302 self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES)
303303 }
304304
305- /// How many prior conversation turns ride along as context on an AI
305+ /// How many prior thread turns ride along as context on an AI
306306 /// request; the built-in default while the school never set one.
307- pub fn get_chat_history_turns(&self) -> i64 {
308- self.chat_history_turns
309- .unwrap_or(DEFAULT_CHAT_HISTORY_TURNS)
307+ pub fn get_chatbot_history_turns(&self) -> i64 {
308+ self.chatbot_history_turns
309+ .unwrap_or(DEFAULT_CHATBOT_HISTORY_TURNS)
310310 }
311311
312- /// How many conversations one user may keep; the built-in default while
312+ /// How many threads one user may keep; the built-in default while
313313 /// the school never set one.
314- pub fn get_max_chat_conversations(&self) -> i64 {
315- self.max_chat_conversations
316- .unwrap_or(DEFAULT_MAX_CHAT_CONVERSATIONS)
314+ pub fn get_max_chatbot_threads(&self) -> i64 {
315+ self.max_chatbot_threads
316+ .unwrap_or(DEFAULT_MAX_CHATBOT_THREADS)
317317 }
318318
319319 /// Character cap on one chat message; the built-in default while the
320320 /// school never set one.
321- pub fn get_max_chat_message_len(&self) -> i64 {
322- self.max_chat_message_len
323- .unwrap_or(DEFAULT_MAX_CHAT_MESSAGE_LEN)
321+ pub fn get_max_chatbot_message_len(&self) -> i64 {
322+ self.max_chatbot_message_len
323+ .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN)
324324 }
325325
326326 /// The label of the band `mark` falls into: the band with the greatest
@@ -374,9 +374,9 @@ impl Settings {
374374 AND attendance_statuses = $st
375375 AND grade_bands = $gb
376376 AND max_file_bytes = $mf
377- AND chat_history_turns = $ct
378- AND max_chat_conversations = $cc
379- AND max_chat_message_len = $cl;
377+ AND chatbot_history_turns = $ct
378+ AND max_chatbot_threads = $cc
379+ AND max_chatbot_message_len = $cl;
380380 COMMIT TRANSACTION;",
381381 )
382382 .bind(("expected", expected.clone()))
@@ -386,9 +386,9 @@ impl Settings {
386386 .bind(("st", expected.attendance_statuses.clone()))
387387 .bind(("gb", expected.grade_bands.clone()))
388388 .bind(("mf", expected.max_file_bytes))
389- .bind(("ct", expected.chat_history_turns))
390- .bind(("cc", expected.max_chat_conversations))
391- .bind(("cl", expected.max_chat_message_len))
389+ .bind(("ct", expected.chatbot_history_turns))
390+ .bind(("cc", expected.max_chatbot_threads))
391+ .bind(("cl", expected.max_chatbot_message_len))
392392 .await?
393393 .check()?;
394394 // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An
@@ -450,7 +450,7 @@ fn validate_list(field: &'static str, values: Vec<String>) -> Result<Vec<String>
450450 #[cfg(test)]
451451 mod tests {
452452 use super::*;
453- use crate::constant::MAX_CHAT_MESSAGE_LEN;
453+ use crate::constant::MAX_CHATBOT_MESSAGE_LEN;
454454
455455 fn kinds(list: &[&str]) -> Vec<ExamKindDef> {
456456 list.iter()
@@ -618,49 +618,49 @@ mod tests {
618618 #[tokio::test]
619619 async fn chat_knobs_are_bounded() {
620620 // Each knob is held to its own inclusive range; the edges are legal.
621- let turns = |chat_history_turns| {
621+ let turns = |chatbot_history_turns| {
622622 Settings::try_new(SettingsParams {
623- chat_history_turns,
623+ chatbot_history_turns,
624624 ..params()
625625 })
626626 };
627627 assert_eq!(
628- turns(MAX_CHAT_HISTORY_TURNS)
628+ turns(MAX_CHATBOT_HISTORY_TURNS)
629629 .unwrap()
630- .get_chat_history_turns(),
631- MAX_CHAT_HISTORY_TURNS
630+ .get_chatbot_history_turns(),
631+ MAX_CHATBOT_HISTORY_TURNS
632632 );
633- assert!(turns(MIN_CHAT_HISTORY_TURNS).is_ok());
633+ assert!(turns(MIN_CHATBOT_HISTORY_TURNS).is_ok());
634634 assert!(turns(0).is_err());
635- assert!(turns(MAX_CHAT_HISTORY_TURNS + 1).is_err());
635+ assert!(turns(MAX_CHATBOT_HISTORY_TURNS + 1).is_err());
636636
637- let convos = |max_chat_conversations| {
637+ let convos = |max_chatbot_threads| {
638638 Settings::try_new(SettingsParams {
639- max_chat_conversations,
639+ max_chatbot_threads,
640640 ..params()
641641 })
642642 };
643643 assert_eq!(
644- convos(7).unwrap().get_max_chat_conversations(),
644+ convos(7).unwrap().get_max_chatbot_threads(),
645645 7,
646646 "an in-range cap survives validation"
647647 );
648- assert!(convos(MIN_MAX_CHAT_CONVERSATIONS).is_ok());
649- assert!(convos(MAX_MAX_CHAT_CONVERSATIONS).is_ok());
648+ assert!(convos(MIN_MAX_CHATBOT_THREADS).is_ok());
649+ assert!(convos(MAX_MAX_CHATBOT_THREADS).is_ok());
650650 assert!(convos(0).is_err());
651- assert!(convos(MAX_MAX_CHAT_CONVERSATIONS + 1).is_err());
651+ assert!(convos(MAX_MAX_CHATBOT_THREADS + 1).is_err());
652652
653- let len = |max_chat_message_len| {
653+ let len = |max_chatbot_message_len| {
654654 Settings::try_new(SettingsParams {
655- max_chat_message_len,
655+ max_chatbot_message_len,
656656 ..params()
657657 })
658658 };
659- assert!(len(MIN_MAX_CHAT_MESSAGE_LEN).is_ok());
660- assert!(len(MAX_MAX_CHAT_MESSAGE_LEN).is_ok());
661- assert!(len(MIN_MAX_CHAT_MESSAGE_LEN - 1).is_err());
659+ assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN).is_ok());
660+ assert!(len(MAX_MAX_CHATBOT_MESSAGE_LEN).is_ok());
661+ assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN - 1).is_err());
662662 // The ceiling is the newtype's hard cap: no school can raise it.
663- assert!(len(MAX_CHAT_MESSAGE_LEN as i64 + 1).is_err());
663+ assert!(len(MAX_CHATBOT_MESSAGE_LEN as i64 + 1).is_err());
664664 }
665665
666666 #[tokio::test]
@@ -671,14 +671,14 @@ mod tests {
671671 Settings::defaults().save(&db).await.unwrap();
672672 let loaded = Settings::load(&db).await.unwrap();
673673 assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);
674- assert_eq!(loaded.get_chat_history_turns(), DEFAULT_CHAT_HISTORY_TURNS);
674+ assert_eq!(loaded.get_chatbot_history_turns(), DEFAULT_CHATBOT_HISTORY_TURNS);
675675 assert_eq!(
676- loaded.get_max_chat_conversations(),
677- DEFAULT_MAX_CHAT_CONVERSATIONS
676+ loaded.get_max_chatbot_threads(),
677+ DEFAULT_MAX_CHATBOT_THREADS
678678 );
679679 assert_eq!(
680- loaded.get_max_chat_message_len(),
681- DEFAULT_MAX_CHAT_MESSAGE_LEN
680+ loaded.get_max_chatbot_message_len(),
681+ DEFAULT_MAX_CHATBOT_MESSAGE_LEN
682682 );
683683 // And a snapshot of that old row still passes the compare-and-set.
684684 let saved = Settings::try_new(SettingsParams {
@@ -708,7 +708,7 @@ mod tests {
708708 exam_kinds: kinds(&["lab"]),
709709 grade_bands: bands(&[(0, "F"), (50, "P")]),
710710 max_file_bytes: 2048,
711- chat_history_turns: 3,
711+ chatbot_history_turns: 3,
712712 ..params()
713713 })
714714 .unwrap()
@@ -720,7 +720,7 @@ mod tests {
720720 assert_eq!(loaded.get_grade_bands().len(), 2);
721721 assert_eq!(loaded.grade_label(60.0), Some("P"));
722722 assert_eq!(loaded.get_max_file_bytes(), 2048);
723- assert_eq!(loaded.get_chat_history_turns(), 3);
723+ assert_eq!(loaded.get_chatbot_history_turns(), 3);
724724 // A second save lands on the same singleton row, not a new one.
725725 Settings::try_new(SettingsParams {
726726 exam_kinds: kinds(&["quiz"]),
src/lib.rsmodified+2 -2
@@ -42,7 +42,7 @@ use crate::state::AppState;
4242 (name = "meta", description = "Liveness and service metadata"),
4343 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
4444 (name = "auth", description = "Registration, login, session lifecycle"),
45- (name = "chat", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chat_conversations` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHAT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chat/conversations/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chat/conversations/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chat_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no AI service connected, sending answers `503` and writes nothing"),
45+ (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no AI service connected, sending answers `503` and writes nothing"),
4646 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"),
4747 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),
4848 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
@@ -90,7 +90,7 @@ pub fn build_router(state: AppState) -> Router {
9090 .routes(routes!(server_time))
9191 .nest("/ai", web::ai::routes())
9292 .nest("/auth", web::auth::routes(&state.rate_limit))
93- .nest("/chat", web::chat::routes())
93+ .nest("/chatbot", web::chatbot::routes())
9494 .nest("/users", web::users::routes())
9595 .nest("/notes", web::notes::routes())
9696 .nest("/messages", web::messages::routes())
src/main.rsmodified+1 -1
@@ -30,7 +30,7 @@ async fn main() -> anyhow::Result<()> {
3030 files_path: cfg.files_path.clone().into(),
3131 cookie_secure: cfg.cookie_secure,
3232 rate_limit: cfg.rate_limit.clone(),
33- chat_limit: UserRateLimiter::per_user_minute(cfg.chat_per_minute),
33+ chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute),
3434 exam_presence: Default::default(),
3535 db_up,
3636 ai,
src/rate_limit.rsmodified+3 -3
@@ -95,13 +95,13 @@ impl Default for UserRateLimiter {
9595 /// The chatbot tier at its shipped default, for tests and any caller that
9696 /// has no [`crate::config::Config`] to hand.
9797 fn default() -> Self {
98- Self::per_user_minute(crate::config::DEFAULT_CHAT_RATE_LIMIT)
98+ Self::per_user_minute(crate::config::DEFAULT_CHATBOT_RATE_LIMIT)
9999 }
100100 }
101101
102102 impl UserRateLimiter {
103103 /// The chatbot tier: `max` messages per user per minute, from
104- /// `RATE_LIMIT_CHAT_PER_MINUTE`. `max == 0` disables it, like the IP tiers.
104+ /// `RATE_LIMIT_CHATBOT_PER_MINUTE`. `max == 0` disables it, like the IP tiers.
105105 pub fn per_user_minute(max: u32) -> Self {
106106 Self::new(max, false)
107107 }
@@ -346,7 +346,7 @@ mod tests {
346346 #[tokio::test(start_paused = true)]
347347 async fn users_get_independent_windows_that_reset() {
348348 let limiter = UserRateLimiter::default();
349- for _ in 0..crate::config::DEFAULT_CHAT_RATE_LIMIT {
349+ for _ in 0..crate::config::DEFAULT_CHATBOT_RATE_LIMIT {
350350 assert!(limiter.enforce_user("user:a").is_ok());
351351 }
352352 assert!(matches!(
src/state.rsmodified+2 -2
@@ -22,10 +22,10 @@ pub struct AppState {
2222 /// Read once by [`crate::build_router`] when the limiters are built.
2323 pub rate_limit: RateLimitConfig,
2424 /// Per-user chatbot limit (see [`UserRateLimiter`], built from
25- /// [`crate::config::Config::chat_per_minute`]). Not middleware: the
25+ /// [`crate::config::Config::chatbot_per_minute`]). Not middleware: the
2626 /// caller is only known after `CurrentUser` has run, so handlers call it
2727 /// themselves.
28- pub chat_limit: UserRateLimiter,
28+ pub chatbot_limit: UserRateLimiter,
2929 /// Who is inside which exam room right now (see [`ExamPresence`]).
3030 pub exam_presence: ExamPresence,
3131 /// Whether the database socket answered its last ping (see [`DbHealth`]).
src/web/chat.rs → src/web/chatbot.rsrenamed+135 -135
@@ -2,7 +2,7 @@
22 //!
33 //! The backend owns everything except the answer itself — auth, the per-user
44 //! rate limit, the thread, the payload format, and the last look at the reply
5-//! before it is stored. There are no intent or rule tables: the conversation is
5+//! before it is stored. There are no intent or rule tables: the thread is
66 //! free-form on purpose.
77 //!
88 //! Sending is asynchronous by design. `POST .../messages` writes the user's
@@ -30,12 +30,12 @@ use utoipa_axum::routes;
3030
3131 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
3232 use crate::ai::{AiBridge, AiError};
33-use crate::constant::{AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHAT_MESSAGE_LEN};
33+use crate::constant::{AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN};
3434 use crate::database::Database;
35-use crate::domain::chat_message::{
36- ChatContent, ChatMessage, ChatMessageId, MessageRole, MessageStatus,
35+use crate::domain::chatbot_message::{
36+ ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,
3737 };
38-use crate::domain::conversation::{Conversation, ConversationId, ConversationTitle};
38+use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
3939 use crate::domain::settings::Settings;
4040 use crate::domain::user::UserId;
4141 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -45,8 +45,8 @@ use super::{CurrentUser, Page, PageParams, paginate};
4545
4646 pub fn routes() -> OpenApiRouter<AppState> {
4747 OpenApiRouter::new()
48- .routes(routes!(create_conversation, list_conversations))
49- .routes(routes!(rename_conversation, delete_conversation))
48+ .routes(routes!(create_thread, list_threads))
49+ .routes(routes!(rename_thread, delete_thread))
5050 .routes(routes!(list_messages, send_message))
5151 .routes(routes!(read_message))
5252 .routes(routes!(stream_message))
@@ -57,10 +57,10 @@ pub fn routes() -> OpenApiRouter<AppState> {
5757 const REPLY_CHUNKS: usize = 8;
5858 const MIN_CHUNK_CHARS: usize = 24;
5959
60-// ---- conversations ----------------------------------------------------------
60+// ---- threads ----------------------------------------------------------
6161
6262 #[derive(Deserialize, ToSchema)]
63-struct CreateConversation {
63+struct CreateChatbotThread {
6464 /// Optional thread name, up to 200 characters. Blank counts as absent —
6565 /// an untitled thread is normal (the UI labels it from its first turn).
6666 #[schema(example = "Fizik ödevi")]
@@ -70,7 +70,7 @@ struct CreateConversation {
7070 /// One chatbot thread. `updated_at` moves on every turn, and the list is
7171 /// sorted by it, so the thread just written to is always first.
7272 #[derive(Serialize, ToSchema)]
73-struct ConversationResponse {
73+struct ChatbotThreadResponse {
7474 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
7575 id: String,
7676 #[schema(example = "Fizik ödevi")]
@@ -81,55 +81,55 @@ struct ConversationResponse {
8181 updated_at: i64,
8282 }
8383
84-impl ConversationResponse {
85- fn new(conversation: &Conversation) -> Self {
84+impl ChatbotThreadResponse {
85+ fn new(thread: &ChatbotThread) -> Self {
8686 Self {
87- id: conversation.get_id().key().to_string(),
88- title: conversation
87+ id: thread.get_id().key().to_string(),
88+ title: thread
8989 .get_title()
9090 .map(|title| title.as_str().to_string()),
91- created_at: conversation.get_created_at().as_millis(),
92- updated_at: conversation.get_updated_at().as_millis(),
91+ created_at: thread.get_created_at().as_millis(),
92+ updated_at: thread.get_updated_at().as_millis(),
9393 }
9494 }
9595 }
9696
9797 /// Start a new chatbot thread, optionally named. Every authenticated role may
9898 /// chat, parents included. A user may keep up to the school's
99-/// `max_chat_conversations` threads; at the cap the request is refused (409)
99+/// `max_chatbot_threads` threads; at the cap the request is refused (409)
100100 /// until an old thread is deleted — the cap is storage protection, not a
101101 /// usage quota (that is the per-minute message limit).
102102 #[utoipa::path(
103103 post,
104- path = "/conversations",
105- tag = "chat",
104+ path = "/threads",
105+ tag = "chatbot",
106106 security(("session_cookie" = [])),
107- request_body = CreateConversation,
107+ request_body = CreateChatbotThread,
108108 responses(
109- (status = 201, description = "The new thread", body = ConversationResponse),
109+ (status = 201, description = "The new thread", body = ChatbotThreadResponse),
110110 (status = 400, description = "Invalid title", body = ErrorResponse),
111111 (status = 401, description = "Not authenticated", body = ErrorResponse),
112- (status = 409, description = "At the school's conversation cap", body = ErrorResponse),
112+ (status = 409, description = "At the school's thread cap", body = ErrorResponse),
113113 ),
114114 )]
115-async fn create_conversation(
115+async fn create_thread(
116116 State(st): State<AppState>,
117117 CurrentUser(user): CurrentUser,
118- Json(req): Json<CreateConversation>,
119-) -> Result<(StatusCode, Json<ConversationResponse>), AppError> {
118+ Json(req): Json<CreateChatbotThread>,
119+) -> Result<(StatusCode, Json<ChatbotThreadResponse>), AppError> {
120120 // Blank is "untitled", not an error — same rule as a message's label.
121121 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
122122 "" => None,
123- value => Some(ConversationTitle::try_new(value)?),
123+ value => Some(ChatbotThreadTitle::try_new(value)?),
124124 };
125125
126126 // The cap is checked and the row written as one critical section in the
127127 // domain: counting here and creating after would over-admit under
128128 // concurrency (the database does not serialize a count against inserts).
129- let conversation = Conversation::create_capped(user.get_id(), title, &st.db).await?;
129+ let thread = ChatbotThread::create_capped(user.get_id(), title, &st.db).await?;
130130 Ok((
131131 StatusCode::CREATED,
132- Json(ConversationResponse::new(&conversation)),
132+ Json(ChatbotThreadResponse::new(&thread)),
133133 ))
134134 }
135135
@@ -137,33 +137,33 @@ async fn create_conversation(
137137 /// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's.
138138 #[utoipa::path(
139139 get,
140- path = "/conversations",
141- tag = "chat",
140+ path = "/threads",
141+ tag = "chatbot",
142142 security(("session_cookie" = [])),
143143 params(PageParams),
144144 responses(
145- (status = 200, description = "A page of the caller's threads", body = Page<ConversationResponse>),
145+ (status = 200, description = "A page of the caller's threads", body = Page<ChatbotThreadResponse>),
146146 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
147147 (status = 401, description = "Not authenticated", body = ErrorResponse),
148148 ),
149149 )]
150-async fn list_conversations(
150+async fn list_threads(
151151 State(st): State<AppState>,
152152 CurrentUser(user): CurrentUser,
153153 Query(page): Query<PageParams>,
154-) -> Result<Json<Page<ConversationResponse>>, AppError> {
154+) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {
155155 let (limit, offset) = page.resolve()?;
156- let conversations = Conversation::list_for_user(user.get_id(), &st.db).await?;
157- let total = conversations.len() as i64;
158- let items = paginate(&conversations, limit, offset)
156+ let threads = ChatbotThread::list_for_user(user.get_id(), &st.db).await?;
157+ let total = threads.len() as i64;
158+ let items = paginate(&threads, limit, offset)
159159 .iter()
160- .map(ConversationResponse::new)
160+ .map(ChatbotThreadResponse::new)
161161 .collect();
162162 Ok(Json(Page::new(items, total, limit, offset)))
163163 }
164164
165165 #[derive(Deserialize, ToSchema)]
166-struct RenameConversation {
166+struct RenameChatbotThread {
167167 /// The new name, up to 200 characters. `null` — or blank — clears it back
168168 /// to untitled, the same rule the create route applies.
169169 #[schema(example = "Fizik ödevi")]
@@ -179,65 +179,65 @@ struct RenameConversation {
179179 /// title, and the AI service is never asked for one.
180180 #[utoipa::path(
181181 patch,
182- path = "/conversations/{id}",
183- tag = "chat",
182+ path = "/threads/{id}",
183+ tag = "chatbot",
184184 security(("session_cookie" = [])),
185- params(("id" = String, Path, description = "Conversation id")),
186- request_body = RenameConversation,
185+ params(("id" = String, Path, description = "ChatbotThread id")),
186+ request_body = RenameChatbotThread,
187187 responses(
188- (status = 200, description = "The renamed thread", body = ConversationResponse),
188+ (status = 200, description = "The renamed thread", body = ChatbotThreadResponse),
189189 (status = 400, description = "Invalid title", body = ErrorResponse),
190190 (status = 401, description = "Not authenticated", body = ErrorResponse),
191191 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
192192 ),
193193 )]
194-async fn rename_conversation(
194+async fn rename_thread(
195195 State(st): State<AppState>,
196196 CurrentUser(user): CurrentUser,
197197 Path(id): Path<String>,
198- Json(req): Json<RenameConversation>,
199-) -> Result<Json<ConversationResponse>, AppError> {
198+ Json(req): Json<RenameChatbotThread>,
199+) -> Result<Json<ChatbotThreadResponse>, AppError> {
200200 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
201201 "" => None,
202- value => Some(ConversationTitle::try_new(value)?),
202+ value => Some(ChatbotThreadTitle::try_new(value)?),
203203 };
204- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;
205- let renamed = conversation.rename(title, &st.db).await?;
206- Ok(Json(ConversationResponse::new(&renamed)))
204+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
205+ let renamed = thread.rename(title, &st.db).await?;
206+ Ok(Json(ChatbotThreadResponse::new(&renamed)))
207207 }
208208
209209 /// Delete a thread and every turn in it, permanently. Owner only; someone
210210 /// else's thread is a `404`, never a `403` (its existence is not leaked).
211211 #[utoipa::path(
212212 delete,
213- path = "/conversations/{id}",
214- tag = "chat",
213+ path = "/threads/{id}",
214+ tag = "chatbot",
215215 security(("session_cookie" = [])),
216- params(("id" = String, Path, description = "Conversation id")),
216+ params(("id" = String, Path, description = "ChatbotThread id")),
217217 responses(
218218 (status = 204, description = "Deleted, with its messages"),
219219 (status = 401, description = "Not authenticated", body = ErrorResponse),
220220 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
221221 ),
222222 )]
223-async fn delete_conversation(
223+async fn delete_thread(
224224 State(st): State<AppState>,
225225 CurrentUser(user): CurrentUser,
226226 Path(id): Path<String>,
227227 ) -> Result<StatusCode, AppError> {
228- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;
229- conversation.delete(&st.db).await?;
228+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
229+ thread.delete(&st.db).await?;
230230 Ok(StatusCode::NO_CONTENT)
231231 }
232232
233233 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
234234 /// from a missing one.
235-async fn own_conversation(
235+async fn own_thread(
236236 id: &str,
237237 user: &UserId,
238238 db: &Database,
239-) -> Result<Conversation, AppError> {
240- Conversation::read_for(&ConversationId::from_key(id), user, db)
239+) -> Result<ChatbotThread, AppError> {
240+ ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db)
241241 .await?
242242 .ok_or(AppError::NotFound)
243243 }
@@ -245,15 +245,15 @@ async fn own_conversation(
245245 // ---- turns ------------------------------------------------------------------
246246
247247 #[derive(Deserialize, ToSchema)]
248-struct SendChatMessage {
248+struct SendChatbotMessage {
249249 /// What to ask. Required, and capped by the school's
250- /// `max_chat_message_len` (`GET /settings`).
250+ /// `max_chatbot_message_len` (`GET /settings`).
251251 #[schema(example = "Newton'un ikinci yasasını açıklar mısın?")]
252252 content: String,
253253 }
254254
255255 /// The receipt for an accepted turn. The answer is *not* here: it is being
256-/// fetched. Poll `GET /chat/conversations/{id}/messages/{mid}` or open its
256+/// fetched. Poll `GET /chatbot/threads/{id}/messages/{mid}` or open its
257257 /// `/stream`.
258258 #[derive(Serialize, ToSchema)]
259259 struct AcceptedResponse {
@@ -268,11 +268,11 @@ struct AcceptedResponse {
268268 /// One turn. `content` is empty while `status` is `pending`; `error_code` is
269269 /// set only when `status` is `failed`.
270270 #[derive(Serialize, ToSchema)]
271-struct ChatMessageResponse {
271+struct ChatbotMessageResponse {
272272 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
273273 id: String,
274274 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
275- conversation_id: String,
275+ thread_id: String,
276276 /// `user` or `assistant`.
277277 #[schema(example = "assistant")]
278278 role: String,
@@ -281,7 +281,7 @@ struct ChatMessageResponse {
281281 status: String,
282282 content: String,
283283 /// `true` when `content` is only the first part of what the assistant
284- /// answered — the rest was over the school's `max_chat_message_len` and was
284+ /// answered — the rest was over the school's `max_chatbot_message_len` and was
285285 /// cut. Always `false` for a user turn and for a failed one. Show the user
286286 /// that the answer is incomplete; asking again shortens nothing, so the way
287287 /// out is a narrower question (or a bigger cap).
@@ -299,11 +299,11 @@ struct ChatMessageResponse {
299299 completed_at: Option<i64>,
300300 }
301301
302-impl ChatMessageResponse {
303- fn new(message: &ChatMessage) -> Self {
302+impl ChatbotMessageResponse {
303+ fn new(message: &ChatbotMessage) -> Self {
304304 Self {
305305 id: message.get_id().key().to_string(),
306- conversation_id: message.get_conversation_id().key().to_string(),
306+ thread_id: message.get_thread_id().key().to_string(),
307307 role: message.get_role().as_str().to_string(),
308308 status: message.get_status().as_str().to_string(),
309309 content: message.get_content().as_str().to_string(),
@@ -318,12 +318,12 @@ impl ChatMessageResponse {
318318 /// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only.
319319 #[utoipa::path(
320320 get,
321- path = "/conversations/{id}/messages",
322- tag = "chat",
321+ path = "/threads/{id}/messages",
322+ tag = "chatbot",
323323 security(("session_cookie" = [])),
324- params(("id" = String, Path, description = "Conversation id"), PageParams),
324+ params(("id" = String, Path, description = "ChatbotThread id"), PageParams),
325325 responses(
326- (status = 200, description = "A page of the thread's turns", body = Page<ChatMessageResponse>),
326+ (status = 200, description = "A page of the thread's turns", body = Page<ChatbotMessageResponse>),
327327 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
328328 (status = 401, description = "Not authenticated", body = ErrorResponse),
329329 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
@@ -334,14 +334,14 @@ async fn list_messages(
334334 CurrentUser(user): CurrentUser,
335335 Path(id): Path<String>,
336336 Query(page): Query<PageParams>,
337-) -> Result<Json<Page<ChatMessageResponse>>, AppError> {
337+) -> Result<Json<Page<ChatbotMessageResponse>>, AppError> {
338338 let (limit, offset) = page.resolve()?;
339- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;
340- let messages = ChatMessage::list_for_conversation(conversation.get_id(), &st.db).await?;
339+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
340+ let messages = ChatbotMessage::list_for_thread(thread.get_id(), &st.db).await?;
341341 let total = messages.len() as i64;
342342 let items = paginate(&messages, limit, offset)
343343 .iter()
344- .map(ChatMessageResponse::new)
344+ .map(ChatbotMessageResponse::new)
345345 .collect();
346346 Ok(Json(Page::new(items, total, limit, offset)))
347347 }
@@ -358,14 +358,14 @@ async fn list_messages(
358358 /// the boot sweep repairs whatever a process death left behind.
359359 #[utoipa::path(
360360 post,
361- path = "/conversations/{id}/messages",
362- tag = "chat",
361+ path = "/threads/{id}/messages",
362+ tag = "chatbot",
363363 security(("session_cookie" = [])),
364- params(("id" = String, Path, description = "Conversation id")),
365- request_body = SendChatMessage,
364+ params(("id" = String, Path, description = "ChatbotThread id")),
365+ request_body = SendChatbotMessage,
366366 responses(
367367 (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse),
368- (status = 400, description = "Empty message, or longer than the school's `max_chat_message_len`", body = ErrorResponse),
368+ (status = 400, description = "Empty message, or longer than the school's `max_chatbot_message_len`", body = ErrorResponse),
369369 (status = 401, description = "Not authenticated", body = ErrorResponse),
370370 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
371371 (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse),
@@ -376,12 +376,12 @@ async fn send_message(
376376 State(st): State<AppState>,
377377 CurrentUser(user): CurrentUser,
378378 Path(id): Path<String>,
379- Json(req): Json<SendChatMessage>,
379+ Json(req): Json<SendChatbotMessage>,
380380 ) -> Result<Response, AppError> {
381381 // Charged first: a rejected turn must cost nothing and leave no row.
382- st.chat_limit.enforce_user(user.get_id().key())?;
382+ st.chatbot_limit.enforce_user(user.get_id().key())?;
383383
384- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;
384+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
385385 let settings = Settings::load(&st.db).await?;
386386 let reply_cap = content_cap(&settings);
387387 let length = req.content.chars().count();
@@ -406,23 +406,23 @@ async fn send_message(
406406 return Ok(unavailable("no AI service is connected right now"));
407407 }
408408
409- let prompt = ChatMessage::append_user(
410- conversation.get_id(),
409+ let prompt = ChatbotMessage::append_user(
410+ thread.get_id(),
411411 user.get_id(),
412412 content.clone(),
413413 &st.db,
414414 )
415415 .await?;
416416 let answer =
417- ChatMessage::append_pending_assistant(conversation.get_id(), user.get_id(), &st.db).await?;
417+ ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?;
418418 // Never fatal: both rows are already written, and failing here would strand
419419 // the pending one with no task to answer it (it would only settle 300s
420420 // later, by projection). `updated_at` is the list's sort key — cosmetic
421421 // next to a turn that has been accepted.
422- if let Err(err) = conversation.touch(&st.db).await {
422+ if let Err(err) = thread.touch(&st.db).await {
423423 tracing::warn!(
424- "could not stamp activity on conversation {}: {err}",
425- conversation.get_id().key()
424+ "could not stamp activity on thread {}: {err}",
425+ thread.get_id().key()
426426 );
427427 }
428428
@@ -431,10 +431,10 @@ async fn send_message(
431431 tokio::spawn(answer_turn(
432432 bridge,
433433 st.db.clone(),
434- conversation.get_id().clone(),
434+ thread.get_id().clone(),
435435 [prompt.get_id().clone(), answer.get_id().clone()],
436436 content.as_str().to_string(),
437- settings.get_chat_history_turns().max(0) as usize,
437+ settings.get_chatbot_history_turns().max(0) as usize,
438438 reply_cap,
439439 ));
440440
@@ -451,7 +451,7 @@ async fn send_message(
451451 /// The school's per-message character cap, never above the domain's hard
452452 /// ceiling. Applied to what the user sends *and* to what the service answers.
453453 fn content_cap(settings: &Settings) -> usize {
454- (settings.get_max_chat_message_len().max(0) as usize).min(MAX_CHAT_MESSAGE_LEN)
454+ (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN)
455455 }
456456
457457 /// The AI-unavailable `503`. Built here rather than as an `AppError` variant:
@@ -477,9 +477,9 @@ fn unavailable(message: &str) -> Response {
477477 async fn answer_turn(
478478 bridge: AiBridge,
479479 db: Database,
480- conversation: ConversationId,
480+ thread: ChatbotThreadId,
481481 // The two rows this turn just wrote; both are excluded from the history.
482- fresh: [ChatMessageId; 2],
482+ fresh: [ChatbotMessageId; 2],
483483 prompt: String,
484484 history_turns: usize,
485485 reply_cap: usize,
@@ -488,7 +488,7 @@ async fn answer_turn(
488488 let settled = match fetch_reply(
489489 &bridge,
490490 &db,
491- &conversation,
491+ &thread,
492492 &fresh,
493493 prompt,
494494 history_turns,
@@ -496,16 +496,16 @@ async fn answer_turn(
496496 )
497497 .await
498498 {
499- Ok((text, truncated)) => ChatMessage::complete(&answer_id, text, truncated, &db).await,
499+ Ok((text, truncated)) => ChatbotMessage::complete(&answer_id, text, truncated, &db).await,
500500 Err(code) => {
501501 tracing::warn!("chat answer {} failed: {code}", answer_id.key());
502- ChatMessage::fail(&answer_id, &code, &db).await
502+ ChatbotMessage::fail(&answer_id, &code, &db).await
503503 }
504504 };
505505 match settled {
506506 Ok(_) => {}
507507 // The row was no longer `pending`: the boot sweep or a stale-timeout
508- // already spoke for it, or the conversation was deleted mid-flight.
508+ // already spoke for it, or the thread was deleted mid-flight.
509509 // Benign — the user is not waiting on this row any more.
510510 Err(AppError::NotFound) => {
511511 tracing::info!("chat answer {} was already settled", answer_id.key());
@@ -518,13 +518,13 @@ async fn answer_turn(
518518 async fn fetch_reply(
519519 bridge: &AiBridge,
520520 db: &Database,
521- conversation: &ConversationId,
522- fresh: &[ChatMessageId; 2],
521+ thread: &ChatbotThreadId,
522+ fresh: &[ChatbotMessageId; 2],
523523 prompt: String,
524524 history_turns: usize,
525525 reply_cap: usize,
526526 ) -> Result<(ChatContent, bool), String> {
527- let history = match history_for(db, conversation, fresh, history_turns).await {
527+ let history = match history_for(db, thread, fresh, history_turns).await {
528528 Ok(history) => history,
529529 Err(err) => {
530530 tracing::warn!("could not load chat history: {err}");
@@ -571,21 +571,21 @@ async fn fetch_reply(
571571 Ok((content, truncated))
572572 }
573573
574-/// The tail of the conversation replayed to the service: oldest first, only
574+/// The tail of the thread replayed to the service: oldest first, only
575575 /// settled turns with text, and never the two rows this turn just wrote (the
576576 /// new prompt rides in `message`, the answer does not exist yet).
577577 async fn history_for(
578578 db: &Database,
579- conversation: &ConversationId,
580- fresh: &[ChatMessageId; 2],
579+ thread: &ChatbotThreadId,
580+ fresh: &[ChatbotMessageId; 2],
581581 turns: usize,
582582 ) -> Result<Vec<ChatTurn>, AppError> {
583583 // The query counts only settled rows with text, so a run of failed answers
584584 // makes the window reach *further back* instead of shrinking it — that is
585- // what "the last `chat_history_turns` settled turns" means. +2 so dropping
585+ // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping
586586 // this turn's own two rows cannot shorten it either (only the user one can
587587 // match: the assistant row is still `pending`).
588- let tail = ChatMessage::list_settled_tail(conversation, turns.saturating_add(2), db).await?;
588+ let tail = ChatbotMessage::list_settled_tail(thread, turns.saturating_add(2), db).await?;
589589 let mut history: Vec<ChatTurn> = tail
590590 .iter()
591591 .filter(|message| !fresh.contains(message.get_id()))
@@ -629,15 +629,15 @@ fn failure_code(err: AiError) -> String {
629629 /// so the two can never disagree about a turn's state.
630630 #[utoipa::path(
631631 get,
632- path = "/conversations/{id}/messages/{mid}",
633- tag = "chat",
632+ path = "/threads/{id}/messages/{mid}",
633+ tag = "chatbot",
634634 security(("session_cookie" = [])),
635635 params(
636- ("id" = String, Path, description = "Conversation id"),
636+ ("id" = String, Path, description = "ChatbotThread id"),
637637 ("mid" = String, Path, description = "Message id"),
638638 ),
639639 responses(
640- (status = 200, description = "The turn, in whatever state it is", body = ChatMessageResponse),
640+ (status = 200, description = "The turn, in whatever state it is", body = ChatbotMessageResponse),
641641 (status = 401, description = "Not authenticated", body = ErrorResponse),
642642 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
643643 ),
@@ -646,28 +646,28 @@ async fn read_message(
646646 State(st): State<AppState>,
647647 CurrentUser(user): CurrentUser,
648648 Path((id, mid)): Path<(String, String)>,
649-) -> Result<Json<ChatMessageResponse>, AppError> {
649+) -> Result<Json<ChatbotMessageResponse>, AppError> {
650650 let message = own_message(&id, &mid, user.get_id(), &st.db).await?;
651- Ok(Json(ChatMessageResponse::new(&message)))
651+ Ok(Json(ChatbotMessageResponse::new(&message)))
652652 }
653653
654654 /// Read one turn only if the caller owns it *and* it belongs to the named
655-/// conversation — a mismatched pair is a `404`, like a foreign one.
655+/// thread — a mismatched pair is a `404`, like a foreign one.
656656 async fn own_message(
657- conversation: &str,
657+ thread: &str,
658658 message: &str,
659659 user: &UserId,
660660 db: &Database,
661-) -> Result<ChatMessage, AppError> {
662- ChatMessage::read_for(&ChatMessageId::from_key(message), user, db)
661+) -> Result<ChatbotMessage, AppError> {
662+ ChatbotMessage::read_for(&ChatbotMessageId::from_key(message), user, db)
663663 .await?
664- .filter(|message| message.get_conversation_id().key() == conversation)
664+ .filter(|message| message.get_thread_id().key() == thread)
665665 .ok_or(AppError::NotFound)
666666 }
667667
668668 /// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a
669669 /// single `done` carrying the finished message, or one `error`. The stream
670-/// closes after `done`/`error` — one stream per turn, not per conversation.
670+/// closes after `done`/`error` — one stream per turn, not per thread.
671671 ///
672672 /// Works whatever state the turn is in when the stream opens: an answer that
673673 /// already landed replays as `delta`s and a `done` straight away, so a client
@@ -675,11 +675,11 @@ async fn own_message(
675675 /// (cookies ride along on same-site / credentialed requests).
676676 #[utoipa::path(
677677 get,
678- path = "/conversations/{id}/messages/{mid}/stream",
679- tag = "chat",
678+ path = "/threads/{id}/messages/{mid}/stream",
679+ tag = "chatbot",
680680 security(("session_cookie" = [])),
681681 params(
682- ("id" = String, Path, description = "Conversation id"),
682+ ("id" = String, Path, description = "ChatbotThread id"),
683683 ("mid" = String, Path, description = "Message id"),
684684 ),
685685 responses(
@@ -699,7 +699,7 @@ async fn stream_message(
699699
700700 let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2);
701701 let (message_id, user_id, db) = (
702- ChatMessageId::from_key(&mid),
702+ ChatbotMessageId::from_key(&mid),
703703 user.get_id().clone(),
704704 st.db.clone(),
705705 );
@@ -719,7 +719,7 @@ async fn stream_message(
719719 _ = ticker.tick() => {}
720720 _ = tx.closed() => return,
721721 }
722- let message = match ChatMessage::read_for(&message_id, &user_id, &db).await {
722+ let message = match ChatbotMessage::read_for(&message_id, &user_id, &db).await {
723723 Ok(Some(message)) => message,
724724 // Deleted mid-stream (the thread went away) — say so and stop.
725725 Ok(None) => {
@@ -744,7 +744,7 @@ async fn stream_message(
744744 return;
745745 }
746746 }
747- let done = json!({ "message": ChatMessageResponse::new(&message) });
747+ let done = json!({ "message": ChatbotMessageResponse::new(&message) });
748748 let _ = send(&tx, "done", done).await;
749749 return;
750750 }
@@ -845,43 +845,43 @@ mod tests {
845845 // shrink it: filtering a fixed-size tail after the fact handed the
846846 // service a handful of unanswered prompts and nothing older.
847847 let db = crate::database::init_mem().await.unwrap();
848- let conversation = ConversationId::from_key("c");
848+ let thread = ChatbotThreadId::from_key("c");
849849 let user = UserId::from_key("u");
850850 let say = |text: String| ChatContent::try_new(&text).unwrap();
851851
852852 for turn in 0..10 {
853- ChatMessage::append_user(&conversation, &user, say(format!("soru {turn}")), &db)
853+ ChatbotMessage::append_user(&thread, &user, say(format!("soru {turn}")), &db)
854854 .await
855855 .unwrap();
856- let answer = ChatMessage::append_pending_assistant(&conversation, &user, &db)
856+ let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
857857 .await
858858 .unwrap();
859- ChatMessage::complete(answer.get_id(), say(format!("cevap {turn}")), false, &db)
859+ ChatbotMessage::complete(answer.get_id(), say(format!("cevap {turn}")), false, &db)
860860 .await
861861 .unwrap();
862862 }
863863 // Five turns in a row whose answer never landed.
864864 for turn in 0..5 {
865- ChatMessage::append_user(&conversation, &user, say(format!("kayıp {turn}")), &db)
865+ ChatbotMessage::append_user(&thread, &user, say(format!("kayıp {turn}")), &db)
866866 .await
867867 .unwrap();
868- let answer = ChatMessage::append_pending_assistant(&conversation, &user, &db)
868+ let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
869869 .await
870870 .unwrap();
871- ChatMessage::fail(answer.get_id(), "timed_out", &db)
871+ ChatbotMessage::fail(answer.get_id(), "timed_out", &db)
872872 .await
873873 .unwrap();
874874 }
875875 // And this turn's own two rows, which never belong in the history.
876- let prompt = ChatMessage::append_user(&conversation, &user, say("yeni".into()), &db)
876+ let prompt = ChatbotMessage::append_user(&thread, &user, say("yeni".into()), &db)
877877 .await
878878 .unwrap();
879- let pending = ChatMessage::append_pending_assistant(&conversation, &user, &db)
879+ let pending = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
880880 .await
881881 .unwrap();
882882 let fresh = [prompt.get_id().clone(), pending.get_id().clone()];
883883
884- let history = history_for(&db, &conversation, &fresh, 6).await.unwrap();
884+ let history = history_for(&db, &thread, &fresh, 6).await.unwrap();
885885 let texts: Vec<&str> = history.iter().map(|turn| turn.content.as_str()).collect();
886886 assert_eq!(
887887 texts,
src/web/mod.rsmodified+1 -1
@@ -7,7 +7,7 @@ pub mod ai;
77 pub mod appointments;
88 pub mod attendance;
99 pub mod auth;
10-pub mod chat;
10+pub mod chatbot;
1111 pub mod courses;
1212 pub mod events;
1313 pub mod exam_ws;
src/web/settings.rsmodified+21 -21
@@ -65,15 +65,15 @@ struct SettingsResponse {
6565 /// Per-file size limit for note uploads, in bytes.
6666 #[schema(example = 5_242_880)]
6767 max_file_bytes: i64,
68- /// How many prior turns of a conversation the chatbot is given as context.
68+ /// How many prior turns of a thread the chatbot is given as context.
6969 #[schema(example = 10)]
70- chat_history_turns: i64,
71- /// How many chatbot conversations one user may keep.
70+ chatbot_history_turns: i64,
71+ /// How many chatbot threads one user may keep.
7272 #[schema(example = 50)]
73- max_chat_conversations: i64,
73+ max_chatbot_threads: i64,
7474 /// Character limit on one chat message.
7575 #[schema(example = 4000)]
76- max_chat_message_len: i64,
76+ max_chatbot_message_len: i64,
7777 }
7878
7979 impl SettingsResponse {
@@ -97,9 +97,9 @@ impl SettingsResponse {
9797 })
9898 .collect(),
9999 max_file_bytes: settings.get_max_file_bytes(),
100- chat_history_turns: settings.get_chat_history_turns(),
101- max_chat_conversations: settings.get_max_chat_conversations(),
102- max_chat_message_len: settings.get_max_chat_message_len(),
100+ chatbot_history_turns: settings.get_chatbot_history_turns(),
101+ max_chatbot_threads: settings.get_max_chatbot_threads(),
102+ max_chatbot_message_len: settings.get_max_chatbot_message_len(),
103103 }
104104 }
105105 }
@@ -119,18 +119,18 @@ struct UpdateSettings {
119119 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.
120120 #[schema(example = 5_242_880)]
121121 max_file_bytes: Option<i64>,
122- /// How many prior turns of a conversation the chatbot is given as context,
122+ /// How many prior turns of a thread the chatbot is given as context,
123123 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.
124124 #[schema(example = 10)]
125- chat_history_turns: Option<i64>,
126- /// How many chatbot conversations one user may keep, `1`–`500`. At the cap
127- /// the user deletes an old conversation before starting a new one.
125+ chatbot_history_turns: Option<i64>,
126+ /// How many chatbot threads one user may keep, `1`–`500`. At the cap
127+ /// the user deletes an old thread before starting a new one.
128128 #[schema(example = 50)]
129- max_chat_conversations: Option<i64>,
129+ max_chatbot_threads: Option<i64>,
130130 /// Character limit on one chat message, `100`–`8000`. The ceiling is a
131131 /// server hard cap.
132132 #[schema(example = 4000)]
133- max_chat_message_len: Option<i64>,
133+ max_chatbot_message_len: Option<i64>,
134134 }
135135
136136 /// The school's current policy. Any authenticated user — clients need it to
@@ -239,13 +239,13 @@ async fn update_settings(
239239 params.attendance_statuses = attendance_statuses;
240240 params.grade_bands = grade_bands;
241241 params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes);
242- params.chat_history_turns = req.chat_history_turns.unwrap_or(params.chat_history_turns);
243- params.max_chat_conversations = req
244- .max_chat_conversations
245- .unwrap_or(params.max_chat_conversations);
246- params.max_chat_message_len = req
247- .max_chat_message_len
248- .unwrap_or(params.max_chat_message_len);
242+ params.chatbot_history_turns = req.chatbot_history_turns.unwrap_or(params.chatbot_history_turns);
243+ params.max_chatbot_threads = req
244+ .max_chatbot_threads
245+ .unwrap_or(params.max_chatbot_threads);
246+ params.max_chatbot_message_len = req
247+ .max_chatbot_message_len
248+ .unwrap_or(params.max_chatbot_message_len);
249249
250250 let settings = Settings::try_new(params)?;
251251 if let Some(saved) = settings.save_if_unchanged(&current, &st.db).await? {
tests/ai_bridge.rsmodified+28 -28
@@ -805,7 +805,7 @@ async fn fetch_certificate(ai: Option<AiBridge>) -> (axum::http::StatusCode, Val
805805 files_path: std::env::temp_dir(),
806806 cookie_secure: false,
807807 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
808- chat_limit: Default::default(),
808+ chatbot_limit: Default::default(),
809809 exam_presence: Default::default(),
810810 db_up: Default::default(),
811811 ai,
@@ -924,7 +924,7 @@ fn payloads_are_opaque(v: Value) -> Value {
924924
925925 use axum::Router;
926926 use axum::http::StatusCode;
927-use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHAT_MESSAGE_LEN};
927+use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHATBOT_MESSAGE_LEN};
928928 use hezarfen_backend::database::Database;
929929 use surrealdb::types::RecordId;
930930
@@ -938,7 +938,7 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) {
938938 files_path: common::files_dir(),
939939 cookie_secure: false,
940940 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
941- chat_limit: Default::default(),
941+ chatbot_limit: Default::default(),
942942 exam_presence: Default::default(),
943943 db_up: Default::default(),
944944 ai: Some(bridge.clone()),
@@ -952,7 +952,7 @@ async fn chat_user(app: &Router, name: &str) -> (String, String) {
952952 let res = common::send(
953953 app,
954954 "POST",
955- "/chat/conversations",
955+ "/chatbot/threads",
956956 Some(&cookie),
957957 Some(json!({})),
958958 )
@@ -963,11 +963,11 @@ async fn chat_user(app: &Router, name: &str) -> (String, String) {
963963 }
964964
965965 /// Ask one question (asserts `202`) and return the reserved assistant row's id.
966-async fn ask(app: &Router, cookie: &str, conversation: &str, text: &str) -> String {
966+async fn ask(app: &Router, cookie: &str, thread: &str, text: &str) -> String {
967967 let res = common::send(
968968 app,
969969 "POST",
970- &format!("/chat/conversations/{conversation}/messages"),
970+ &format!("/chatbot/threads/{thread}/messages"),
971971 Some(cookie),
972972 Some(json!({ "content": text })),
973973 )
@@ -982,12 +982,12 @@ async fn ask(app: &Router, cookie: &str, conversation: &str, text: &str) -> Stri
982982
983983 /// Poll a turn until it leaves `pending`. Bounded polling rather than a sleep
984984 /// sized to the answering task: the round trip settles when it settles.
985-async fn settled(app: &Router, cookie: &str, conversation: &str, mid: &str) -> Value {
985+async fn settled(app: &Router, cookie: &str, thread: &str, mid: &str) -> Value {
986986 for _ in 0..500 {
987987 let res = common::send(
988988 app,
989989 "GET",
990- &format!("/chat/conversations/{conversation}/messages/{mid}"),
990+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
991991 Some(cookie),
992992 None,
993993 )
@@ -1012,10 +1012,10 @@ async fn a_chat_turn_settles_complete_with_the_services_text() {
10121012 .await;
10131013 await_workers(&bridge, 1).await;
10141014 let (app, _db) = chat_app(&bridge).await;
1015- let (cookie, conversation) = chat_user(&app, "ali").await;
1015+ let (cookie, thread) = chat_user(&app, "ali").await;
10161016
1017- let mid = ask(&app, &cookie, &conversation, "ikinci yasa nedir?").await;
1018- let turn = settled(&app, &cookie, &conversation, &mid).await;
1017+ let mid = ask(&app, &cookie, &thread, "ikinci yasa nedir?").await;
1018+ let turn = settled(&app, &cookie, &thread, &mid).await;
10191019 assert_eq!(turn["status"], "complete", "{turn}");
10201020 assert_eq!(turn["content"], "F = ma");
10211021 assert_eq!(turn["role"], "assistant");
@@ -1050,28 +1050,28 @@ async fn the_history_a_service_receives_is_oldest_first_without_the_new_turn() {
10501050 .await;
10511051 await_workers(&bridge, 1).await;
10521052 let (app, db) = chat_app(&bridge).await;
1053- let (cookie, conversation) = chat_user(&app, "ali").await;
1053+ let (cookie, thread) = chat_user(&app, "ali").await;
10541054 let user = common::me_id(&app, &cookie).await;
10551055
1056- let first = ask(&app, &cookie, &conversation, "birinci soru").await;
1056+ let first = ask(&app, &cookie, &thread, "birinci soru").await;
10571057 assert_eq!(
1058- settled(&app, &cookie, &conversation, &first).await["status"],
1058+ settled(&app, &cookie, &thread, &first).await["status"],
10591059 "complete"
10601060 );
10611061
10621062 db.query(
1063- "CREATE chat_message:h3 SET conversation_id = $conv, user_id = $usr, role = 'assistant',
1063+ "CREATE chatbot_message:h3 SET thread_id = $conv, user_id = $usr, role = 'assistant',
10641064 content = '', status = 'pending', created_at = 1002;",
10651065 )
1066- .bind(("conv", RecordId::new("conversation", conversation.as_str())))
1066+ .bind(("conv", RecordId::new("chatbot_thread", thread.as_str())))
10671067 .bind(("usr", RecordId::new("user", user.as_str())))
10681068 .await
10691069 .expect("seed history")
10701070 .check()
10711071 .expect("seed history");
10721072
1073- let mid = ask(&app, &cookie, &conversation, "ikinci soru").await;
1074- let turn = settled(&app, &cookie, &conversation, &mid).await;
1073+ let mid = ask(&app, &cookie, &thread, "ikinci soru").await;
1074+ let turn = settled(&app, &cookie, &thread, &mid).await;
10751075 assert_eq!(turn["status"], "complete", "{turn}");
10761076
10771077 let seen = service.seen();
@@ -1103,10 +1103,10 @@ async fn a_refused_chat_turn_carries_the_services_own_error_code() {
11031103 .await;
11041104 await_workers(&bridge, 1).await;
11051105 let (app, _db) = chat_app(&bridge).await;
1106- let (cookie, conversation) = chat_user(&app, "ali").await;
1106+ let (cookie, thread) = chat_user(&app, "ali").await;
11071107
1108- let mid = ask(&app, &cookie, &conversation, "bir soru").await;
1109- let turn = settled(&app, &cookie, &conversation, &mid).await;
1108+ let mid = ask(&app, &cookie, &thread, "bir soru").await;
1109+ let turn = settled(&app, &cookie, &thread, &mid).await;
11101110 assert_eq!(turn["status"], "failed", "{turn}");
11111111 assert_eq!(turn["error_code"], "quota_exhausted");
11121112 assert_eq!(turn["content"], "", "a failed turn shows no text");
@@ -1120,7 +1120,7 @@ async fn an_over_long_chat_answer_is_clipped_rather_than_failed() {
11201120 // truncated (a clipped answer still helps), and on a character boundary —
11211121 // a byte-wise clip of a multi-byte script would render as garbage. The cut
11221122 // is flagged, so the UI never passes a clipped answer off as the whole one.
1123- let cap = DEFAULT_MAX_CHAT_MESSAGE_LEN as usize;
1123+ let cap = DEFAULT_MAX_CHATBOT_MESSAGE_LEN as usize;
11241124 let bridge = bridge().await;
11251125 let _service = connect_service(
11261126 &bridge,
@@ -1130,10 +1130,10 @@ async fn an_over_long_chat_answer_is_clipped_rather_than_failed() {
11301130 .await;
11311131 await_workers(&bridge, 1).await;
11321132 let (app, _db) = chat_app(&bridge).await;
1133- let (cookie, conversation) = chat_user(&app, "ali").await;
1133+ let (cookie, thread) = chat_user(&app, "ali").await;
11341134
1135- let mid = ask(&app, &cookie, &conversation, "uzun cevap ver").await;
1136- let turn = settled(&app, &cookie, &conversation, &mid).await;
1135+ let mid = ask(&app, &cookie, &thread, "uzun cevap ver").await;
1136+ let turn = settled(&app, &cookie, &thread, &mid).await;
11371137 assert_eq!(turn["status"], "complete", "{turn}");
11381138 let text = turn["content"].as_str().expect("content");
11391139 assert_eq!(text.chars().count(), cap);
@@ -1154,10 +1154,10 @@ async fn a_blank_chat_answer_fails_as_empty_reply() {
11541154 .await;
11551155 await_workers(&bridge, 1).await;
11561156 let (app, _db) = chat_app(&bridge).await;
1157- let (cookie, conversation) = chat_user(&app, "ali").await;
1157+ let (cookie, thread) = chat_user(&app, "ali").await;
11581158
1159- let mid = ask(&app, &cookie, &conversation, "bir soru").await;
1160- let turn = settled(&app, &cookie, &conversation, &mid).await;
1159+ let mid = ask(&app, &cookie, &thread, "bir soru").await;
1160+ let turn = settled(&app, &cookie, &thread, &mid).await;
11611161 assert_eq!(turn["status"], "failed", "{turn}");
11621162 assert_eq!(turn["error_code"], "empty_reply");
11631163 }
tests/common/mod.rsmodified+1 -1
@@ -47,7 +47,7 @@ pub async fn app_and_db() -> (Router, Database) {
4747 // Off, so suites hammering the API never trip a limit; the dedicated
4848 // `rate_limit` test binary opts into tight configs on purpose.
4949 rate_limit: RateLimitConfig::unlimited(),
50- chat_limit: Default::default(),
50+ chatbot_limit: Default::default(),
5151 exam_presence: Default::default(),
5252 db_up: Default::default(),
5353 ai: None,
tests/e2e.rsmodified+14 -14
@@ -27,7 +27,7 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St
2727 // Every request here comes from 127.0.0.1, so per-IP limits would
2828 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
2929 rate_limit: RateLimitConfig::unlimited(),
30- chat_limit: Default::default(),
30+ chatbot_limit: Default::default(),
3131 exam_presence: Default::default(),
3232 db_up: Default::default(),
3333 ai,
@@ -1936,7 +1936,7 @@ async fn chat_service(text: &str) -> ChatService {
19361936 /// Open a thread and ask one question. Returns (thread id, reserved answer id).
19371937 async fn ask(client: &Client, base: &str) -> (String, String) {
19381938 let thread: Value = client
1939- .post(format!("{base}/chat/conversations"))
1939+ .post(format!("{base}/chatbot/threads"))
19401940 .json(&json!({ "title": "Fizik" }))
19411941 .send()
19421942 .await
@@ -1944,10 +1944,10 @@ async fn ask(client: &Client, base: &str) -> (String, String) {
19441944 .json()
19451945 .await
19461946 .unwrap();
1947- let conversation = thread["id"].as_str().expect("thread id").to_string();
1947+ let thread = thread["id"].as_str().expect("thread id").to_string();
19481948
19491949 let res = client
1950- .post(format!("{base}/chat/conversations/{conversation}/messages"))
1950+ .post(format!("{base}/chatbot/threads/{thread}/messages"))
19511951 .json(&json!({ "content": "ikinci yasa nedir?" }))
19521952 .send()
19531953 .await
@@ -1959,7 +1959,7 @@ async fn ask(client: &Client, base: &str) -> (String, String) {
19591959 .as_str()
19601960 .expect("message id")
19611961 .to_string();
1962- (conversation, mid)
1962+ (thread, mid)
19631963 }
19641964
19651965 /// Read the SSE stream until its terminal event (`done` or `error`), returning
@@ -2036,18 +2036,18 @@ fn assert_deltas_then_done(events: &[(String, Value)], mid: &str, answer: &str)
20362036 /// must reach the same conclusion about the very same turn.
20372037 #[tokio::test]
20382038 async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {
2039- let cap = hezarfen_backend::constant::DEFAULT_MAX_CHAT_MESSAGE_LEN as usize;
2039+ let cap = hezarfen_backend::constant::DEFAULT_MAX_CHATBOT_MESSAGE_LEN as usize;
20402040 let service = chat_service(&"é".repeat(cap + 500)).await;
20412041 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
20422042 let ali = client();
20432043 register(&ali, &base, "ali").await;
20442044 login(&ali, &base, "ali").await;
20452045
2046- let (conversation, mid) = ask(&ali, &base).await;
2046+ let (thread, mid) = ask(&ali, &base).await;
20472047
20482048 let mut res = ali
20492049 .get(format!(
2050- "{base}/chat/conversations/{conversation}/messages/{mid}/stream"
2050+ "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
20512051 ))
20522052 .send()
20532053 .await
@@ -2071,7 +2071,7 @@ async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {
20712071 // The same row, read the other way: identical verdict, field for field.
20722072 let polled: Value = ali
20732073 .get(format!(
2074- "{base}/chat/conversations/{conversation}/messages/{mid}"
2074+ "{base}/chatbot/threads/{thread}/messages/{mid}"
20752075 ))
20762076 .send()
20772077 .await
@@ -2091,13 +2091,13 @@ async fn chat_stream_delivers_deltas_then_done_over_http() {
20912091 register(&ali, &base, "ali").await;
20922092 login(&ali, &base, "ali").await;
20932093
2094- let (conversation, mid) = ask(&ali, &base).await;
2094+ let (thread, mid) = ask(&ali, &base).await;
20952095
20962096 // The client opens the stream while the turn is still in flight; it stays
20972097 // open until the answer lands, then closes after `done`.
20982098 let mut res = ali
20992099 .get(format!(
2100- "{base}/chat/conversations/{conversation}/messages/{mid}/stream"
2100+ "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
21012101 ))
21022102 .send()
21032103 .await
@@ -2137,7 +2137,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
21372137 register(&ali, &base, "ali").await;
21382138 login(&ali, &base, "ali").await;
21392139
2140- let (conversation, mid) = ask(&ali, &base).await;
2140+ let (thread, mid) = ask(&ali, &base).await;
21412141
21422142 // Wait — by polling, never by sleeping — until the turn has settled, so the
21432143 // stream below opens strictly after the answer landed.
@@ -2145,7 +2145,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
21452145 for _ in 0..500 {
21462146 let turn: Value = ali
21472147 .get(format!(
2148- "{base}/chat/conversations/{conversation}/messages/{mid}"
2148+ "{base}/chatbot/threads/{thread}/messages/{mid}"
21492149 ))
21502150 .send()
21512151 .await
@@ -2164,7 +2164,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
21642164
21652165 let mut res = ali
21662166 .get(format!(
2167- "{base}/chat/conversations/{conversation}/messages/{mid}/stream"
2167+ "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
21682168 ))
21692169 .send()
21702170 .await
tests/integration.rsmodified+79 -79
@@ -9,8 +9,8 @@ use common::{
99 app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session,
1010 create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,
1111 };
12-use hezarfen_backend::domain::chat_message::ChatMessage;
13-use hezarfen_backend::domain::conversation::ConversationId;
12+use hezarfen_backend::domain::chatbot_message::ChatbotMessage;
13+use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;
1414 use hezarfen_backend::domain::exam::ExamId;
1515 use hezarfen_backend::domain::exam_attempt::ExamAttempt;
1616 use hezarfen_backend::domain::session::Session;
@@ -5224,7 +5224,7 @@ async fn session_cookie_secure_attribute_follows_config() {
52245224 files_path: common::files_dir(),
52255225 cookie_secure: true,
52265226 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
5227- chat_limit: Default::default(),
5227+ chatbot_limit: Default::default(),
52285228 exam_presence: Default::default(),
52295229 db_up: Default::default(),
52305230 ai: None,
@@ -5263,7 +5263,7 @@ async fn db_down_refuses_before_touching_the_database() {
52635263 files_path: common::files_dir(),
52645264 cookie_secure: false,
52655265 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
5266- chat_limit: Default::default(),
5266+ chatbot_limit: Default::default(),
52675267 exam_presence: Default::default(),
52685268 db_up: db_up.clone(),
52695269 ai: None,
@@ -14616,10 +14616,10 @@ async fn chat_app(ai: Option<AiBridge>) -> (axum::Router, Database) {
1461614616 }
1461714617
1461814618 /// The same, with an explicit per-user chat tier — what
14619-/// `RATE_LIMIT_CHAT_PER_MINUTE` configures in production.
14619+/// `RATE_LIMIT_CHATBOT_PER_MINUTE` configures in production.
1462014620 async fn chat_app_limited(
1462114621 ai: Option<AiBridge>,
14622- chat_limit: hezarfen_backend::rate_limit::UserRateLimiter,
14622+ chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter,
1462314623 ) -> (axum::Router, Database) {
1462414624 let db = database::init_mem().await.expect("in-memory db");
1462514625 let app = build_router(AppState {
@@ -14627,7 +14627,7 @@ async fn chat_app_limited(
1462714627 files_path: common::files_dir(),
1462814628 cookie_secure: false,
1462914629 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
14630- chat_limit,
14630+ chatbot_limit,
1463114631 exam_presence: Default::default(),
1463214632 db_up: Default::default(),
1463314633 ai,
@@ -14635,17 +14635,17 @@ async fn chat_app_limited(
1463514635 (app, db)
1463614636 }
1463714637
14638-/// How many `conversation` and `chat_message` rows exist, anywhere.
14638+/// How many `thread` and `chatbot_message` rows exist, anywhere.
1463914639 async fn chat_rows(db: &Database) -> (usize, usize) {
1464014640 let mut res = db
14641- .query("SELECT VALUE id FROM conversation; SELECT VALUE id FROM chat_message;")
14641+ .query("SELECT VALUE id FROM chatbot_thread; SELECT VALUE id FROM chatbot_message;")
1464214642 .await
1464314643 .expect("count query")
1464414644 .check()
1464514645 .expect("count check");
14646- let conversations: Vec<surrealdb::types::RecordId> = res.take(0).expect("conversation ids");
14647- let messages: Vec<surrealdb::types::RecordId> = res.take(1).expect("chat_message ids");
14648- (conversations.len(), messages.len())
14646+ let threads: Vec<surrealdb::types::RecordId> = res.take(0).expect("thread ids");
14647+ let messages: Vec<surrealdb::types::RecordId> = res.take(1).expect("chatbot_message ids");
14648+ (threads.len(), messages.len())
1464914649 }
1465014650
1465114651 /// Open a thread (asserts 201) and return its id.
@@ -14653,7 +14653,7 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String {
1465314653 let res = send(
1465414654 app,
1465514655 "POST",
14656- "/chat/conversations",
14656+ "/chatbot/threads",
1465714657 Some(cookie),
1465814658 Some(json!({})),
1465914659 )
@@ -14665,13 +14665,13 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String {
1466514665 async fn post_turn(
1466614666 app: &axum::Router,
1466714667 cookie: &str,
14668- conversation: &str,
14668+ thread: &str,
1466914669 content: &str,
1467014670 ) -> common::Res {
1467114671 send(
1467214672 app,
1467314673 "POST",
14674- &format!("/chat/conversations/{conversation}/messages"),
14674+ &format!("/chatbot/threads/{thread}/messages"),
1467514675 Some(cookie),
1467614676 Some(json!({ "content": content })),
1467714677 )
@@ -14683,13 +14683,13 @@ async fn post_turn(
1468314683 async fn open_stream(
1468414684 app: &axum::Router,
1468514685 cookie: &str,
14686- conversation: &str,
14686+ thread: &str,
1468714687 mid: &str,
1468814688 ) -> StatusCode {
1468914689 let request = Request::builder()
1469014690 .method("GET")
1469114691 .uri(format!(
14692- "/chat/conversations/{conversation}/messages/{mid}/stream"
14692+ "/chatbot/threads/{thread}/messages/{mid}/stream"
1469314693 ))
1469414694 .header("cookie", cookie)
1469514695 .body(Body::empty())
@@ -14706,7 +14706,7 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
1470614706 let res = send(
1470714707 &app,
1470814708 "POST",
14709- "/chat/conversations",
14709+ "/chatbot/threads",
1471014710 Some(&cookie),
1471114711 Some(json!({ "title": "Fizik" })),
1471214712 )
@@ -14715,11 +14715,11 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
1471514715 assert_eq!(res.body["title"], "Fizik");
1471614716 assert!(res.body["created_at"].is_i64(), "{}", res.body);
1471714717 assert!(res.body["updated_at"].is_i64(), "{}", res.body);
14718- let conversation = id_of(&res.body);
14718+ let thread = id_of(&res.body);
1471914719
1472014720 // The receipt: the reserved row's id and nothing else. The answer is not
1472114721 // here — it is being fetched.
14722- let res = post_turn(&app, &cookie, &conversation, "ikinci yasa nedir?").await;
14722+ let res = post_turn(&app, &cookie, &thread, "ikinci yasa nedir?").await;
1472314723 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
1472414724 assert_eq!(res.body["status"], "pending");
1472514725 let mid = res.body["message_id"].as_str().expect("message_id");
@@ -14736,13 +14736,13 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
1473614736 let res = send(
1473714737 &app,
1473814738 "GET",
14739- &format!("/chat/conversations/{conversation}/messages/{mid}"),
14739+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
1474014740 Some(&cookie),
1474114741 None,
1474214742 )
1474314743 .await;
1474414744 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
14745- assert_eq!(res.body["conversation_id"], conversation);
14745+ assert_eq!(res.body["thread_id"], thread);
1474614746 assert_eq!(res.body["role"], "assistant");
1474714747 assert_eq!(res.body["status"], "pending");
1474814748 assert_eq!(res.body["content"], "");
@@ -14756,7 +14756,7 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
1475614756 let res = send(
1475714757 &app,
1475814758 "GET",
14759- &format!("/chat/conversations/{conversation}/messages"),
14759+ &format!("/chatbot/threads/{thread}/messages"),
1476014760 Some(&cookie),
1476114761 None,
1476214762 )
@@ -14788,9 +14788,9 @@ async fn chat_send_without_a_service_is_503_and_writes_nothing() {
1478814788 for ai in [None, Some(idle)] {
1478914789 let (app, db) = chat_app(ai).await;
1479014790 let cookie = login(&app, "ali").await;
14791- let conversation = new_thread(&app, &cookie).await;
14791+ let thread = new_thread(&app, &cookie).await;
1479214792
14793- let res = post_turn(&app, &cookie, &conversation, "bir soru").await;
14793+ let res = post_turn(&app, &cookie, &thread, "bir soru").await;
1479414794 assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
1479514795 assert!(
1479614796 res.body["error"]
@@ -14826,8 +14826,8 @@ async fn chat_lists_are_paged() {
1482614826 // list. Order is compared element for element: the id tie-break makes it
1482714827 // deterministic even for the two rows one POST writes in a millisecond.
1482814828 for (uri, expected) in [
14829- ("/chat/conversations".to_string(), 3),
14830- (format!("/chat/conversations/{}/messages", threads[0]), 6),
14829+ ("/chatbot/threads".to_string(), 3),
14830+ (format!("/chatbot/threads/{}/messages", threads[0]), 6),
1483114831 ] {
1483214832 let res = send(
1483314833 &app,
@@ -14895,8 +14895,8 @@ async fn chat_threads_are_invisible_to_everyone_else() {
1489514895 let ai = chat_bridge().await;
1489614896 let (app, db) = chat_app(Some(ai.bridge.clone())).await;
1489714897 let ali = login(&app, "ali").await;
14898- let conversation = new_thread(&app, &ali).await;
14899- let res = post_turn(&app, &ali, &conversation, "bir soru").await;
14898+ let thread = new_thread(&app, &ali).await;
14899+ let res = post_turn(&app, &ali, &thread, "bir soru").await;
1490014900 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
1490114901 let mid = res.body["message_id"].as_str().unwrap().to_string();
1490214902
@@ -14909,21 +14909,21 @@ async fn chat_threads_are_invisible_to_everyone_else() {
1490914909 for (method, uri) in [
1491014910 (
1491114911 "GET",
14912- format!("/chat/conversations/{conversation}/messages"),
14912+ format!("/chatbot/threads/{thread}/messages"),
1491314913 ),
1491414914 (
1491514915 "GET",
14916- format!("/chat/conversations/{conversation}/messages/{mid}"),
14916+ format!("/chatbot/threads/{thread}/messages/{mid}"),
1491714917 ),
1491814918 (
1491914919 "GET",
14920- format!("/chat/conversations/{conversation}/messages/{mid}/stream"),
14920+ format!("/chatbot/threads/{thread}/messages/{mid}/stream"),
1492114921 ),
14922- ("DELETE", format!("/chat/conversations/{conversation}")),
14923- ("PATCH", format!("/chat/conversations/{conversation}")),
14922+ ("DELETE", format!("/chatbot/threads/{thread}")),
14923+ ("PATCH", format!("/chatbot/threads/{thread}")),
1492414924 (
1492514925 "POST",
14926- format!("/chat/conversations/{conversation}/messages"),
14926+ format!("/chatbot/threads/{thread}/messages"),
1492714927 ),
1492814928 ] {
1492914929 let body = match method {
@@ -14935,13 +14935,13 @@ async fn chat_threads_are_invisible_to_everyone_else() {
1493514935 assert_eq!(res.status, StatusCode::NOT_FOUND, "{name} {method} {uri}");
1493614936 }
1493714937 // Nor does someone else's thread show up in their own list.
14938- let res = send(&app, "GET", "/chat/conversations", Some(&other), None).await;
14938+ let res = send(&app, "GET", "/chatbot/threads", Some(&other), None).await;
1493914939 assert!(common::items(&res.body).is_empty(), "{}", res.body);
1494014940 }
1494114941
1494214942 // And the owner still has everything, untouched.
1494314943 assert_eq!(chat_rows(&db).await, (1, 2));
14944- let res = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;
14944+ let res = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
1494514945 assert_eq!(common::items(&res.body).len(), 1, "{}", res.body);
1494614946 }
1494714947
@@ -14954,7 +14954,7 @@ async fn chat_thread_count_is_capped_by_the_school() {
1495414954 "PATCH",
1495514955 "/settings",
1495614956 Some(&manager),
14957- Some(json!({ "max_chat_conversations": 1 })),
14957+ Some(json!({ "max_chatbot_threads": 1 })),
1495814958 )
1495914959 .await;
1496014960 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -14964,7 +14964,7 @@ async fn chat_thread_count_is_capped_by_the_school() {
1496414964 let res = send(
1496514965 &app,
1496614966 "POST",
14967- "/chat/conversations",
14967+ "/chatbot/threads",
1496814968 Some(&ali),
1496914969 Some(json!({})),
1497014970 )
@@ -14979,7 +14979,7 @@ async fn chat_thread_count_is_capped_by_the_school() {
1497914979 let res = send(
1498014980 &app,
1498114981 "DELETE",
14982- &format!("/chat/conversations/{first}"),
14982+ &format!("/chatbot/threads/{first}"),
1498314983 Some(&ali),
1498414984 None,
1498514985 )
@@ -15004,7 +15004,7 @@ async fn concurrent_thread_creation_never_passes_the_cap() {
1500415004 "PATCH",
1500515005 "/settings",
1500615006 Some(&manager),
15007- Some(json!({ "max_chat_conversations": CAP })),
15007+ Some(json!({ "max_chatbot_threads": CAP })),
1500815008 )
1500915009 .await;
1501015010 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -15021,7 +15021,7 @@ async fn concurrent_thread_creation_never_passes_the_cap() {
1502115021 send(
1502215022 &app,
1502315023 "POST",
15024- "/chat/conversations",
15024+ "/chatbot/threads",
1502515025 Some(&cookie),
1502615026 Some(json!({})),
1502715027 )
@@ -15054,18 +15054,18 @@ async fn chat_turn_stamps_thread_activity() {
1505415054 let ai = chat_bridge().await;
1505515055 let (app, _db) = chat_app(Some(ai.bridge.clone())).await;
1505615056 let ali = login(&app, "ali").await;
15057- let conversation = new_thread(&app, &ali).await;
15058- let before = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;
15057+ let thread = new_thread(&app, &ali).await;
15058+ let before = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
1505915059 let opened = common::items(&before.body)[0]["updated_at"]
1506015060 .as_i64()
1506115061 .unwrap();
1506215062
1506315063 // The stamp is in whole milliseconds; make sure the clock has moved.
1506415064 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
15065- let res = post_turn(&app, &ali, &conversation, "bir soru").await;
15065+ let res = post_turn(&app, &ali, &thread, "bir soru").await;
1506615066 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
1506715067
15068- let after = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;
15068+ let after = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
1506915069 let stamped = common::items(&after.body)[0]["updated_at"]
1507015070 .as_i64()
1507115071 .unwrap();
@@ -15083,11 +15083,11 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() {
1508315083 // count below is not drowned in the QUIC service's task churn.
1508415084 let (app, db) = chat_app(None).await;
1508515085 let ali = login(&app, "ali").await;
15086- let conversation = new_thread(&app, &ali).await;
15086+ let thread = new_thread(&app, &ali).await;
1508715087 let me = send(&app, "GET", "/auth/me", Some(&ali), None).await;
1508815088 let user = UserId::from_key(me.body["id"].as_str().unwrap());
1508915089 let pending =
15090- ChatMessage::append_pending_assistant(&ConversationId::from_key(&conversation), &user, &db)
15090+ ChatbotMessage::append_pending_assistant(&ChatbotThreadId::from_key(&thread), &user, &db)
1509115091 .await
1509215092 .expect("reserve an assistant row");
1509315093 let mid = pending.get_id().key().to_string();
@@ -15108,7 +15108,7 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() {
1510815108 let request = Request::builder()
1510915109 .method("GET")
1511015110 .uri(format!(
15111- "/chat/conversations/{conversation}/messages/{mid}/stream"
15111+ "/chatbot/threads/{thread}/messages/{mid}/stream"
1511215112 ))
1511315113 .header("cookie", &ali)
1511415114 .body(Body::empty())
@@ -15140,25 +15140,25 @@ async fn chat_content_is_required_and_capped_by_the_school() {
1514015140 "PATCH",
1514115141 "/settings",
1514215142 Some(&manager),
15143- Some(json!({ "max_chat_message_len": 100 })),
15143+ Some(json!({ "max_chatbot_message_len": 100 })),
1514415144 )
1514515145 .await;
1514615146 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1514715147
1514815148 let ali = login(&app, "ali").await;
15149- let conversation = new_thread(&app, &ali).await;
15149+ let thread = new_thread(&app, &ali).await;
1515015150
1515115151 for empty in ["", " ", "\n\t"] {
15152- let res = post_turn(&app, &ali, &conversation, empty).await;
15152+ let res = post_turn(&app, &ali, &thread, empty).await;
1515315153 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{empty:?} accepted");
1515415154 }
1515515155 // Counted in characters, not bytes: 101 multi-byte characters is 101.
15156- let res = post_turn(&app, &ali, &conversation, &"é".repeat(101)).await;
15156+ let res = post_turn(&app, &ali, &thread, &"é".repeat(101)).await;
1515715157 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
1515815158 // Nothing rejected was written.
1515915159 assert_eq!(chat_rows(&db).await, (1, 0));
1516015160
15161- let res = post_turn(&app, &ali, &conversation, &"é".repeat(100)).await;
15161+ let res = post_turn(&app, &ali, &thread, &"é".repeat(100)).await;
1516215162 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
1516315163 }
1516415164
@@ -15170,10 +15170,10 @@ async fn chat_rate_limit_refuses_before_anything_is_written() {
1517015170 let ai = chat_bridge().await;
1517115171 let (app, db) = chat_app(Some(ai.bridge.clone())).await;
1517215172 let ali = login(&app, "ali").await;
15173- let conversation = new_thread(&app, &ali).await;
15173+ let thread = new_thread(&app, &ali).await;
1517415174
1517515175 for n in 1..=20 {
15176- let res = post_turn(&app, &ali, &conversation, &format!("soru {n}")).await;
15176+ let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await;
1517715177 assert_eq!(res.status, StatusCode::ACCEPTED, "turn {n}: {}", res.body);
1517815178 }
1517915179 let before = chat_rows(&db).await;
@@ -15182,7 +15182,7 @@ async fn chat_rate_limit_refuses_before_anything_is_written() {
1518215182 let (status, headers, _) = common::send_raw(
1518315183 &app,
1518415184 "POST",
15185- &format!("/chat/conversations/{conversation}/messages"),
15185+ &format!("/chatbot/threads/{thread}/messages"),
1518615186 Some(&ali),
1518715187 Some("application/json"),
1518815188 json!({ "content": "yirmi birinci" })
@@ -15222,16 +15222,16 @@ async fn every_role_may_chat_parents_included() {
1522215222 ("patron", "admin"),
1522315223 ] {
1522415224 let cookie = login_as(&app, &db, name, role).await;
15225- let conversation = new_thread(&app, &cookie).await;
15225+ let thread = new_thread(&app, &cookie).await;
1522615226
15227- let res = post_turn(&app, &cookie, &conversation, "bir soru").await;
15227+ let res = post_turn(&app, &cookie, &thread, "bir soru").await;
1522815228 assert_eq!(res.status, StatusCode::ACCEPTED, "{role}: {}", res.body);
1522915229 let mid = res.body["message_id"].as_str().unwrap().to_string();
1523015230
1523115231 let res = send(
1523215232 &app,
1523315233 "GET",
15234- &format!("/chat/conversations/{conversation}/messages/{mid}"),
15234+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
1523515235 Some(&cookie),
1523615236 None,
1523715237 )
@@ -15241,7 +15241,7 @@ async fn every_role_may_chat_parents_included() {
1524115241 let res = send(
1524215242 &app,
1524315243 "GET",
15244- &format!("/chat/conversations/{conversation}/messages"),
15244+ &format!("/chatbot/threads/{thread}/messages"),
1524515245 Some(&cookie),
1524615246 None,
1524715247 )
@@ -15250,19 +15250,19 @@ async fn every_role_may_chat_parents_included() {
1525015250 assert_eq!(common::items(&res.body).len(), 2, "{role}: {}", res.body);
1525115251
1525215252 assert_eq!(
15253- open_stream(&app, &cookie, &conversation, &mid).await,
15253+ open_stream(&app, &cookie, &thread, &mid).await,
1525415254 StatusCode::OK,
1525515255 "{role} may open the stream"
1525615256 );
1525715257
15258- let res = send(&app, "GET", "/chat/conversations", Some(&cookie), None).await;
15258+ let res = send(&app, "GET", "/chatbot/threads", Some(&cookie), None).await;
1525915259 assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body);
1526015260 assert_eq!(common::items(&res.body).len(), 1, "{role}: {}", res.body);
1526115261
1526215262 let res = send(
1526315263 &app,
1526415264 "DELETE",
15265- &format!("/chat/conversations/{conversation}"),
15265+ &format!("/chatbot/threads/{thread}"),
1526615266 Some(&cookie),
1526715267 None,
1526815268 )
@@ -15284,7 +15284,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1528415284 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1528515285 let second = new_thread(&app, &ali).await;
1528615286
15287- let listed = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;
15287+ let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
1528815288 let items = common::items(&listed.body);
1528915289 assert_eq!(id_of(&items[0]), second, "newest activity first");
1529015290 let before = items[1]["updated_at"].as_i64().expect("updated_at");
@@ -15295,7 +15295,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1529515295 let res = send(
1529615296 &app,
1529715297 "PATCH",
15298- &format!("/chat/conversations/{first}"),
15298+ &format!("/chatbot/threads/{first}"),
1529915299 Some(&ali),
1530015300 Some(json!({ "title": " Fizik ödevi " })),
1530115301 )
@@ -15307,7 +15307,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1530715307 assert!(stamped > before, "{stamped} !> {before}");
1530815308
1530915309 // The rename is durable and re-sorted the list.
15310- let listed = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;
15310+ let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
1531115311 let items = common::items(&listed.body);
1531215312 assert_eq!(id_of(&items[0]), first, "the renamed thread is now first");
1531315313 assert_eq!(items[0]["title"], "Fizik ödevi");
@@ -15317,7 +15317,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1531715317 let res = send(
1531815318 &app,
1531915319 "PATCH",
15320- &format!("/chat/conversations/{first}"),
15320+ &format!("/chatbot/threads/{first}"),
1532115321 Some(&ali),
1532215322 Some(clearing.clone()),
1532315323 )
@@ -15329,7 +15329,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1532915329 send(
1533015330 &app,
1533115331 "PATCH",
15332- &format!("/chat/conversations/{first}"),
15332+ &format!("/chatbot/threads/{first}"),
1533315333 Some(&ali),
1533415334 Some(json!({ "title": "geri" })),
1533515335 )
@@ -15340,7 +15340,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1534015340 let res = send(
1534115341 &app,
1534215342 "PATCH",
15343- &format!("/chat/conversations/{first}"),
15343+ &format!("/chatbot/threads/{first}"),
1534415344 Some(&ali),
1534515345 Some(json!({ "title": "é".repeat(201) })),
1534615346 )
@@ -15349,7 +15349,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1534915349 let res = send(
1535015350 &app,
1535115351 "PATCH",
15352- &format!("/chat/conversations/{first}"),
15352+ &format!("/chatbot/threads/{first}"),
1535315353 Some(&ali),
1535415354 Some(json!({ "title": "é".repeat(200) })),
1535515355 )
@@ -15360,7 +15360,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1536015360 let res = send(
1536115361 &app,
1536215362 "PATCH",
15363- "/chat/conversations/nosuchthread",
15363+ "/chatbot/threads/nosuchthread",
1536415364 Some(&ali),
1536515365 Some(json!({ "title": "hayalet" })),
1536615366 )
@@ -15370,7 +15370,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1537015370 let res = send(
1537115371 &app,
1537215372 "GET",
15373- &format!("/chat/conversations/{second}/messages"),
15373+ &format!("/chatbot/threads/{second}/messages"),
1537415374 Some(&ali),
1537515375 None,
1537615376 )
@@ -15380,7 +15380,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
1538015380
1538115381 #[tokio::test]
1538215382 async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {
15383- // `RATE_LIMIT_CHAT_PER_MINUTE`, the third tier, behaves like the two IP
15383+ // `RATE_LIMIT_CHATBOT_PER_MINUTE`, the third tier, behaves like the two IP
1538415384 // ones: the configured number is honoured exactly and `0` switches it off.
1538515385 // No bridge is needed — the limiter is charged before the availability
1538615386 // gate, so a metered turn answers 503 and only the refused one answers 429.
@@ -15388,9 +15388,9 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {
1538815388
1538915389 let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(3)).await;
1539015390 let ali = login(&app, "ali").await;
15391- let conversation = new_thread(&app, &ali).await;
15391+ let thread = new_thread(&app, &ali).await;
1539215392 for n in 1..=3 {
15393- let res = post_turn(&app, &ali, &conversation, &format!("soru {n}")).await;
15393+ let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await;
1539415394 assert_eq!(
1539515395 res.status,
1539615396 StatusCode::SERVICE_UNAVAILABLE,
@@ -15398,7 +15398,7 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {
1539815398 res.body
1539915399 );
1540015400 }
15401- let res = post_turn(&app, &ali, &conversation, "dorduncu").await;
15401+ let res = post_turn(&app, &ali, &thread, "dorduncu").await;
1540215402 assert_eq!(res.status, StatusCode::TOO_MANY_REQUESTS, "{}", res.body);
1540315403 // Per user, still: a second caller starts with a full budget.
1540415404 let veli = login(&app, "veli").await;
@@ -15413,9 +15413,9 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {
1541315413 // `0` disables the tier: well past the shipped default, nothing is refused.
1541415414 let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(0)).await;
1541515415 let ali = login(&app, "ali").await;
15416- let conversation = new_thread(&app, &ali).await;
15416+ let thread = new_thread(&app, &ali).await;
1541715417 for n in 1..=40 {
15418- let res = post_turn(&app, &ali, &conversation, &format!("soru {n}")).await;
15418+ let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await;
1541915419 assert_eq!(
1542015420 res.status,
1542115421 StatusCode::SERVICE_UNAVAILABLE,
tests/persistence.rsmodified+33 -33
@@ -24,7 +24,7 @@ async fn reboot(db: &Database) -> Router {
2424 files_path: common::files_dir(),
2525 cookie_secure: false,
2626 rate_limit: RateLimitConfig::unlimited(),
27- chat_limit: Default::default(),
27+ chatbot_limit: Default::default(),
2828 exam_presence: Default::default(),
2929 db_up: Default::default(),
3030 ai: None,
@@ -729,13 +729,13 @@ async fn appointments_survive_remigration() {
729729 }
730730
731731 /// A chatbot thread and every turn in it die together: deleting the
732-/// conversation cascades its `chat_message` rows in one transaction, so no
732+/// thread cascades its `chatbot_message` rows in one transaction, so no
733733 /// orphan survives a reboot. And the thread is owner-scoped end to end — a
734-/// second user reads neither the conversation nor its messages.
734+/// second user reads neither the thread nor its messages.
735735 #[tokio::test]
736736 async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
737- use hezarfen_backend::domain::chat_message::{ChatContent, ChatMessage, MessageStatus};
738- use hezarfen_backend::domain::conversation::Conversation;
737+ use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage, MessageStatus};
738+ use hezarfen_backend::domain::chatbot_thread::ChatbotThread;
739739 use hezarfen_backend::domain::user::UserId;
740740
741741 let (app, db) = common::app_and_db().await;
@@ -744,11 +744,11 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
744744 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);
745745 let other = UserId::from_key(&me_id(&app, &other_cookie).await);
746746
747- let conversation = Conversation::create(&owner, None, &db)
747+ let thread = ChatbotThread::create(&owner, None, &db)
748748 .await
749749 .expect("create");
750- let id = conversation.get_id().clone();
751- let prompt = ChatMessage::append_user(
750+ let id = thread.get_id().clone();
751+ let prompt = ChatbotMessage::append_user(
752752 &id,
753753 &owner,
754754 ChatContent::try_new("selam").expect("content"),
@@ -756,12 +756,12 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
756756 )
757757 .await
758758 .expect("append user");
759- let reply = ChatMessage::append_pending_assistant(&id, &owner, &db)
759+ let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db)
760760 .await
761761 .expect("append assistant");
762762 assert_eq!(reply.get_status(), MessageStatus::Pending);
763763
764- let reply = ChatMessage::complete(
764+ let reply = ChatbotMessage::complete(
765765 reply.get_id(),
766766 ChatContent::try_new("aleykum selam").expect("content"),
767767 false,
@@ -773,56 +773,56 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
773773 assert_eq!(reply.get_content().as_str(), "aleykum selam");
774774 assert!(reply.get_completed_at().is_some());
775775 assert_eq!(
776- ChatMessage::list_for_conversation(&id, &db)
776+ ChatbotMessage::list_for_thread(&id, &db)
777777 .await
778778 .expect("thread")
779779 .len(),
780780 2
781781 );
782782
783- // The other user sees nothing of it, by conversation or by message.
783+ // The other user sees nothing of it, by thread or by message.
784784 assert!(
785- Conversation::read_for(&id, &other, &db)
785+ ChatbotThread::read_for(&id, &other, &db)
786786 .await
787- .expect("cross-user conversation")
787+ .expect("cross-user thread")
788788 .is_none()
789789 );
790790 assert!(
791- ChatMessage::read_for(prompt.get_id(), &other, &db)
791+ ChatbotMessage::read_for(prompt.get_id(), &other, &db)
792792 .await
793793 .expect("cross-user message")
794794 .is_none()
795795 );
796796 assert_eq!(
797- Conversation::count_for_user(&other, &db)
797+ ChatbotThread::count_for_user(&other, &db)
798798 .await
799799 .expect("count"),
800800 0
801801 );
802802 assert_eq!(
803- Conversation::count_for_user(&owner, &db)
803+ ChatbotThread::count_for_user(&owner, &db)
804804 .await
805805 .expect("count"),
806806 1
807807 );
808808
809- conversation.delete(&db).await.expect("delete");
809+ thread.delete(&db).await.expect("delete");
810810 assert!(
811- Conversation::read_for(&id, &owner, &db)
811+ ChatbotThread::read_for(&id, &owner, &db)
812812 .await
813- .expect("deleted conversation")
813+ .expect("deleted thread")
814814 .is_none()
815815 );
816816 assert_eq!(
817- Conversation::list_for_user(&owner, &db)
817+ ChatbotThread::list_for_user(&owner, &db)
818818 .await
819819 .unwrap()
820820 .len(),
821821 0
822822 );
823- // Not just the thread's own view: no `chat_message` row is left anywhere.
823+ // Not just the thread's own view: no `chatbot_message` row is left anywhere.
824824 let mut left = db
825- .query("SELECT VALUE id FROM chat_message")
825+ .query("SELECT VALUE id FROM chatbot_message")
826826 .await
827827 .expect("sweep")
828828 .check()
@@ -839,8 +839,8 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
839839 /// read back as whole, which is exactly how they were shown at the time.
840840 #[tokio::test]
841841 async fn legacy_chat_turns_backfill_to_untruncated() {
842- use hezarfen_backend::domain::chat_message::{ChatContent, ChatMessage};
843- use hezarfen_backend::domain::conversation::Conversation;
842+ use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage};
843+ use hezarfen_backend::domain::chatbot_thread::ChatbotThread;
844844 use hezarfen_backend::domain::user::UserId;
845845
846846 let (app, db) = common::app_and_db().await;
@@ -857,11 +857,11 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
857857 .unwrap();
858858 let owner = UserId::from_key(&me_id(&app, &cookie).await);
859859
860- let conversation = Conversation::create(&owner, None, &db)
860+ let thread = ChatbotThread::create(&owner, None, &db)
861861 .await
862862 .expect("create");
863- let id = conversation.get_id().clone();
864- ChatMessage::append_user(
863+ let id = thread.get_id().clone();
864+ ChatbotMessage::append_user(
865865 &id,
866866 &owner,
867867 ChatContent::try_new("selam").expect("content"),
@@ -869,10 +869,10 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
869869 )
870870 .await
871871 .expect("append user");
872- let reply = ChatMessage::append_pending_assistant(&id, &owner, &db)
872+ let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db)
873873 .await
874874 .expect("append assistant");
875- ChatMessage::complete(
875+ ChatbotMessage::complete(
876876 reply.get_id(),
877877 ChatContent::try_new("aleykum selam").expect("content"),
878878 false,
@@ -883,8 +883,8 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
883883
884884 // Strip the column the way a pre-flag binary's schema would have left it.
885885 db.query(
886- "REMOVE FIELD IF EXISTS truncated ON TABLE chat_message;
887- UPDATE chat_message SET truncated = NONE;",
886+ "REMOVE FIELD IF EXISTS truncated ON TABLE chatbot_message;
887+ UPDATE chatbot_message SET truncated = NONE;",
888888 )
889889 .await
890890 .expect("strip truncated")
@@ -901,7 +901,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
901901 let res = send(
902902 &app,
903903 "GET",
904- &format!("/chat/conversations/{}/messages", id.key()),
904+ &format!("/chatbot/threads/{}/messages", id.key()),
905905 Some(&cookie),
906906 None,
907907 )
tests/rate_limit.rsmodified+2 -2
@@ -24,7 +24,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
2424 files_path: tempfile::tempdir().expect("files dir").keep(),
2525 cookie_secure: false,
2626 rate_limit,
27- chat_limit: Default::default(),
27+ chatbot_limit: Default::default(),
2828 exam_presence: Default::default(),
2929 db_up: Default::default(),
3030 ai: None,
@@ -318,7 +318,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
318318 files_path: tempfile::tempdir().expect("files dir").keep(),
319319 cookie_secure: false,
320320 rate_limit,
321- chat_limit: Default::default(),
321+ chatbot_limit: Default::default(),
322322 exam_presence: Default::default(),
323323 db_up: Default::default(),
324324 ai: None,