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
35 # Chatbot messages per minute, per USER (not per IP) — the tier that rations35 # Chatbot messages per minute, per USER (not per IP) — the tier that rations
36 # the AI service, so a shared-IP classroom can't spend one student's budget on36 # the AI service, so a shared-IP classroom can't spend one student's budget on
37 # another's. 0 disables it, like the tiers above.37 # another's. 0 disables it, like the tiers above.
38-# RATE_LIMIT_CHAT_PER_MINUTE=2038+# RATE_LIMIT_CHATBOT_PER_MINUTE=20
39 39
40 # Key rate limits by the rightmost X-Forwarded-For entry instead of the TCP40 # Key rate limits by the rightmost X-Forwarded-For entry instead of the TCP
41 # peer address. Enable ONLY behind a reverse proxy that appends the client IP41 # 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.
95 The bridge's certificate is published at `GET /ai/certificate` so a service can95 The bridge's certificate is published at `GET /ai/certificate` so a service can
96 pin it before dialling (see "AI bridge (QUIC)").96 pin it before dialling (see "AI bridge (QUIC)").
97 The first thing riding that bridge is the **chatbot**: every signed-in user97 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 —
99 no rule tables, no canned answers, the backend only owns auth, limits,99 no rule tables, no canned answers, the backend only owns auth, limits,
100 persistence and the payload format. Sending is asynchronous because an100 persistence and the payload format. Sending is asynchronous because an
101 inference outlives a request: the turn plus an empty `pending` answer are101 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 —
234 useful for load tests.234 useful for load tests.
235 235
236 Sending a chatbot message adds a third tier, and it is keyed by **user id**,236 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 inference237+not by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference
238 costs the school real money and a shared-IP classroom must not spend one238 costs the school real money and a shared-IP classroom must not spend one
239 student's budget on another's. `0` disables it like the other two. It is239 student's budget on another's. `0` disables it like the other two. It is
240 charged before anything is written, so a `429` leaves no trace (see240 charged before anything is written, so a `429` leaves no trace (see
@@ -576,21 +576,21 @@ their existing shapes: the student exam-room reads
576 | GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` |576 | GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` |
577 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |577 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
578 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |578 | 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` |
580 | 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") |580 | 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") |
581 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |581 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
582 | GET | `/terms` | student | List terms, newest first · paged |582 | GET | `/terms` | student | List terms, newest first · paged |
583 | GET | `/terms/{id}` | student | Get one term |583 | GET | `/terms/{id}` | student | Get one term |
584 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |584 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |
585 | DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course still links to it |585 | 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` |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 | `/chat/conversations` | student | The caller's conversations, newest activity first · paged |587+| GET | `/chatbot/threads` | student | The caller's threads, 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 |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 | `/chat/conversations/{id}` | student | Delete own conversation and every message in it (someone else's is a `404`, never a `403`) |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 | `/chat/conversations/{id}/messages` | student | The conversation's turns, oldest first — user and assistant rows alike · paged |590+| GET | `/chatbot/threads/{id}/messages` | student | The thread'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) |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 | `/chat/conversations/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` |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 | `/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") |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") |
594 594
595 `status` must be one of the school's attendance statuses (`GET /settings`);595 `status` must be one of the school's attendance statuses (`GET /settings`);
596 the core four `present | absent | late | excused` always exist, plus whatever596 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,
904 exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;904 exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB;
905 a server hard cap — uploads buffer in memory), default `5242880` (5 MiB).905 a server hard cap — uploads buffer in memory), default `5242880` (5 MiB).
906 Checked at upload time only: lowering it never touches already-stored files.906 Checked at upload time only: lowering it never touches already-stored files.
907-- **`chat_history_turns`** — how many prior **messages** of a conversation the907+- **`chatbot_history_turns`** — how many prior **messages** of a thread the
908 chatbot is given as context, `1`–`50` (default `10`). The unit is messages,908 chatbot is given as context, `1`–`50` (default `10`). The unit is messages,
909 not exchanges: a question and its answer are two, so the default remembers909 not exchanges: a question and its answer are two, so the default remembers
910 five question/answer pairs. Every one of them is re-sent on every reply, so910 five question/answer pairs. Every one of them is re-sent on every reply, so
911 the number is both what the bot remembers and what each answer costs.911 the number is both what the bot remembers and what each answer costs.
912-- **`max_chat_conversations`** — how many chatbot conversations one user may912+- **`max_chatbot_threads`** — how many chatbot threads one user may
913 keep, `1`–`500` (default `50`); at the cap the user deletes an old one913 keep, `1`–`500` (default `50`); at the cap the user deletes an old one
914 first. Storage protection, not a usage quota — that is the per-minute914 first. Storage protection, not a usage quota — that is the per-minute
915 message limit.915 message limit.
916-- **`max_chat_message_len`** — character limit on one chat message,916+- **`max_chatbot_message_len`** — character limit on one chat message,
917 `100`–`8000` (default `4000`); the ceiling is a server hard cap, because917 `100`–`8000` (default `4000`); the ceiling is a server hard cap, because
918 the message and its history must fit one bridge frame.918 the message and its history must fit one bridge frame.
919 919
@@ -1564,18 +1564,18 @@ only as trustworthy as that HTTP hop. On an untrusted network set
1564 1564
1565 ## Chatbot1565 ## Chatbot
1566 1566
1567-Every signed-in user — `parent` included — keeps private conversations with an1567+Every signed-in user — `parent` included — keeps private threads with an
1568 AI service. The backend is a **relay**: it owns auth, the limits, the thread,1568 AI service. The backend is a **relay**: it owns auth, the limits, the thread,
1569 the payload format, and the last look at the answer before anyone sees it; the1569 the payload format, and the last look at the answer before anyone sees it; the
1570 words are the service's. There are deliberately **no rule, intent or1570 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 wants1571+canned-answer tables** — the thread is free-form, and a school that wants
1572 different behaviour changes its AI service, not this backend. A thread is1572 different behaviour changes its AI service, not this backend. A thread is
1573 private to its owner: no teacher, no admin, nobody reads someone else's, and1573 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`.
1575 1575
1576 ### Sending is two-phase, and that is the point1576 ### Sending is two-phase, and that is the point
1577 1577
1578-`POST /chat/conversations/{id}/messages` answers `202 {message_id, status:1578+`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status:
1579 "pending"}` instead of the answer, because an inference outlives a normal1579 "pending"}` instead of the answer, because an inference outlives a normal
1580 request (and the request-timeout layer that guards every handler). Before the1580 request (and the request-timeout layer that guards every handler). Before the
1581 AI is even called, two rows are written: the user's turn, and an **empty1581 AI is even called, two rows are written: the user's turn, and an **empty
@@ -1586,9 +1586,9 @@ outlives the HTTP request.
1586 1586
1587 The client then reads that row either way it likes:1587 The client then reads that row either way it likes:
1588 1588
1589-- **poll** `GET /chat/conversations/{id}/messages/{mid}` — `pending` until it1589+- **poll** `GET /chatbot/threads/{id}/messages/{mid}` — `pending` until it
1590 settles, then `complete` with `content` or `failed` with `error_code`;1590 settles, then `complete` with `content` or `failed` with `error_code`;
1591-- **stream** `GET /chat/conversations/{id}/messages/{mid}/stream` — the same1591+- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` — the same
1592 row over Server-Sent Events.1592 row over Server-Sent Events.
1593 1593
1594 Both read the same row, so they can never disagree, in any state.1594 Both read the same row, so they can never disagree, in any state.
@@ -1622,7 +1622,7 @@ unchanged frontend.
1622 ### The message DTO1622 ### The message DTO
1623 1623
1624 ```json1624 ```json
1625-{ "id": "01J8…", "conversation_id": "01J8…", "role": "assistant",1625+{ "id": "01J8…", "thread_id": "01J8…", "role": "assistant",
1626 "status": "complete", "content": "…", "truncated": false, "error_code": null,1626 "status": "complete", "content": "…", "truncated": false, "error_code": null,
1627 "created_at": 1761820800000, "completed_at": 1761820803120 }1627 "created_at": 1761820800000, "completed_at": 1761820803120 }
1628 ```1628 ```
@@ -1631,7 +1631,7 @@ unchanged frontend.
1631 `failed` (a user turn is always `complete`). `content` is empty while pending,1631 `failed` (a user turn is always `complete`). `content` is empty while pending,
1632 `error_code` is set only when failed, `completed_at` is `null` until the turn1632 `error_code` is set only when failed, `completed_at` is `null` until the turn
1633 settles. `truncated` is `true` when `content` is only the first part of what1633 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;
1635 it is always `false` for a user turn and for a failed one. Show it: a clipped1635 it is always `false` for a user turn and for a failed one. Show it: a clipped
1636 answer that looks whole is worse than one the reader knows is clipped. The same1636 answer that looks whole is worse than one the reader knows is clipped. The same
1637 DTO is what the SSE `done` event carries, so the streaming and polling reads1637 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.
1642 | code | when |1642 | code | when |
1643 | --- | --- |1643 | --- | --- |
1644 | `202` | the turn was accepted; the answer is on its way |1644 | `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` |1645+| `400` | empty message, or longer than the school's `max_chatbot_message_len` |
1646-| `404` | no such conversation or message — or not the caller's |1646+| `404` | no such thread or message — or not the caller's |
1647-| `409` | already at `max_chat_conversations`; delete a thread first |1647+| `409` | already at `max_chatbot_threads`; delete a thread first |
1648-| `429` | over `RATE_LIMIT_CHAT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |1648+| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` |
1649 | `503` | no connected service offers `chat.reply` — **nothing was written**, retry later |1649 | `503` | no connected service offers `chat.reply` — **nothing was written**, retry later |
1650 1650
1651 The `503` ordering matters: the bridge is checked before the rows exist, so an1651 The `503` ordering matters: the bridge is checked before the rows exist, so an
@@ -1666,7 +1666,7 @@ three independent mechanisms:
1666 1666
1667 Two more verdicts come from inspecting the answer: an **empty** reply is1667 Two more verdicts come from inspecting the answer: an **empty** reply is
1668 reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a1668 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` — a1669+bug), and an **over-long** one is truncated to `max_chatbot_message_len` — a
1670 clipped answer still helps, a discarded one does not — with `truncated: true`1670 clipped answer still helps, a discarded one does not — with `truncated: true`
1671 on the stored turn, so the clip is never passed off as the whole answer.1671 on the stored turn, so the clip is never passed off as the whole answer.
1672 1672
@@ -1689,14 +1689,14 @@ Requests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:
1689 ```1689 ```
1690 1690
1691 `history` is **oldest first** (index 0 is furthest back), optional (absent or1691 `history` is **oldest first** (index 0 is furthest back), optional (absent or
1692-`[]` = a fresh conversation), and **excludes** the new message — that one is1692+`[]` = a fresh thread), and **excludes** the new message — that one is
1693-`message`. It carries the last `chat_history_turns` **settled messages** —1693+`message`. It carries the last `chatbot_history_turns` **settled messages** —
1694 entries, not exchanges: the default `10` is five question/answer pairs, and1694 entries, not exchanges: the default `10` is five question/answer pairs, and
1695 `history` is exactly that many entries long whenever the thread holds enough1695 `history` is exactly that many entries long whenever the thread holds enough
1696 of them. Only settled turns count: a failed answer is skipped and the window1696 of them. Only settled turns count: a failed answer is skipped and the window
1697 reaches further back for a usable one, rather than coming up short. All of it1697 reaches further back for a usable one, rather than coming up short. All of it
1698 is re-sent on every request, which is why the service may be stateless: it can1698 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.
1700 1700
1701 The answer is a `Response::Ok` whose payload is:1701 The answer is a `Response::Ok` whose payload is:
1702 1702
@@ -1770,10 +1770,10 @@ src/
1770 subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum)1770 subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum)
1771 term.rs TermId · TermName · Term (school term window)1771 term.rs TermId · TermName · Term (school term window)
1772 settings.rs ExamKindDef · GradeBand · Settings (per-school policy)1772 settings.rs ExamKindDef · GradeBand · Settings (per-school policy)
1773- conversation.rs ConversationId · ConversationTitle · Conversation (one1773+ chatbot_thread.rs ChatbotThreadId · ChatbotThreadTitle · ChatbotThread (one
1774 chatbot thread, private to its owner)1774 chatbot thread, private to its owner)
1775- chat_message.rs ChatMessageId · ChatContent · MessageRole · MessageStatus ·1775+ chatbot_message.rs ChatbotMessageId · ChatContent · MessageRole · MessageStatus ·
1776- ChatMessage (one turn; the assistant row is written1776+ ChatbotMessage (one turn; the assistant row is written
1777 `pending` before the AI call and settled after)1777 `pending` before the AI call and settled after)
1778 appointment_slot.rs AppointmentSlotId · SlotSeries · SlotNote ·1778 appointment_slot.rs AppointmentSlotId · SlotSeries · SlotNote ·
1779 AppointmentSlot (a teacher's published availability; a1779 AppointmentSlot (a teacher's published availability; a
@@ -1807,7 +1807,7 @@ src/
1807 auth.rs users.rs notes.rs messages.rs events.rs appointments.rs1807 auth.rs users.rs notes.rs messages.rs events.rs appointments.rs
1808 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs1808 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
1809 marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs1809 marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs
1810- ai.rs chat.rs1810+ ai.rs chatbot.rs
1811 ```1811 ```
1812 1812
1813 Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory1813 Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory
src/ai/mod.rsmodified+1 -1
@@ -18,7 +18,7 @@
18 //! * [`tls`] — the listener's certificate18 //! * [`tls`] — the listener's certificate
19 //!19 //!
20 //! The transport is generic; the features land on top of it. So far that is20 //! 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.
22 22
23 pub mod chat;23 pub mod chat;
24 pub mod error;24 pub mod error;
src/config.rsmodified+6 -6
@@ -10,7 +10,7 @@ pub const DEFAULT_API_RATE_LIMIT: u32 = 300;
10 /// Default chatbot messages per minute *per user*. Sits far above a human10 /// Default chatbot messages per minute *per user*. Sits far above a human
11 /// typing while still blunting a scripted fan-out at the AI service behind the11 /// typing while still blunting a scripted fan-out at the AI service behind the
12 /// bridge — which is the cost this tier rations, not this process.12 /// 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;
14 14
15 /// Runtime configuration, sourced from environment variables (see `.env.example`).15 /// Runtime configuration, sourced from environment variables (see `.env.example`).
16 #[derive(Clone, Debug)]16 #[derive(Clone, Debug)]
@@ -33,10 +33,10 @@ pub struct Config {
33 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.33 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.
34 pub rate_limit: RateLimitConfig,34 pub rate_limit: RateLimitConfig,
35 /// Chatbot messages one user may send per minute35 /// Chatbot messages one user may send per minute
36- /// (`RATE_LIMIT_CHAT_PER_MINUTE`). `0` disables the tier. Kept out of36+ /// (`RATE_LIMIT_CHATBOT_PER_MINUTE`). `0` disables the tier. Kept out of
37 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is37 /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is
38 /// keyed by user and is enforced inside the handler.38 /// keyed by user and is enforced inside the handler.
39- pub chat_per_minute: u32,39+ pub chatbot_per_minute: u32,
40 /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are40 /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are
41 /// set, an admin account with these credentials is created at boot if the41 /// set, an admin account with these credentials is created at boot if the
42 /// username doesn't exist yet. Blank values count as unset.42 /// username doesn't exist yet. Blank values count as unset.
@@ -82,9 +82,9 @@ impl Config {
82 ),82 ),
83 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),83 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),
84 },84 },
85- chat_per_minute: parse_limit(85+ chatbot_per_minute: parse_limit(
86- env::var("RATE_LIMIT_CHAT_PER_MINUTE").ok(),86+ env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(),
87- DEFAULT_CHAT_RATE_LIMIT,87+ DEFAULT_CHATBOT_RATE_LIMIT,
88 ),88 ),
89 admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()),89 admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()),
90 admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()),90 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";
291 /// Hard ceiling on one chat message's characters — the newtype bound, above291 /// Hard ceiling on one chat message's characters — the newtype bound, above
292 /// which no school setting can reach. Sized for a pasted question with its292 /// which no school setting can reach. Sized for a pasted question with its
293 /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along.293 /// 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;
295 295
296-/// The school-adjustable per-message character cap (`max_chat_message_len` in296+/// The school-adjustable per-message character cap (`max_chatbot_message_len` in
297 /// settings): its default and the inclusive range a manager may set. The297 /// 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 service298+/// ceiling is [`MAX_CHATBOT_MESSAGE_LEN`] — a longer prompt costs the AI service
299 /// context it needs for the history.299 /// context it needs for the history.
300-pub const DEFAULT_MAX_CHAT_MESSAGE_LEN: i64 = 4_000;300+pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000;
301-pub const MIN_MAX_CHAT_MESSAGE_LEN: i64 = 100;301+pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100;
302-pub const MAX_MAX_CHAT_MESSAGE_LEN: i64 = MAX_CHAT_MESSAGE_LEN as i64;302+pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64;
303 303
304-/// How many prior user/assistant turns of a conversation are replayed to the304+/// How many prior user/assistant turns of a thread are replayed to the
305-/// AI service as context (`chat_history_turns` in settings): its default and305+/// AI service as context (`chatbot_history_turns` in settings): its default and
306 /// the inclusive range a manager may set. Every turn is re-sent on every306 /// the inclusive range a manager may set. Every turn is re-sent on every
307 /// request, so the ceiling bounds both the frame size and the inference cost.307 /// request, so the ceiling bounds both the frame size and the inference cost.
308-pub const DEFAULT_CHAT_HISTORY_TURNS: i64 = 10;308+pub const DEFAULT_CHATBOT_HISTORY_TURNS: i64 = 10;
309-pub const MIN_CHAT_HISTORY_TURNS: i64 = 1;309+pub const MIN_CHATBOT_HISTORY_TURNS: i64 = 1;
310-pub const MAX_CHAT_HISTORY_TURNS: i64 = 50;310+pub const MAX_CHATBOT_HISTORY_TURNS: i64 = 50;
311 311
312-/// How many conversations one user may keep (`max_chat_conversations` in312+/// How many threads one user may keep (`max_chatbot_threads` in
313 /// settings): its default and the inclusive range a manager may set. Reached,313 /// 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 is314+/// the user deletes an old thread before starting a new one — the cap is
315 /// storage protection, not a usage quota.315 /// storage protection, not a usage quota.
316-pub const DEFAULT_MAX_CHAT_CONVERSATIONS: i64 = 50;316+pub const DEFAULT_MAX_CHATBOT_THREADS: i64 = 50;
317-pub const MIN_MAX_CHAT_CONVERSATIONS: i64 = 1;317+pub const MIN_MAX_CHATBOT_THREADS: i64 = 1;
318-pub const MAX_MAX_CHAT_CONVERSATIONS: i64 = 500;318+pub const MAX_MAX_CHATBOT_THREADS: i64 = 500;
319 319
320 /// How often the chat stream re-reads a `pending` assistant message while it320 /// How often the chat stream re-reads a `pending` assistant message while it
321 /// waits for the answer. The reply lands in the database from whichever task321 /// 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;
327 /// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may327 /// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may
328 /// raise), because the answering task normally stamps the failure itself —328 /// raise), because the answering task normally stamps the failure itself —
329 /// this only catches the row whose task died with the process.329 /// 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;
331 331
332 /// How long a dialling AI service has to complete its `Hello`/`Welcome`332 /// How long a dialling AI service has to complete its `Hello`/`Welcome`
333 /// exchange before the connection is dropped. Short: the handshake is one333 /// 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";
54 pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";54 pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission";
55 pub const HOMEWORK_FILE_TABLE: &str = "homework_file";55 pub const HOMEWORK_FILE_TABLE: &str = "homework_file";
56 pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";56 pub const HOMEWORK_RESULT_TABLE: &str = "homework_result";
57-pub const CONVERSATION_TABLE: &str = "conversation";57+pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread";
58-pub const CHAT_MESSAGE_TABLE: &str = "chat_message";58+pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";
59 pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";59 pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
60 pub const APPOINTMENT_TABLE: &str = "appointment";60 pub const APPOINTMENT_TABLE: &str = "appointment";
61 61
@@ -120,30 +120,30 @@ const MIGRATION: &str = "
120 DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;120 DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int;
121 DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;121 DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note;
122 122
123- -- Chatbot relay (2026-07-23): a `conversation` groups the turns, one123+ -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
124- -- `chat_message` is one turn. `user_id` rides on the message too so an124+ -- `chatbot_message` is one turn. `user_id` rides on the message too so an
125 -- ownership check needs no join. An assistant turn is born `pending` and125 -- ownership check needs no join. An assistant turn is born `pending` and
126 -- is completed (or failed) by the task holding the AI-bridge stream —126 -- is completed (or failed) by the task holding the AI-bridge stream —
127 -- hence the BACKFILL sweep, since that task dies with the process.127 -- hence the BACKFILL sweep, since that task dies with the process.
128- DEFINE TABLE IF NOT EXISTS conversation SCHEMAFULL;128+ DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL;
129- DEFINE FIELD IF NOT EXISTS user_id ON conversation TYPE record<user> READONLY;129+ DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record<user> READONLY;
130- DEFINE FIELD IF NOT EXISTS title ON conversation TYPE option<string>;130+ DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option<string>;
131- DEFINE FIELD IF NOT EXISTS created_at ON conversation TYPE int READONLY;131+ DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY;
132- DEFINE FIELD IF NOT EXISTS updated_at ON conversation TYPE int;132+ DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int;
133- DEFINE INDEX IF NOT EXISTS conversation_user_updated ON conversation FIELDS user_id, updated_at;133+ DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at;
134-134+
135- DEFINE TABLE IF NOT EXISTS chat_message SCHEMAFULL;135+ DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL;
136- DEFINE FIELD IF NOT EXISTS conversation_id ON chat_message TYPE record<conversation> READONLY;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 chat_message TYPE record<user> READONLY;137+ DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record<user> READONLY;
138- DEFINE FIELD IF NOT EXISTS role ON chat_message TYPE string READONLY;138+ DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY;
139- DEFINE FIELD IF NOT EXISTS content ON chat_message TYPE string;139+ DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string;
140- DEFINE FIELD IF NOT EXISTS status ON chat_message TYPE string;140+ DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string;
141- DEFINE FIELD IF NOT EXISTS truncated ON chat_message TYPE bool DEFAULT false;141+ DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false;
142- DEFINE FIELD IF NOT EXISTS error_code ON chat_message TYPE option<string>;142+ DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option<string>;
143- DEFINE FIELD IF NOT EXISTS created_at ON chat_message TYPE int READONLY;143+ DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY;
144- DEFINE FIELD IF NOT EXISTS completed_at ON chat_message TYPE option<int>;144+ DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option<int>;
145- DEFINE INDEX IF NOT EXISTS chat_message_conversation_created ON chat_message FIELDS conversation_id, created_at;145+ DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at;
146- DEFINE INDEX IF NOT EXISTS chat_message_user ON chat_message FIELDS user_id;146+ DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id;
147 147
148 DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;148 DEFINE TABLE IF NOT EXISTS event SCHEMAFULL;
149 DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;149 DEFINE FIELD IF NOT EXISTS creator ON event TYPE record<user>;
@@ -346,9 +346,9 @@ const MIGRATION: &str = "
346 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;346 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
347 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;347 DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string;
348 DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option<int>;348 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>;349+ DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
350- DEFINE FIELD IF NOT EXISTS max_chat_conversations 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_chat_message_len ON settings TYPE option<int>;351+ DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
352 352
353 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students353 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
354 -- submit files + optional text, a teacher grades a status + optional mark.354 -- submit files + optional text, a teacher grades a status + optional mark.
@@ -471,12 +471,12 @@ const BACKFILL: &str = "
471 -- Turns written before the clipped-answer flag existed (2026-07-23): the471 -- Turns written before the clipped-answer flag existed (2026-07-23): the
472 -- clip was silent then, so nothing can be recovered — they read as whole,472 -- clip was silent then, so nothing can be recovered — they read as whole,
473 -- which is what they were presented as all along.473 -- 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;
475 475
476 -- An assistant turn is answered by an in-process task, so a restart leaves476 -- An assistant turn is answered by an in-process task, so a restart leaves
477 -- its row `pending` with nobody left to complete it: fail it at boot rather477 -- 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.478+ -- than let a reader wait out `CHATBOT_PENDING_STALE_SECS` on every load.
479- UPDATE chat_message SET status = 'failed', error_code = 'interrupted',479+ UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted',
480 completed_at = time::unix(time::now()) * 1000 WHERE status = 'pending';480 completed_at = time::unix(time::now()) * 1000 WHERE status = 'pending';
481 481
482 -- Promotion out of student now deletes the user's enrollments (2026-07-18);482 -- 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> {
546 #[cfg(test)]546 #[cfg(test)]
547 mod tests {547 mod tests {
548 #[tokio::test]548 #[tokio::test]
549- async fn boot_fails_chat_messages_left_pending() {549+ async fn boot_fails_chatbot_messages_left_pending() {
550 let db = super::init_mem().await.unwrap();550 let db = super::init_mem().await.unwrap();
551 db.query(551 db.query(
552 "CREATE user:u SET username = 'u', password_hash = 'x';552 "CREATE user:u SET username = 'u', password_hash = 'x';
553- CREATE conversation:c SET user_id = user:u, created_at = 1, updated_at = 1;553+ CREATE chatbot_thread: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,554+ CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u,
555 role = 'assistant', content = '', status = 'pending', created_at = 1;555 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,
557 role = 'assistant', content = 'hi', status = 'complete', created_at = 1;",557 role = 'assistant', content = 'hi', status = 'complete', created_at = 1;",
558 )558 )
559 .await559 .await
@@ -566,7 +566,7 @@ mod tests {
566 super::migrate(&db).await.unwrap();566 super::migrate(&db).await.unwrap();
567 567
568 let mut rows = db568 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")
570 .await570 .await
571 .unwrap();571 .unwrap();
572 let rows: Vec<serde_json::Value> = rows.take(0).unwrap();572 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 @@
5 //! a code) — and if that task dies with the process, the boot sweep in5 //! a code) — and if that task dies with the process, the boot sweep in
6 //! `database.rs` fails the row instead.6 //! `database.rs` fails the row instead.
7 //!7 //!
8-//! `user_id` is duplicated from the conversation onto every message so an8+//! `user_id` is duplicated from the thread onto every message so an
9 //! ownership check is one read, with no join.9 //! ownership check is one read, with no join.
10 10
11 use std::sync::{LazyLock, Mutex};11 use std::sync::{LazyLock, Mutex};
@@ -13,9 +13,9 @@ use std::sync::{LazyLock, Mutex};
13 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};13 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use ulid::{Generator, Ulid};14 use ulid::{Generator, Ulid};
15 15
16-use crate::constant::{CHAT_PENDING_STALE_SECS, MAX_CHAT_MESSAGE_LEN};16+use crate::constant::{CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN};
17 use crate::database::{CHAT_MESSAGE_TABLE, Database};17 use crate::database::{CHAT_MESSAGE_TABLE, Database};
18-use crate::domain::conversation::ConversationId;18+use crate::domain::chatbot_thread::ChatbotThreadId;
19 use crate::domain::timestamp::Timestamp;19 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::UserId;20 use crate::domain::user::UserId;
21 use crate::error::{AppError, ValidationError};21 use crate::error::{AppError, ValidationError};
@@ -33,7 +33,7 @@ const MAX_ERROR_CODE_LEN: usize = 64;
33 /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random33 /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random
34 /// low bits sort arbitrarily among ids minted in the same millisecond, this34 /// low bits sort arbitrarily among ids minted in the same millisecond, this
35 /// increments the previous id — so the `id` tie-break in the `ORDER BY` of35 /// increments the previous id — so the `id` tie-break in the `ORDER BY` of
36-/// [`ChatMessage::list_for_conversation`] / [`ChatMessage::list_tail`] is the36+/// [`ChatbotMessage::list_for_thread`] / [`ChatbotMessage::list_tail`] is the
37 /// order the rows were written. The user prompt and the assistant row one POST37 /// order the rows were written. The user prompt and the assistant row one POST
38 /// writes back-to-back routinely share a millisecond, and a random tie-break38 /// writes back-to-back routinely share a millisecond, and a random tie-break
39 /// there renders the answer *above* its own question — and hands the AI39 /// there renders the answer *above* its own question — and hands the AI
@@ -41,9 +41,9 @@ const MAX_ERROR_CODE_LEN: usize = 64;
41 static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));41 static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
42 42
43 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]43 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
44-pub struct ChatMessageId(RecordId);44+pub struct ChatbotMessageId(RecordId);
45 45
46-impl ChatMessageId {46+impl ChatbotMessageId {
47 pub fn generate() -> Self {47 pub fn generate() -> Self {
48 let mut ids = IDS.lock().expect("chat id generator poisoned");48 let mut ids = IDS.lock().expect("chat id generator poisoned");
49 // The only error is overflow of the random bits *within* one49 // The only error is overflow of the random bits *within* one
@@ -115,13 +115,13 @@ impl MessageStatus {
115 }115 }
116 116
117 /// One turn's text. The hard ceiling only — the school-adjustable117 /// 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.
119 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]119 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
120 pub struct ChatContent(String);120 pub struct ChatContent(String);
121 121
122 impl ChatContent {122 impl ChatContent {
123 pub fn try_new(value: &str) -> Result<Self, ValidationError> {123 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)?;
125 Ok(Self(value.to_string()))125 Ok(Self(value.to_string()))
126 }126 }
127 127
@@ -137,9 +137,9 @@ impl ChatContent {
137 }137 }
138 138
139 #[derive(Debug, Clone, SurrealValue)]139 #[derive(Debug, Clone, SurrealValue)]
140-pub struct ChatMessage {140+pub struct ChatbotMessage {
141- id: ChatMessageId,141+ id: ChatbotMessageId,
142- conversation_id: ConversationId,142+ thread_id: ChatbotThreadId,
143 user_id: UserId,143 user_id: UserId,
144 role: MessageRole,144 role: MessageRole,
145 content: ChatContent,145 content: ChatContent,
@@ -153,13 +153,13 @@ pub struct ChatMessage {
153 completed_at: Option<Timestamp>,153 completed_at: Option<Timestamp>,
154 }154 }
155 155
156-impl ChatMessage {156+impl ChatbotMessage {
157- pub fn get_id(&self) -> &ChatMessageId {157+ pub fn get_id(&self) -> &ChatbotMessageId {
158 &self.id158 &self.id
159 }159 }
160 160
161- pub fn get_conversation_id(&self) -> &ConversationId {161+ pub fn get_thread_id(&self) -> &ChatbotThreadId {
162- &self.conversation_id162+ &self.thread_id
163 }163 }
164 164
165 pub fn get_user_id(&self) -> &UserId {165 pub fn get_user_id(&self) -> &UserId {
@@ -194,7 +194,7 @@ impl ChatMessage {
194 self.completed_at194 self.completed_at
195 }195 }
196 196
197- /// A row still `pending` past [`CHAT_PENDING_STALE_SECS`] has lost the task197+ /// A row still `pending` past [`CHATBOT_PENDING_STALE_SECS`] has lost the task
198 /// that owed it an answer; present it as failed.198 /// that owed it an answer; present it as failed.
199 ///199 ///
200 /// Read-time projection, not a lazy write-back: the read paths (poll loop,200 /// Read-time projection, not a lazy write-back: the read paths (poll loop,
@@ -204,7 +204,7 @@ impl ChatMessage {
204 /// (a dead process) already happens once, at boot. The stored row stays204 /// (a dead process) already happens once, at boot. The stored row stays
205 /// truthful; only the answer handed to the caller is projected.205 /// truthful; only the answer handed to the caller is projected.
206 fn projected(mut self) -> Self {206 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;
208 if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at {208 if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at {
209 self.status = MessageStatus::Failed;209 self.status = MessageStatus::Failed;
210 self.error_code = Some(STALE_ERROR_CODE.to_string());210 self.error_code = Some(STALE_ERROR_CODE.to_string());
@@ -212,24 +212,24 @@ impl ChatMessage {
212 self212 self
213 }213 }
214 214
215- async fn insert(message: ChatMessage, db: &Database) -> Result<ChatMessage, AppError> {215+ async fn insert(message: ChatbotMessage, db: &Database) -> Result<ChatbotMessage, AppError> {
216- let created: Option<ChatMessage> = db.create(message.id.record()).content(message).await?;216+ let created: Option<ChatbotMessage> = db.create(message.id.record()).content(message).await?;
217 created.ok_or_else(|| AppError::Internal("failed to create chat message".into()))217 created.ok_or_else(|| AppError::Internal("failed to create chat message".into()))
218 }218 }
219 219
220 /// Append the user's prompt. Nothing is awaited for it, so it is born220 /// Append the user's prompt. Nothing is awaited for it, so it is born
221 /// complete.221 /// complete.
222 pub async fn append_user(222 pub async fn append_user(
223- conversation: &ConversationId,223+ thread: &ChatbotThreadId,
224 user: &UserId,224 user: &UserId,
225 content: ChatContent,225 content: ChatContent,
226 db: &Database,226 db: &Database,
227- ) -> Result<ChatMessage, AppError> {227+ ) -> Result<ChatbotMessage, AppError> {
228 let now = Timestamp::now();228 let now = Timestamp::now();
229 Self::insert(229 Self::insert(
230- ChatMessage {230+ ChatbotMessage {
231- id: ChatMessageId::generate(),231+ id: ChatbotMessageId::generate(),
232- conversation_id: conversation.clone(),232+ thread_id: thread.clone(),
233 user_id: user.clone(),233 user_id: user.clone(),
234 role: MessageRole::User,234 role: MessageRole::User,
235 content,235 content,
@@ -247,14 +247,14 @@ impl ChatMessage {
247 /// Reserve the assistant's answer *before* the AI call: the row exists,247 /// Reserve the assistant's answer *before* the AI call: the row exists,
248 /// empty and `pending`, so a reload finds the turn and can wait on it.248 /// empty and `pending`, so a reload finds the turn and can wait on it.
249 pub async fn append_pending_assistant(249 pub async fn append_pending_assistant(
250- conversation: &ConversationId,250+ thread: &ChatbotThreadId,
251 user: &UserId,251 user: &UserId,
252 db: &Database,252 db: &Database,
253- ) -> Result<ChatMessage, AppError> {253+ ) -> Result<ChatbotMessage, AppError> {
254 Self::insert(254 Self::insert(
255- ChatMessage {255+ ChatbotMessage {
256- id: ChatMessageId::generate(),256+ id: ChatbotMessageId::generate(),
257- conversation_id: conversation.clone(),257+ thread_id: thread.clone(),
258 user_id: user.clone(),258 user_id: user.clone(),
259 role: MessageRole::Assistant,259 role: MessageRole::Assistant,
260 content: ChatContent::empty(),260 content: ChatContent::empty(),
@@ -271,22 +271,22 @@ impl ChatMessage {
271 271
272 /// The whole thread, oldest first — the order both the UI and the AI272 /// The whole thread, oldest first — the order both the UI and the AI
273 /// history payload read in.273 /// history payload read in.
274- pub async fn list_for_conversation(274+ pub async fn list_for_thread(
275- conversation: &ConversationId,275+ thread: &ChatbotThreadId,
276 db: &Database,276 db: &Database,
277- ) -> Result<Vec<ChatMessage>, AppError> {277+ ) -> Result<Vec<ChatbotMessage>, AppError> {
278 let mut result = db278 let mut result = db
279 .query(279 .query(
280- "SELECT * FROM chat_message WHERE conversation_id = $conv \280+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
281 ORDER BY created_at ASC, id ASC",281 ORDER BY created_at ASC, id ASC",
282 )282 )
283- .bind(("conv", conversation.record()))283+ .bind(("conv", thread.record()))
284 .await?284 .await?
285 .check()?;285 .check()?;
286 Ok(result286 Ok(result
287- .take::<Vec<ChatMessage>>(0)?287+ .take::<Vec<ChatbotMessage>>(0)?
288 .into_iter()288 .into_iter()
289- .map(ChatMessage::projected)289+ .map(ChatbotMessage::projected)
290 .collect())290 .collect())
291 }291 }
292 292
@@ -294,23 +294,23 @@ impl ChatMessage {
294 /// AI service as context. Taken newest-first in the database (so the294 /// AI service as context. Taken newest-first in the database (so the
295 /// `LIMIT` keeps the *recent* end) and flipped back here.295 /// `LIMIT` keeps the *recent* end) and flipped back here.
296 pub async fn list_tail(296 pub async fn list_tail(
297- conversation: &ConversationId,297+ thread: &ChatbotThreadId,
298 limit: usize,298 limit: usize,
299 db: &Database,299 db: &Database,
300- ) -> Result<Vec<ChatMessage>, AppError> {300+ ) -> Result<Vec<ChatbotMessage>, AppError> {
301 let mut result = db301 let mut result = db
302 .query(302 .query(
303- "SELECT * FROM chat_message WHERE conversation_id = $conv \303+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
304 ORDER BY created_at DESC, id DESC LIMIT $limit",304 ORDER BY created_at DESC, id DESC LIMIT $limit",
305 )305 )
306- .bind(("conv", conversation.record()))306+ .bind(("conv", thread.record()))
307 .bind(("limit", limit as i64))307 .bind(("limit", limit as i64))
308 .await?308 .await?
309 .check()?;309 .check()?;
310- let mut messages: Vec<ChatMessage> = result310+ let mut messages: Vec<ChatbotMessage> = result
311- .take::<Vec<ChatMessage>>(0)?311+ .take::<Vec<ChatbotMessage>>(0)?
312 .into_iter()312 .into_iter()
313- .map(ChatMessage::projected)313+ .map(ChatbotMessage::projected)
314 .collect();314 .collect();
315 messages.reverse();315 messages.reverse();
316 Ok(messages)316 Ok(messages)
@@ -323,35 +323,35 @@ impl ChatMessage {
323 /// instead of reaching further back. No projection is applied — it only323 /// instead of reaching further back. No projection is applied — it only
324 /// ever rewrites a `pending` row, and none is selected here.324 /// ever rewrites a `pending` row, and none is selected here.
325 pub async fn list_settled_tail(325 pub async fn list_settled_tail(
326- conversation: &ConversationId,326+ thread: &ChatbotThreadId,
327 limit: usize,327 limit: usize,
328 db: &Database,328 db: &Database,
329- ) -> Result<Vec<ChatMessage>, AppError> {329+ ) -> Result<Vec<ChatbotMessage>, AppError> {
330 let mut result = db330 let mut result = db
331 .query(331 .query(
332- "SELECT * FROM chat_message WHERE conversation_id = $conv \332+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
333 AND status = 'complete' AND content != '' \333 AND status = 'complete' AND content != '' \
334 ORDER BY created_at DESC, id DESC LIMIT $limit",334 ORDER BY created_at DESC, id DESC LIMIT $limit",
335 )335 )
336- .bind(("conv", conversation.record()))336+ .bind(("conv", thread.record()))
337 .bind(("limit", limit as i64))337 .bind(("limit", limit as i64))
338 .await?338 .await?
339 .check()?;339 .check()?;
340- let mut messages: Vec<ChatMessage> = result.take(0)?;340+ let mut messages: Vec<ChatbotMessage> = result.take(0)?;
341 messages.reverse();341 messages.reverse();
342 Ok(messages)342 Ok(messages)
343 }343 }
344 344
345 /// Read one turn only if `user` owns it — the poll loop's read.345 /// Read one turn only if `user` owns it — the poll loop's read.
346 pub async fn read_for(346 pub async fn read_for(
347- id: &ChatMessageId,347+ id: &ChatbotMessageId,
348 user: &UserId,348 user: &UserId,
349 db: &Database,349 db: &Database,
350- ) -> Result<Option<ChatMessage>, AppError> {350+ ) -> Result<Option<ChatbotMessage>, AppError> {
351- let message: Option<ChatMessage> = db.select(id.record()).await?;351+ let message: Option<ChatbotMessage> = db.select(id.record()).await?;
352 Ok(message352 Ok(message
353 .filter(|message| &message.user_id == user)353 .filter(|message| &message.user_id == user)
354- .map(ChatMessage::projected))354+ .map(ChatbotMessage::projected))
355 }355 }
356 356
357 /// Land the answer, recording whether it had to be clipped to fit the357 /// Land the answer, recording whether it had to be clipped to fit the
@@ -359,32 +359,32 @@ impl ChatMessage {
359 /// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a359 /// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a
360 /// timeout) already failed, and two answers can't both apply.360 /// timeout) already failed, and two answers can't both apply.
361 pub async fn complete(361 pub async fn complete(
362- id: &ChatMessageId,362+ id: &ChatbotMessageId,
363 text: ChatContent,363 text: ChatContent,
364 truncated: bool,364 truncated: bool,
365 db: &Database,365 db: &Database,
366- ) -> Result<ChatMessage, AppError> {366+ ) -> Result<ChatbotMessage, AppError> {
367 Self::settle(id, Some(text), truncated, None, db).await367 Self::settle(id, Some(text), truncated, None, db).await
368 }368 }
369 369
370 /// Mark the answer failed with a short code (`unavailable`, the service's370 /// 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`].
372 pub async fn fail(372 pub async fn fail(
373- id: &ChatMessageId,373+ id: &ChatbotMessageId,
374 error_code: &str,374 error_code: &str,
375 db: &Database,375 db: &Database,
376- ) -> Result<ChatMessage, AppError> {376+ ) -> Result<ChatbotMessage, AppError> {
377 // A failed turn has no text, so there is nothing that could be clipped.377 // A failed turn has no text, so there is nothing that could be clipped.
378 Self::settle(id, None, false, Some(error_code), db).await378 Self::settle(id, None, false, Some(error_code), db).await
379 }379 }
380 380
381 async fn settle(381 async fn settle(
382- id: &ChatMessageId,382+ id: &ChatbotMessageId,
383 text: Option<ChatContent>,383 text: Option<ChatContent>,
384 truncated: bool,384 truncated: bool,
385 error_code: Option<&str>,385 error_code: Option<&str>,
386 db: &Database,386 db: &Database,
387- ) -> Result<ChatMessage, AppError> {387+ ) -> Result<ChatbotMessage, AppError> {
388 let status = if text.is_some() {388 let status = if text.is_some() {
389 MessageStatus::Complete389 MessageStatus::Complete
390 } else {390 } else {
@@ -407,7 +407,7 @@ impl ChatMessage {
407 .await?407 .await?
408 .check()?;408 .check()?;
409 result409 result
410- .take::<Vec<ChatMessage>>(0)?410+ .take::<Vec<ChatbotMessage>>(0)?
411 .into_iter()411 .into_iter()
412 .next()412 .next()
413 .ok_or(AppError::NotFound)413 .ok_or(AppError::NotFound)
@@ -422,8 +422,8 @@ mod tests {
422 #[tokio::test]422 #[tokio::test]
423 async fn content_is_required_and_capped() {423 async fn content_is_required_and_capped() {
424 assert!(ChatContent::try_new("").is_err());424 assert!(ChatContent::try_new("").is_err());
425- assert!(ChatContent::try_new(&"x".repeat(MAX_CHAT_MESSAGE_LEN)).is_ok());425+ assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN)).is_ok());
426- assert!(ChatContent::try_new(&"x".repeat(MAX_CHAT_MESSAGE_LEN + 1)).is_err());426+ assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err());
427 }427 }
428 428
429 #[tokio::test]429 #[tokio::test]
@@ -455,24 +455,24 @@ mod tests {
455 // inverted a fifth of the pairs; here every pair must read back455 // inverted a fifth of the pairs; here every pair must read back
456 // question-then-answer, from both read paths.456 // question-then-answer, from both read paths.
457 let db = crate::database::init_mem().await.unwrap();457 let db = crate::database::init_mem().await.unwrap();
458- let conversation = ConversationId::from_key("c");458+ let thread = ChatbotThreadId::from_key("c");
459 let user = UserId::from_key("u");459 let user = UserId::from_key("u");
460 const TURNS: usize = 200;460 const TURNS: usize = 200;
461 461
462 for turn in 0..TURNS {462 for turn in 0..TURNS {
463 let content = ChatContent::try_new(&format!("soru {turn}")).unwrap();463 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)
465 .await465 .await
466 .unwrap();466 .unwrap();
467- ChatMessage::append_pending_assistant(&conversation, &user, &db)467+ ChatbotMessage::append_pending_assistant(&thread, &user, &db)
468 .await468 .await
469 .unwrap();469 .unwrap();
470 }470 }
471 471
472- let whole = ChatMessage::list_for_conversation(&conversation, &db)472+ let whole = ChatbotMessage::list_for_thread(&thread, &db)
473 .await473 .await
474 .unwrap();474 .unwrap();
475- let tail = ChatMessage::list_tail(&conversation, TURNS * 2, &db)475+ let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)
476 .await476 .await
477 .unwrap();477 .unwrap();
478 for messages in [&whole, &tail] {478 for messages in [&whole, &tail] {
@@ -488,9 +488,9 @@ mod tests {
488 #[tokio::test]488 #[tokio::test]
489 async fn stale_pending_projects_as_failed() {489 async fn stale_pending_projects_as_failed() {
490 let aged = |secs: i64| {490 let aged = |secs: i64| {
491- ChatMessage {491+ ChatbotMessage {
492- id: ChatMessageId::generate(),492+ id: ChatbotMessageId::generate(),
493- conversation_id: ConversationId::from_key("c"),493+ thread_id: ChatbotThreadId::from_key("c"),
494 user_id: UserId::from_key("u"),494 user_id: UserId::from_key("u"),
495 role: MessageRole::Assistant,495 role: MessageRole::Assistant,
496 content: ChatContent::empty(),496 content: ChatContent::empty(),
@@ -507,7 +507,7 @@ mod tests {
507 assert_eq!(fresh.get_status(), MessageStatus::Pending);507 assert_eq!(fresh.get_status(), MessageStatus::Pending);
508 assert_eq!(fresh.get_error_code(), None);508 assert_eq!(fresh.get_error_code(), None);
509 509
510- let stale = aged(CHAT_PENDING_STALE_SECS + 1);510+ let stale = aged(CHATBOT_PENDING_STALE_SECS + 1);
511 assert_eq!(stale.get_status(), MessageStatus::Failed);511 assert_eq!(stale.get_status(), MessageStatus::Failed);
512 assert_eq!(stale.get_error_code(), Some(STALE_ERROR_CODE));512 assert_eq!(stale.get_error_code(), Some(STALE_ERROR_CODE));
513 }513 }
src/domain/conversation.rs → src/domain/chatbot_thread.rsrenamed+59 -59
@@ -1,40 +1,40 @@
1 //! A chatbot thread. It only groups turns and carries the ordering key the1 //! A chatbot thread. It only groups turns and carries the ordering key the
2 //! list view sorts on: `updated_at` moves on every new turn, so a user's2 //! 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 in3+//! threads list newest-activity-first. The turns themselves live in
4-//! [`crate::domain::chat_message`], and deleting a conversation cascades them.4+//! [`crate::domain::chatbot_message`], and deleting a thread cascades them.
5 5
6 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};6 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
7 use tokio::sync::Mutex;7 use tokio::sync::Mutex;
8 use ulid::Ulid;8 use ulid::Ulid;
9 9
10-use crate::database::{CONVERSATION_TABLE, Database};10+use crate::database::{CHATBOT_THREAD_TABLE, Database};
11 use crate::domain::settings::Settings;11 use crate::domain::settings::Settings;
12 use crate::domain::timestamp::Timestamp;12 use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::UserId;13 use crate::domain::user::UserId;
14 use crate::error::{AppError, ValidationError};14 use crate::error::{AppError, ValidationError};
15 use crate::validate::validate_required;15 use crate::validate::validate_required;
16 16
17-/// Serializes thread creation so the `max_chat_conversations` check (count,17+/// Serializes thread creation so the `max_chatbot_threads` check (count,
18 /// then write) can't over-admit under concurrency — the database's optimistic18 /// then write) can't over-admit under concurrency — the database's optimistic
19 /// transactions don't serialize cross-record counts against concurrent19 /// transactions don't serialize cross-record counts against concurrent
20 /// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`.20 /// 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(());
22 22
23 /// Bound on a thread's display name. Local to this module because23 /// Bound on a thread's display name. Local to this module because
24 /// `constant.rs` is another task's file; move it there with the rest of the24 /// `constant.rs` is another task's file; move it there with the rest of the
25 /// chat limits when they are next touched.25 /// chat limits when they are next touched.
26-const MAX_CONVERSATION_TITLE_LEN: usize = 200;26+const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200;
27 27
28 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]28 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
29-pub struct ConversationId(RecordId);29+pub struct ChatbotThreadId(RecordId);
30 30
31-impl ConversationId {31+impl ChatbotThreadId {
32 pub fn generate() -> Self {32 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()))
34 }34 }
35 35
36 pub fn from_key(key: &str) -> Self {36 pub fn from_key(key: &str) -> Self {
37- Self(RecordId::new(CONVERSATION_TABLE, key))37+ Self(RecordId::new(CHATBOT_THREAD_TABLE, key))
38 }38 }
39 39
40 pub fn record(&self) -> RecordId {40 pub fn record(&self) -> RecordId {
@@ -50,13 +50,13 @@ impl ConversationId {
50 }50 }
51 51
52 /// A user-chosen thread name. Required-and-bounded here; "untitled" is52 /// A user-chosen thread name. Required-and-bounded here; "untitled" is
53-/// `Option<ConversationTitle>` on the row.53+/// `Option<ChatbotThreadTitle>` on the row.
54 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]54 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
55-pub struct ConversationTitle(String);55+pub struct ChatbotThreadTitle(String);
56 56
57-impl ConversationTitle {57+impl ChatbotThreadTitle {
58 pub fn try_new(value: &str) -> Result<Self, ValidationError> {58 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)?;
60 Ok(Self(value.to_string()))60 Ok(Self(value.to_string()))
61 }61 }
62 62
@@ -66,16 +66,16 @@ impl ConversationTitle {
66 }66 }
67 67
68 #[derive(Debug, Clone, SurrealValue)]68 #[derive(Debug, Clone, SurrealValue)]
69-pub struct Conversation {69+pub struct ChatbotThread {
70- id: ConversationId,70+ id: ChatbotThreadId,
71 user_id: UserId,71 user_id: UserId,
72- title: Option<ConversationTitle>,72+ title: Option<ChatbotThreadTitle>,
73 created_at: Timestamp,73 created_at: Timestamp,
74 updated_at: Timestamp,74 updated_at: Timestamp,
75 }75 }
76 76
77-impl Conversation {77+impl ChatbotThread {
78- pub fn get_id(&self) -> &ConversationId {78+ pub fn get_id(&self) -> &ChatbotThreadId {
79 &self.id79 &self.id
80 }80 }
81 81
@@ -83,7 +83,7 @@ impl Conversation {
83 &self.user_id83 &self.user_id
84 }84 }
85 85
86- pub fn get_title(&self) -> Option<&ConversationTitle> {86+ pub fn get_title(&self) -> Option<&ChatbotThreadTitle> {
87 self.title.as_ref()87 self.title.as_ref()
88 }88 }
89 89
@@ -97,62 +97,62 @@ impl Conversation {
97 97
98 pub async fn create(98 pub async fn create(
99 user: &UserId,99 user: &UserId,
100- title: Option<ConversationTitle>,100+ title: Option<ChatbotThreadTitle>,
101 db: &Database,101 db: &Database,
102- ) -> Result<Conversation, AppError> {102+ ) -> Result<ChatbotThread, AppError> {
103 let now = Timestamp::now();103 let now = Timestamp::now();
104- let conversation = Conversation {104+ let thread = ChatbotThread {
105- id: ConversationId::generate(),105+ id: ChatbotThreadId::generate(),
106 user_id: user.clone(),106 user_id: user.clone(),
107 title,107 title,
108 created_at: now,108 created_at: now,
109 updated_at: now,109 updated_at: now,
110 };110 };
111- let created: Option<Conversation> = db111+ let created: Option<ChatbotThread> = db
112- .create(conversation.id.record())112+ .create(thread.id.record())
113- .content(conversation)113+ .content(thread)
114 .await?;114 .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()))
116 }116 }
117 117
118 /// Start a thread unless `user` is already at the school's118 /// Start a thread unless `user` is already at the school's
119- /// `max_chat_conversations`. The whole check-then-write runs under119+ /// `max_chatbot_threads`. The whole check-then-write runs under
120- /// [`CONVERSATION_LOCK`], and the cap is re-read inside it, since neither120+ /// [`CHATBOT_THREAD_LOCK`], and the cap is re-read inside it, since neither
121 /// the transaction model nor a caller-supplied number survives a concurrent121 /// the transaction model nor a caller-supplied number survives a concurrent
122 /// settings PATCH.122 /// settings PATCH.
123 pub async fn create_capped(123 pub async fn create_capped(
124 user: &UserId,124 user: &UserId,
125- title: Option<ConversationTitle>,125+ title: Option<ChatbotThreadTitle>,
126 db: &Database,126 db: &Database,
127- ) -> Result<Conversation, AppError> {127+ ) -> Result<ChatbotThread, AppError> {
128- let _guard = CONVERSATION_LOCK.lock().await;128+ let _guard = CHATBOT_THREAD_LOCK.lock().await;
129- let cap = Settings::load(db).await?.get_max_chat_conversations();129+ let cap = Settings::load(db).await?.get_max_chatbot_threads();
130 if Self::count_for_user(user, db).await? as i64 >= cap {130 if Self::count_for_user(user, db).await? as i64 >= cap {
131 return Err(AppError::Conflict(131 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",
133 ));133 ));
134 }134 }
135 Self::create(user, title, db).await135 Self::create(user, title, db).await
136 }136 }
137 137
138 /// A user's threads, most recently active first — the sort the138 /// 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.
140 pub async fn list_for_user(140 pub async fn list_for_user(
141 user: &UserId,141 user: &UserId,
142 db: &Database,142 db: &Database,
143- ) -> Result<Vec<Conversation>, AppError> {143+ ) -> Result<Vec<ChatbotThread>, AppError> {
144 let mut result = db144 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")
146 .bind(("usr", user.record()))146 .bind(("usr", user.record()))
147 .await?147 .await?
148 .check()?;148 .check()?;
149- Ok(result.take::<Vec<Conversation>>(0)?)149+ Ok(result.take::<Vec<ChatbotThread>>(0)?)
150 }150 }
151 151
152- /// How many threads `user` keeps — the `max_chat_conversations` cap check.152+ /// How many threads `user` keeps — the `max_chatbot_threads` cap check.
153 pub async fn count_for_user(user: &UserId, db: &Database) -> Result<usize, AppError> {153 pub async fn count_for_user(user: &UserId, db: &Database) -> Result<usize, AppError> {
154 let mut result = db154 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")
156 .bind(("usr", user.record()))156 .bind(("usr", user.record()))
157 .await?157 .await?
158 .check()?;158 .check()?;
@@ -167,17 +167,17 @@ impl Conversation {
167 /// Read a thread only if `user` owns it — a foreign id reads as absent, so167 /// Read a thread only if `user` owns it — a foreign id reads as absent, so
168 /// the web layer answers 404 rather than leaking that it exists.168 /// the web layer answers 404 rather than leaking that it exists.
169 pub async fn read_for(169 pub async fn read_for(
170- id: &ConversationId,170+ id: &ChatbotThreadId,
171 user: &UserId,171 user: &UserId,
172 db: &Database,172 db: &Database,
173- ) -> Result<Option<Conversation>, AppError> {173+ ) -> Result<Option<ChatbotThread>, AppError> {
174- let conversation: Option<Conversation> = db.select(id.record()).await?;174+ let thread: Option<ChatbotThread> = db.select(id.record()).await?;
175- Ok(conversation.filter(|conversation| &conversation.user_id == user))175+ Ok(thread.filter(|thread| &thread.user_id == user))
176 }176 }
177 177
178 /// Stamp new activity. Field-scoped: a rename may be landing concurrently,178 /// Stamp new activity. Field-scoped: a rename may be landing concurrently,
179 /// and a whole-row save would clobber it.179 /// 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> {
181 let mut result = db181 let mut result = db
182 .query("UPDATE $id SET updated_at = $now RETURN AFTER")182 .query("UPDATE $id SET updated_at = $now RETURN AFTER")
183 .bind(("id", self.id.record()))183 .bind(("id", self.id.record()))
@@ -185,7 +185,7 @@ impl Conversation {
185 .await?185 .await?
186 .check()?;186 .check()?;
187 result187 result
188- .take::<Vec<Conversation>>(0)?188+ .take::<Vec<ChatbotThread>>(0)?
189 .into_iter()189 .into_iter()
190 .next()190 .next()
191 .ok_or(AppError::NotFound)191 .ok_or(AppError::NotFound)
@@ -193,12 +193,12 @@ impl Conversation {
193 193
194 /// Rename the thread (`None` clears the name back to untitled), stamping194 /// Rename the thread (`None` clears the name back to untitled), stamping
195 /// the edit as activity. Field-scoped for the same reason as195 /// 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.
197 pub async fn rename(197 pub async fn rename(
198 &self,198 &self,
199- title: Option<ConversationTitle>,199+ title: Option<ChatbotThreadTitle>,
200 db: &Database,200 db: &Database,
201- ) -> Result<Conversation, AppError> {201+ ) -> Result<ChatbotThread, AppError> {
202 let mut result = db202 let mut result = db
203 .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER")203 .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER")
204 .bind(("id", self.id.record()))204 .bind(("id", self.id.record()))
@@ -207,27 +207,27 @@ impl Conversation {
207 .await?207 .await?
208 .check()?;208 .check()?;
209 result209 result
210- .take::<Vec<Conversation>>(0)?210+ .take::<Vec<ChatbotThread>>(0)?
211 .into_iter()211 .into_iter()
212 .next()212 .next()
213 .ok_or(AppError::NotFound)213 .ok_or(AppError::NotFound)
214 }214 }
215 215
216 /// Delete the thread and every turn in it — one transaction, so a crash216 /// Delete the thread and every turn in it — one transaction, so a crash
217- /// can't orphan messages under a vanished conversation.217+ /// can't orphan messages under a vanished thread.
218- pub async fn delete(self, db: &Database) -> Result<Conversation, AppError> {218+ pub async fn delete(self, db: &Database) -> Result<ChatbotThread, AppError> {
219 let mut result = db219 let mut result = db
220 .query(220 .query(
221 "BEGIN TRANSACTION;221 "BEGIN TRANSACTION;
222- DELETE chat_message WHERE conversation_id = $conv;222+ DELETE chatbot_message WHERE thread_id = $conv;
223 DELETE $conv RETURN BEFORE;223 DELETE $conv RETURN BEFORE;
224 COMMIT TRANSACTION;",224 COMMIT TRANSACTION;",
225 )225 )
226 .bind(("conv", self.id.record()))226 .bind(("conv", self.id.record()))
227 .await?227 .await?
228 .check()?;228 .check()?;
229- // BEGIN is slot 0; the conversation's own DELETE is slot 2.229+ // BEGIN is slot 0; the thread's own DELETE is slot 2.
230- let deleted: Option<Conversation> = result.take::<Vec<Conversation>>(2)?.into_iter().next();230+ let deleted: Option<ChatbotThread> = result.take::<Vec<ChatbotThread>>(2)?.into_iter().next();
231 deleted.ok_or(AppError::NotFound)231 deleted.ok_or(AppError::NotFound)
232 }232 }
233 }233 }
@@ -239,10 +239,10 @@ mod tests {
239 #[tokio::test]239 #[tokio::test]
240 async fn title_is_required_and_bounded() {240 async fn title_is_required_and_bounded() {
241 assert_eq!(241 assert_eq!(
242- ConversationTitle::try_new("Fizik").unwrap().as_str(),242+ ChatbotThreadTitle::try_new("Fizik").unwrap().as_str(),
243 "Fizik"243 "Fizik"
244 );244 );
245- assert!(ConversationTitle::try_new(" ").is_err());245+ assert!(ChatbotThreadTitle::try_new(" ").is_err());
246- assert!(ConversationTitle::try_new(&"x".repeat(201)).is_err());246+ assert!(ChatbotThreadTitle::try_new(&"x".repeat(201)).is_err());
247 }247 }
248 }248 }
src/domain/mod.rsmodified+2 -2
@@ -6,8 +6,8 @@ pub mod answer_image;
6 pub mod appointment;6 pub mod appointment;
7 pub mod appointment_slot;7 pub mod appointment_slot;
8 pub mod attendance;8 pub mod attendance;
9-pub mod chat_message;9+pub mod chatbot_message;
10-pub mod conversation;10+pub mod chatbot_thread;
11 pub mod course;11 pub mod course;
12 pub mod course_session;12 pub mod course_session;
13 pub mod enrollment;13 pub mod enrollment;
src/domain/settings.rsmodified+77 -77
@@ -14,12 +14,12 @@
14 use surrealdb::types::{RecordId, SurrealValue};14 use surrealdb::types::{RecordId, SurrealValue};
15 15
16 use crate::constant::{16 use crate::constant::{
17- DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHAT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,17+ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,
18- DEFAULT_MAX_CHAT_CONVERSATIONS, DEFAULT_MAX_CHAT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES,18+ DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES,
19- MAX_CHAT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK,19+ MAX_CHATBOT_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,20+ MAX_MAX_CHATBOT_THREADS, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_FILE_BYTES,
21- MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHAT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,21+ MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,
22- MIN_MARK, MIN_MAX_CHAT_CONVERSATIONS, MIN_MAX_CHAT_MESSAGE_LEN, MIN_MAX_FILE_BYTES,22+ MIN_MARK, MIN_MAX_CHATBOT_THREADS, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_FILE_BYTES,
23 };23 };
24 use crate::database::{Database, SETTINGS_TABLE};24 use crate::database::{Database, SETTINGS_TABLE};
25 use crate::error::{AppError, ValidationError};25 use crate::error::{AppError, ValidationError};
@@ -118,9 +118,9 @@ pub struct Settings {
118 /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`.118 /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`.
119 max_file_bytes: Option<i64>,119 max_file_bytes: Option<i64>,
120 /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`.120 /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`.
121- chat_history_turns: Option<i64>,121+ chatbot_history_turns: Option<i64>,
122- max_chat_conversations: Option<i64>,122+ max_chatbot_threads: Option<i64>,
123- max_chat_message_len: Option<i64>,123+ max_chatbot_message_len: Option<i64>,
124 }124 }
125 125
126 /// Everything [`Settings::try_new`] validates, in one struct — the knobs126 /// Everything [`Settings::try_new`] validates, in one struct — the knobs
@@ -132,9 +132,9 @@ pub struct SettingsParams {
132 pub attendance_statuses: Vec<String>,132 pub attendance_statuses: Vec<String>,
133 pub grade_bands: Vec<GradeBand>,133 pub grade_bands: Vec<GradeBand>,
134 pub max_file_bytes: i64,134 pub max_file_bytes: i64,
135- pub chat_history_turns: i64,135+ pub chatbot_history_turns: i64,
136- pub max_chat_conversations: i64,136+ pub max_chatbot_threads: i64,
137- pub max_chat_message_len: i64,137+ pub max_chatbot_message_len: i64,
138 }138 }
139 139
140 impl Settings {140 impl Settings {
@@ -156,9 +156,9 @@ impl Settings {
156 attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(),156 attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(),
157 grade_bands: Vec::new(),157 grade_bands: Vec::new(),
158 max_file_bytes: None,158 max_file_bytes: None,
159- chat_history_turns: None,159+ chatbot_history_turns: None,
160- max_chat_conversations: None,160+ max_chatbot_threads: None,
161- max_chat_message_len: None,161+ max_chatbot_message_len: None,
162 }162 }
163 }163 }
164 164
@@ -170,9 +170,9 @@ impl Settings {
170 attendance_statuses: self.attendance_statuses.clone(),170 attendance_statuses: self.attendance_statuses.clone(),
171 grade_bands: self.grade_bands.clone(),171 grade_bands: self.grade_bands.clone(),
172 max_file_bytes: self.get_max_file_bytes(),172 max_file_bytes: self.get_max_file_bytes(),
173- chat_history_turns: self.get_chat_history_turns(),173+ chatbot_history_turns: self.get_chatbot_history_turns(),
174- max_chat_conversations: self.get_max_chat_conversations(),174+ max_chatbot_threads: self.get_max_chatbot_threads(),
175- max_chat_message_len: self.get_max_chat_message_len(),175+ max_chatbot_message_len: self.get_max_chatbot_message_len(),
176 }176 }
177 }177 }
178 178
@@ -190,9 +190,9 @@ impl Settings {
190 attendance_statuses,190 attendance_statuses,
191 grade_bands,191 grade_bands,
192 max_file_bytes,192 max_file_bytes,
193- chat_history_turns,193+ chatbot_history_turns,
194- max_chat_conversations,194+ max_chatbot_threads,
195- max_chat_message_len,195+ max_chatbot_message_len,
196 } = params;196 } = params;
197 in_range(197 in_range(
198 "max_file_bytes",198 "max_file_bytes",
@@ -201,21 +201,21 @@ impl Settings {
201 "must be between 1024 (1 KiB) and 26214400 (25 MiB)",201 "must be between 1024 (1 KiB) and 26214400 (25 MiB)",
202 )?;202 )?;
203 in_range(203 in_range(
204- "chat_history_turns",204+ "chatbot_history_turns",
205- chat_history_turns,205+ chatbot_history_turns,
206- MIN_CHAT_HISTORY_TURNS..=MAX_CHAT_HISTORY_TURNS,206+ MIN_CHATBOT_HISTORY_TURNS..=MAX_CHATBOT_HISTORY_TURNS,
207 "must be between 1 and 50",207 "must be between 1 and 50",
208 )?;208 )?;
209 in_range(209 in_range(
210- "max_chat_conversations",210+ "max_chatbot_threads",
211- max_chat_conversations,211+ max_chatbot_threads,
212- MIN_MAX_CHAT_CONVERSATIONS..=MAX_MAX_CHAT_CONVERSATIONS,212+ MIN_MAX_CHATBOT_THREADS..=MAX_MAX_CHATBOT_THREADS,
213 "must be between 1 and 500",213 "must be between 1 and 500",
214 )?;214 )?;
215 in_range(215 in_range(
216- "max_chat_message_len",216+ "max_chatbot_message_len",
217- max_chat_message_len,217+ max_chatbot_message_len,
218- MIN_MAX_CHAT_MESSAGE_LEN..=MAX_MAX_CHAT_MESSAGE_LEN,218+ MIN_MAX_CHATBOT_MESSAGE_LEN..=MAX_MAX_CHATBOT_MESSAGE_LEN,
219 "must be between 100 and 8000 characters",219 "must be between 100 and 8000 characters",
220 )?;220 )?;
221 // Per-entry rules (name shape, weight range) hold structurally on any221 // Per-entry rules (name shape, weight range) hold structurally on any
@@ -267,9 +267,9 @@ impl Settings {
267 attendance_statuses,267 attendance_statuses,
268 grade_bands,268 grade_bands,
269 max_file_bytes: Some(max_file_bytes),269 max_file_bytes: Some(max_file_bytes),
270- chat_history_turns: Some(chat_history_turns),270+ chatbot_history_turns: Some(chatbot_history_turns),
271- max_chat_conversations: Some(max_chat_conversations),271+ max_chatbot_threads: Some(max_chatbot_threads),
272- max_chat_message_len: Some(max_chat_message_len),272+ max_chatbot_message_len: Some(max_chatbot_message_len),
273 })273 })
274 }274 }
275 275
@@ -302,25 +302,25 @@ impl Settings {
302 self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES)302 self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES)
303 }303 }
304 304
305- /// How many prior conversation turns ride along as context on an AI305+ /// How many prior thread turns ride along as context on an AI
306 /// request; the built-in default while the school never set one.306 /// request; the built-in default while the school never set one.
307- pub fn get_chat_history_turns(&self) -> i64 {307+ pub fn get_chatbot_history_turns(&self) -> i64 {
308- self.chat_history_turns308+ self.chatbot_history_turns
309- .unwrap_or(DEFAULT_CHAT_HISTORY_TURNS)309+ .unwrap_or(DEFAULT_CHATBOT_HISTORY_TURNS)
310 }310 }
311 311
312- /// How many conversations one user may keep; the built-in default while312+ /// How many threads one user may keep; the built-in default while
313 /// the school never set one.313 /// the school never set one.
314- pub fn get_max_chat_conversations(&self) -> i64 {314+ pub fn get_max_chatbot_threads(&self) -> i64 {
315- self.max_chat_conversations315+ self.max_chatbot_threads
316- .unwrap_or(DEFAULT_MAX_CHAT_CONVERSATIONS)316+ .unwrap_or(DEFAULT_MAX_CHATBOT_THREADS)
317 }317 }
318 318
319 /// Character cap on one chat message; the built-in default while the319 /// Character cap on one chat message; the built-in default while the
320 /// school never set one.320 /// school never set one.
321- pub fn get_max_chat_message_len(&self) -> i64 {321+ pub fn get_max_chatbot_message_len(&self) -> i64 {
322- self.max_chat_message_len322+ self.max_chatbot_message_len
323- .unwrap_or(DEFAULT_MAX_CHAT_MESSAGE_LEN)323+ .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN)
324 }324 }
325 325
326 /// The label of the band `mark` falls into: the band with the greatest326 /// The label of the band `mark` falls into: the band with the greatest
@@ -374,9 +374,9 @@ impl Settings {
374 AND attendance_statuses = $st374 AND attendance_statuses = $st
375 AND grade_bands = $gb375 AND grade_bands = $gb
376 AND max_file_bytes = $mf376 AND max_file_bytes = $mf
377- AND chat_history_turns = $ct377+ AND chatbot_history_turns = $ct
378- AND max_chat_conversations = $cc378+ AND max_chatbot_threads = $cc
379- AND max_chat_message_len = $cl;379+ AND max_chatbot_message_len = $cl;
380 COMMIT TRANSACTION;",380 COMMIT TRANSACTION;",
381 )381 )
382 .bind(("expected", expected.clone()))382 .bind(("expected", expected.clone()))
@@ -386,9 +386,9 @@ impl Settings {
386 .bind(("st", expected.attendance_statuses.clone()))386 .bind(("st", expected.attendance_statuses.clone()))
387 .bind(("gb", expected.grade_bands.clone()))387 .bind(("gb", expected.grade_bands.clone()))
388 .bind(("mf", expected.max_file_bytes))388 .bind(("mf", expected.max_file_bytes))
389- .bind(("ct", expected.chat_history_turns))389+ .bind(("ct", expected.chatbot_history_turns))
390- .bind(("cc", expected.max_chat_conversations))390+ .bind(("cc", expected.max_chatbot_threads))
391- .bind(("cl", expected.max_chat_message_len))391+ .bind(("cl", expected.max_chatbot_message_len))
392 .await?392 .await?
393 .check()?;393 .check()?;
394 // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An394 // 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>
450 #[cfg(test)]450 #[cfg(test)]
451 mod tests {451 mod tests {
452 use super::*;452 use super::*;
453- use crate::constant::MAX_CHAT_MESSAGE_LEN;453+ use crate::constant::MAX_CHATBOT_MESSAGE_LEN;
454 454
455 fn kinds(list: &[&str]) -> Vec<ExamKindDef> {455 fn kinds(list: &[&str]) -> Vec<ExamKindDef> {
456 list.iter()456 list.iter()
@@ -618,49 +618,49 @@ mod tests {
618 #[tokio::test]618 #[tokio::test]
619 async fn chat_knobs_are_bounded() {619 async fn chat_knobs_are_bounded() {
620 // Each knob is held to its own inclusive range; the edges are legal.620 // 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| {
622 Settings::try_new(SettingsParams {622 Settings::try_new(SettingsParams {
623- chat_history_turns,623+ chatbot_history_turns,
624 ..params()624 ..params()
625 })625 })
626 };626 };
627 assert_eq!(627 assert_eq!(
628- turns(MAX_CHAT_HISTORY_TURNS)628+ turns(MAX_CHATBOT_HISTORY_TURNS)
629 .unwrap()629 .unwrap()
630- .get_chat_history_turns(),630+ .get_chatbot_history_turns(),
631- MAX_CHAT_HISTORY_TURNS631+ MAX_CHATBOT_HISTORY_TURNS
632 );632 );
633- assert!(turns(MIN_CHAT_HISTORY_TURNS).is_ok());633+ assert!(turns(MIN_CHATBOT_HISTORY_TURNS).is_ok());
634 assert!(turns(0).is_err());634 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());
636 636
637- let convos = |max_chat_conversations| {637+ let convos = |max_chatbot_threads| {
638 Settings::try_new(SettingsParams {638 Settings::try_new(SettingsParams {
639- max_chat_conversations,639+ max_chatbot_threads,
640 ..params()640 ..params()
641 })641 })
642 };642 };
643 assert_eq!(643 assert_eq!(
644- convos(7).unwrap().get_max_chat_conversations(),644+ convos(7).unwrap().get_max_chatbot_threads(),
645 7,645 7,
646 "an in-range cap survives validation"646 "an in-range cap survives validation"
647 );647 );
648- assert!(convos(MIN_MAX_CHAT_CONVERSATIONS).is_ok());648+ assert!(convos(MIN_MAX_CHATBOT_THREADS).is_ok());
649- assert!(convos(MAX_MAX_CHAT_CONVERSATIONS).is_ok());649+ assert!(convos(MAX_MAX_CHATBOT_THREADS).is_ok());
650 assert!(convos(0).is_err());650 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());
652 652
653- let len = |max_chat_message_len| {653+ let len = |max_chatbot_message_len| {
654 Settings::try_new(SettingsParams {654 Settings::try_new(SettingsParams {
655- max_chat_message_len,655+ max_chatbot_message_len,
656 ..params()656 ..params()
657 })657 })
658 };658 };
659- assert!(len(MIN_MAX_CHAT_MESSAGE_LEN).is_ok());659+ assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN).is_ok());
660- assert!(len(MAX_MAX_CHAT_MESSAGE_LEN).is_ok());660+ assert!(len(MAX_MAX_CHATBOT_MESSAGE_LEN).is_ok());
661- assert!(len(MIN_MAX_CHAT_MESSAGE_LEN - 1).is_err());661+ assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN - 1).is_err());
662 // The ceiling is the newtype's hard cap: no school can raise it.662 // 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());
664 }664 }
665 665
666 #[tokio::test]666 #[tokio::test]
@@ -671,14 +671,14 @@ mod tests {
671 Settings::defaults().save(&db).await.unwrap();671 Settings::defaults().save(&db).await.unwrap();
672 let loaded = Settings::load(&db).await.unwrap();672 let loaded = Settings::load(&db).await.unwrap();
673 assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);673 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);
675 assert_eq!(675 assert_eq!(
676- loaded.get_max_chat_conversations(),676+ loaded.get_max_chatbot_threads(),
677- DEFAULT_MAX_CHAT_CONVERSATIONS677+ DEFAULT_MAX_CHATBOT_THREADS
678 );678 );
679 assert_eq!(679 assert_eq!(
680- loaded.get_max_chat_message_len(),680+ loaded.get_max_chatbot_message_len(),
681- DEFAULT_MAX_CHAT_MESSAGE_LEN681+ DEFAULT_MAX_CHATBOT_MESSAGE_LEN
682 );682 );
683 // And a snapshot of that old row still passes the compare-and-set.683 // And a snapshot of that old row still passes the compare-and-set.
684 let saved = Settings::try_new(SettingsParams {684 let saved = Settings::try_new(SettingsParams {
@@ -708,7 +708,7 @@ mod tests {
708 exam_kinds: kinds(&["lab"]),708 exam_kinds: kinds(&["lab"]),
709 grade_bands: bands(&[(0, "F"), (50, "P")]),709 grade_bands: bands(&[(0, "F"), (50, "P")]),
710 max_file_bytes: 2048,710 max_file_bytes: 2048,
711- chat_history_turns: 3,711+ chatbot_history_turns: 3,
712 ..params()712 ..params()
713 })713 })
714 .unwrap()714 .unwrap()
@@ -720,7 +720,7 @@ mod tests {
720 assert_eq!(loaded.get_grade_bands().len(), 2);720 assert_eq!(loaded.get_grade_bands().len(), 2);
721 assert_eq!(loaded.grade_label(60.0), Some("P"));721 assert_eq!(loaded.grade_label(60.0), Some("P"));
722 assert_eq!(loaded.get_max_file_bytes(), 2048);722 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);
724 // A second save lands on the same singleton row, not a new one.724 // A second save lands on the same singleton row, not a new one.
725 Settings::try_new(SettingsParams {725 Settings::try_new(SettingsParams {
726 exam_kinds: kinds(&["quiz"]),726 exam_kinds: kinds(&["quiz"]),
src/lib.rsmodified+2 -2
@@ -42,7 +42,7 @@ use crate::state::AppState;
42 (name = "meta", description = "Liveness and service metadata"),42 (name = "meta", description = "Liveness and service metadata"),
43 (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"),43 (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"),
44 (name = "auth", description = "Registration, login, session lifecycle"),44 (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"),
46 (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"),46 (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"),
47 (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`)"),47 (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`)"),
48 (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"),48 (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 {
90 .routes(routes!(server_time))90 .routes(routes!(server_time))
91 .nest("/ai", web::ai::routes())91 .nest("/ai", web::ai::routes())
92 .nest("/auth", web::auth::routes(&state.rate_limit))92 .nest("/auth", web::auth::routes(&state.rate_limit))
93- .nest("/chat", web::chat::routes())93+ .nest("/chatbot", web::chatbot::routes())
94 .nest("/users", web::users::routes())94 .nest("/users", web::users::routes())
95 .nest("/notes", web::notes::routes())95 .nest("/notes", web::notes::routes())
96 .nest("/messages", web::messages::routes())96 .nest("/messages", web::messages::routes())
src/main.rsmodified+1 -1
@@ -30,7 +30,7 @@ async fn main() -> anyhow::Result<()> {
30 files_path: cfg.files_path.clone().into(),30 files_path: cfg.files_path.clone().into(),
31 cookie_secure: cfg.cookie_secure,31 cookie_secure: cfg.cookie_secure,
32 rate_limit: cfg.rate_limit.clone(),32 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),
34 exam_presence: Default::default(),34 exam_presence: Default::default(),
35 db_up,35 db_up,
36 ai,36 ai,
src/rate_limit.rsmodified+3 -3
@@ -95,13 +95,13 @@ impl Default for UserRateLimiter {
95 /// The chatbot tier at its shipped default, for tests and any caller that95 /// The chatbot tier at its shipped default, for tests and any caller that
96 /// has no [`crate::config::Config`] to hand.96 /// has no [`crate::config::Config`] to hand.
97 fn default() -> Self {97 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)
99 }99 }
100 }100 }
101 101
102 impl UserRateLimiter {102 impl UserRateLimiter {
103 /// The chatbot tier: `max` messages per user per minute, from103 /// 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.
105 pub fn per_user_minute(max: u32) -> Self {105 pub fn per_user_minute(max: u32) -> Self {
106 Self::new(max, false)106 Self::new(max, false)
107 }107 }
@@ -346,7 +346,7 @@ mod tests {
346 #[tokio::test(start_paused = true)]346 #[tokio::test(start_paused = true)]
347 async fn users_get_independent_windows_that_reset() {347 async fn users_get_independent_windows_that_reset() {
348 let limiter = UserRateLimiter::default();348 let limiter = UserRateLimiter::default();
349- for _ in 0..crate::config::DEFAULT_CHAT_RATE_LIMIT {349+ for _ in 0..crate::config::DEFAULT_CHATBOT_RATE_LIMIT {
350 assert!(limiter.enforce_user("user:a").is_ok());350 assert!(limiter.enforce_user("user:a").is_ok());
351 }351 }
352 assert!(matches!(352 assert!(matches!(
src/state.rsmodified+2 -2
@@ -22,10 +22,10 @@ pub struct AppState {
22 /// Read once by [`crate::build_router`] when the limiters are built.22 /// Read once by [`crate::build_router`] when the limiters are built.
23 pub rate_limit: RateLimitConfig,23 pub rate_limit: RateLimitConfig,
24 /// Per-user chatbot limit (see [`UserRateLimiter`], built from24 /// Per-user chatbot limit (see [`UserRateLimiter`], built from
25- /// [`crate::config::Config::chat_per_minute`]). Not middleware: the25+ /// [`crate::config::Config::chatbot_per_minute`]). Not middleware: the
26 /// caller is only known after `CurrentUser` has run, so handlers call it26 /// caller is only known after `CurrentUser` has run, so handlers call it
27 /// themselves.27 /// themselves.
28- pub chat_limit: UserRateLimiter,28+ pub chatbot_limit: UserRateLimiter,
29 /// Who is inside which exam room right now (see [`ExamPresence`]).29 /// Who is inside which exam room right now (see [`ExamPresence`]).
30 pub exam_presence: ExamPresence,30 pub exam_presence: ExamPresence,
31 /// Whether the database socket answered its last ping (see [`DbHealth`]).31 /// Whether the database socket answered its last ping (see [`DbHealth`]).
src/web/chat.rs → src/web/chatbot.rsrenamed+135 -135
@@ -2,7 +2,7 @@
2 //!2 //!
3 //! The backend owns everything except the answer itself — auth, the per-user3 //! The backend owns everything except the answer itself — auth, the per-user
4 //! rate limit, the thread, the payload format, and the last look at the reply4 //! 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 is5+//! before it is stored. There are no intent or rule tables: the thread is
6 //! free-form on purpose.6 //! free-form on purpose.
7 //!7 //!
8 //! Sending is asynchronous by design. `POST .../messages` writes the user's8 //! Sending is asynchronous by design. `POST .../messages` writes the user's
@@ -30,12 +30,12 @@ use utoipa_axum::routes;
30 30
31 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};31 use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
32 use crate::ai::{AiBridge, AiError};32 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};
34 use crate::database::Database;34 use crate::database::Database;
35-use crate::domain::chat_message::{35+use crate::domain::chatbot_message::{
36- ChatContent, ChatMessage, ChatMessageId, MessageRole, MessageStatus,36+ ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,
37 };37 };
38-use crate::domain::conversation::{Conversation, ConversationId, ConversationTitle};38+use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
39 use crate::domain::settings::Settings;39 use crate::domain::settings::Settings;
40 use crate::domain::user::UserId;40 use crate::domain::user::UserId;
41 use crate::error::{AppError, ErrorResponse, ValidationError};41 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -45,8 +45,8 @@ use super::{CurrentUser, Page, PageParams, paginate};
45 45
46 pub fn routes() -> OpenApiRouter<AppState> {46 pub fn routes() -> OpenApiRouter<AppState> {
47 OpenApiRouter::new()47 OpenApiRouter::new()
48- .routes(routes!(create_conversation, list_conversations))48+ .routes(routes!(create_thread, list_threads))
49- .routes(routes!(rename_conversation, delete_conversation))49+ .routes(routes!(rename_thread, delete_thread))
50 .routes(routes!(list_messages, send_message))50 .routes(routes!(list_messages, send_message))
51 .routes(routes!(read_message))51 .routes(routes!(read_message))
52 .routes(routes!(stream_message))52 .routes(routes!(stream_message))
@@ -57,10 +57,10 @@ pub fn routes() -> OpenApiRouter<AppState> {
57 const REPLY_CHUNKS: usize = 8;57 const REPLY_CHUNKS: usize = 8;
58 const MIN_CHUNK_CHARS: usize = 24;58 const MIN_CHUNK_CHARS: usize = 24;
59 59
60-// ---- conversations ----------------------------------------------------------60+// ---- threads ----------------------------------------------------------
61 61
62 #[derive(Deserialize, ToSchema)]62 #[derive(Deserialize, ToSchema)]
63-struct CreateConversation {63+struct CreateChatbotThread {
64 /// Optional thread name, up to 200 characters. Blank counts as absent —64 /// Optional thread name, up to 200 characters. Blank counts as absent —
65 /// an untitled thread is normal (the UI labels it from its first turn).65 /// an untitled thread is normal (the UI labels it from its first turn).
66 #[schema(example = "Fizik ödevi")]66 #[schema(example = "Fizik ödevi")]
@@ -70,7 +70,7 @@ struct CreateConversation {
70 /// One chatbot thread. `updated_at` moves on every turn, and the list is70 /// One chatbot thread. `updated_at` moves on every turn, and the list is
71 /// sorted by it, so the thread just written to is always first.71 /// sorted by it, so the thread just written to is always first.
72 #[derive(Serialize, ToSchema)]72 #[derive(Serialize, ToSchema)]
73-struct ConversationResponse {73+struct ChatbotThreadResponse {
74 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]74 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
75 id: String,75 id: String,
76 #[schema(example = "Fizik ödevi")]76 #[schema(example = "Fizik ödevi")]
@@ -81,55 +81,55 @@ struct ConversationResponse {
81 updated_at: i64,81 updated_at: i64,
82 }82 }
83 83
84-impl ConversationResponse {84+impl ChatbotThreadResponse {
85- fn new(conversation: &Conversation) -> Self {85+ fn new(thread: &ChatbotThread) -> Self {
86 Self {86 Self {
87- id: conversation.get_id().key().to_string(),87+ id: thread.get_id().key().to_string(),
88- title: conversation88+ title: thread
89 .get_title()89 .get_title()
90 .map(|title| title.as_str().to_string()),90 .map(|title| title.as_str().to_string()),
91- created_at: conversation.get_created_at().as_millis(),91+ created_at: thread.get_created_at().as_millis(),
92- updated_at: conversation.get_updated_at().as_millis(),92+ updated_at: thread.get_updated_at().as_millis(),
93 }93 }
94 }94 }
95 }95 }
96 96
97 /// Start a new chatbot thread, optionally named. Every authenticated role may97 /// Start a new chatbot thread, optionally named. Every authenticated role may
98 /// chat, parents included. A user may keep up to the school's98 /// 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)
100 /// until an old thread is deleted — the cap is storage protection, not a100 /// until an old thread is deleted — the cap is storage protection, not a
101 /// usage quota (that is the per-minute message limit).101 /// usage quota (that is the per-minute message limit).
102 #[utoipa::path(102 #[utoipa::path(
103 post,103 post,
104- path = "/conversations",104+ path = "/threads",
105- tag = "chat",105+ tag = "chatbot",
106 security(("session_cookie" = [])),106 security(("session_cookie" = [])),
107- request_body = CreateConversation,107+ request_body = CreateChatbotThread,
108 responses(108 responses(
109- (status = 201, description = "The new thread", body = ConversationResponse),109+ (status = 201, description = "The new thread", body = ChatbotThreadResponse),
110 (status = 400, description = "Invalid title", body = ErrorResponse),110 (status = 400, description = "Invalid title", body = ErrorResponse),
111 (status = 401, description = "Not authenticated", body = ErrorResponse),111 (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),
113 ),113 ),
114 )]114 )]
115-async fn create_conversation(115+async fn create_thread(
116 State(st): State<AppState>,116 State(st): State<AppState>,
117 CurrentUser(user): CurrentUser,117 CurrentUser(user): CurrentUser,
118- Json(req): Json<CreateConversation>,118+ Json(req): Json<CreateChatbotThread>,
119-) -> Result<(StatusCode, Json<ConversationResponse>), AppError> {119+) -> Result<(StatusCode, Json<ChatbotThreadResponse>), AppError> {
120 // Blank is "untitled", not an error — same rule as a message's label.120 // Blank is "untitled", not an error — same rule as a message's label.
121 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {121 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
122 "" => None,122 "" => None,
123- value => Some(ConversationTitle::try_new(value)?),123+ value => Some(ChatbotThreadTitle::try_new(value)?),
124 };124 };
125 125
126 // The cap is checked and the row written as one critical section in the126 // The cap is checked and the row written as one critical section in the
127 // domain: counting here and creating after would over-admit under127 // domain: counting here and creating after would over-admit under
128 // concurrency (the database does not serialize a count against inserts).128 // 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?;
130 Ok((130 Ok((
131 StatusCode::CREATED,131 StatusCode::CREATED,
132- Json(ConversationResponse::new(&conversation)),132+ Json(ChatbotThreadResponse::new(&thread)),
133 ))133 ))
134 }134 }
135 135
@@ -137,33 +137,33 @@ async fn create_conversation(
137 /// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's.137 /// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's.
138 #[utoipa::path(138 #[utoipa::path(
139 get,139 get,
140- path = "/conversations",140+ path = "/threads",
141- tag = "chat",141+ tag = "chatbot",
142 security(("session_cookie" = [])),142 security(("session_cookie" = [])),
143 params(PageParams),143 params(PageParams),
144 responses(144 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>),
146 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),146 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
147 (status = 401, description = "Not authenticated", body = ErrorResponse),147 (status = 401, description = "Not authenticated", body = ErrorResponse),
148 ),148 ),
149 )]149 )]
150-async fn list_conversations(150+async fn list_threads(
151 State(st): State<AppState>,151 State(st): State<AppState>,
152 CurrentUser(user): CurrentUser,152 CurrentUser(user): CurrentUser,
153 Query(page): Query<PageParams>,153 Query(page): Query<PageParams>,
154-) -> Result<Json<Page<ConversationResponse>>, AppError> {154+) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {
155 let (limit, offset) = page.resolve()?;155 let (limit, offset) = page.resolve()?;
156- let conversations = Conversation::list_for_user(user.get_id(), &st.db).await?;156+ let threads = ChatbotThread::list_for_user(user.get_id(), &st.db).await?;
157- let total = conversations.len() as i64;157+ let total = threads.len() as i64;
158- let items = paginate(&conversations, limit, offset)158+ let items = paginate(&threads, limit, offset)
159 .iter()159 .iter()
160- .map(ConversationResponse::new)160+ .map(ChatbotThreadResponse::new)
161 .collect();161 .collect();
162 Ok(Json(Page::new(items, total, limit, offset)))162 Ok(Json(Page::new(items, total, limit, offset)))
163 }163 }
164 164
165 #[derive(Deserialize, ToSchema)]165 #[derive(Deserialize, ToSchema)]
166-struct RenameConversation {166+struct RenameChatbotThread {
167 /// The new name, up to 200 characters. `null` — or blank — clears it back167 /// The new name, up to 200 characters. `null` — or blank — clears it back
168 /// to untitled, the same rule the create route applies.168 /// to untitled, the same rule the create route applies.
169 #[schema(example = "Fizik ödevi")]169 #[schema(example = "Fizik ödevi")]
@@ -179,65 +179,65 @@ struct RenameConversation {
179 /// title, and the AI service is never asked for one.179 /// title, and the AI service is never asked for one.
180 #[utoipa::path(180 #[utoipa::path(
181 patch,181 patch,
182- path = "/conversations/{id}",182+ path = "/threads/{id}",
183- tag = "chat",183+ tag = "chatbot",
184 security(("session_cookie" = [])),184 security(("session_cookie" = [])),
185- params(("id" = String, Path, description = "Conversation id")),185+ params(("id" = String, Path, description = "ChatbotThread id")),
186- request_body = RenameConversation,186+ request_body = RenameChatbotThread,
187 responses(187 responses(
188- (status = 200, description = "The renamed thread", body = ConversationResponse),188+ (status = 200, description = "The renamed thread", body = ChatbotThreadResponse),
189 (status = 400, description = "Invalid title", body = ErrorResponse),189 (status = 400, description = "Invalid title", body = ErrorResponse),
190 (status = 401, description = "Not authenticated", body = ErrorResponse),190 (status = 401, description = "Not authenticated", body = ErrorResponse),
191 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),191 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
192 ),192 ),
193 )]193 )]
194-async fn rename_conversation(194+async fn rename_thread(
195 State(st): State<AppState>,195 State(st): State<AppState>,
196 CurrentUser(user): CurrentUser,196 CurrentUser(user): CurrentUser,
197 Path(id): Path<String>,197 Path(id): Path<String>,
198- Json(req): Json<RenameConversation>,198+ Json(req): Json<RenameChatbotThread>,
199-) -> Result<Json<ConversationResponse>, AppError> {199+) -> Result<Json<ChatbotThreadResponse>, AppError> {
200 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {200 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
201 "" => None,201 "" => None,
202- value => Some(ConversationTitle::try_new(value)?),202+ value => Some(ChatbotThreadTitle::try_new(value)?),
203 };203 };
204- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;204+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
205- let renamed = conversation.rename(title, &st.db).await?;205+ let renamed = thread.rename(title, &st.db).await?;
206- Ok(Json(ConversationResponse::new(&renamed)))206+ Ok(Json(ChatbotThreadResponse::new(&renamed)))
207 }207 }
208 208
209 /// Delete a thread and every turn in it, permanently. Owner only; someone209 /// Delete a thread and every turn in it, permanently. Owner only; someone
210 /// else's thread is a `404`, never a `403` (its existence is not leaked).210 /// else's thread is a `404`, never a `403` (its existence is not leaked).
211 #[utoipa::path(211 #[utoipa::path(
212 delete,212 delete,
213- path = "/conversations/{id}",213+ path = "/threads/{id}",
214- tag = "chat",214+ tag = "chatbot",
215 security(("session_cookie" = [])),215 security(("session_cookie" = [])),
216- params(("id" = String, Path, description = "Conversation id")),216+ params(("id" = String, Path, description = "ChatbotThread id")),
217 responses(217 responses(
218 (status = 204, description = "Deleted, with its messages"),218 (status = 204, description = "Deleted, with its messages"),
219 (status = 401, description = "Not authenticated", body = ErrorResponse),219 (status = 401, description = "Not authenticated", body = ErrorResponse),
220 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),220 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
221 ),221 ),
222 )]222 )]
223-async fn delete_conversation(223+async fn delete_thread(
224 State(st): State<AppState>,224 State(st): State<AppState>,
225 CurrentUser(user): CurrentUser,225 CurrentUser(user): CurrentUser,
226 Path(id): Path<String>,226 Path(id): Path<String>,
227 ) -> Result<StatusCode, AppError> {227 ) -> Result<StatusCode, AppError> {
228- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;228+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
229- conversation.delete(&st.db).await?;229+ thread.delete(&st.db).await?;
230 Ok(StatusCode::NO_CONTENT)230 Ok(StatusCode::NO_CONTENT)
231 }231 }
232 232
233 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable233 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
234 /// from a missing one.234 /// from a missing one.
235-async fn own_conversation(235+async fn own_thread(
236 id: &str,236 id: &str,
237 user: &UserId,237 user: &UserId,
238 db: &Database,238 db: &Database,
239-) -> Result<Conversation, AppError> {239+) -> Result<ChatbotThread, AppError> {
240- Conversation::read_for(&ConversationId::from_key(id), user, db)240+ ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db)
241 .await?241 .await?
242 .ok_or(AppError::NotFound)242 .ok_or(AppError::NotFound)
243 }243 }
@@ -245,15 +245,15 @@ async fn own_conversation(
245 // ---- turns ------------------------------------------------------------------245 // ---- turns ------------------------------------------------------------------
246 246
247 #[derive(Deserialize, ToSchema)]247 #[derive(Deserialize, ToSchema)]
248-struct SendChatMessage {248+struct SendChatbotMessage {
249 /// What to ask. Required, and capped by the school's249 /// What to ask. Required, and capped by the school's
250- /// `max_chat_message_len` (`GET /settings`).250+ /// `max_chatbot_message_len` (`GET /settings`).
251 #[schema(example = "Newton'un ikinci yasasını açıklar mısın?")]251 #[schema(example = "Newton'un ikinci yasasını açıklar mısın?")]
252 content: String,252 content: String,
253 }253 }
254 254
255 /// The receipt for an accepted turn. The answer is *not* here: it is being255 /// 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 its256+/// fetched. Poll `GET /chatbot/threads/{id}/messages/{mid}` or open its
257 /// `/stream`.257 /// `/stream`.
258 #[derive(Serialize, ToSchema)]258 #[derive(Serialize, ToSchema)]
259 struct AcceptedResponse {259 struct AcceptedResponse {
@@ -268,11 +268,11 @@ struct AcceptedResponse {
268 /// One turn. `content` is empty while `status` is `pending`; `error_code` is268 /// One turn. `content` is empty while `status` is `pending`; `error_code` is
269 /// set only when `status` is `failed`.269 /// set only when `status` is `failed`.
270 #[derive(Serialize, ToSchema)]270 #[derive(Serialize, ToSchema)]
271-struct ChatMessageResponse {271+struct ChatbotMessageResponse {
272 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]272 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
273 id: String,273 id: String,
274 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]274 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
275- conversation_id: String,275+ thread_id: String,
276 /// `user` or `assistant`.276 /// `user` or `assistant`.
277 #[schema(example = "assistant")]277 #[schema(example = "assistant")]
278 role: String,278 role: String,
@@ -281,7 +281,7 @@ struct ChatMessageResponse {
281 status: String,281 status: String,
282 content: String,282 content: String,
283 /// `true` when `content` is only the first part of what the assistant283 /// `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 was284+ /// answered — the rest was over the school's `max_chatbot_message_len` and was
285 /// cut. Always `false` for a user turn and for a failed one. Show the user285 /// cut. Always `false` for a user turn and for a failed one. Show the user
286 /// that the answer is incomplete; asking again shortens nothing, so the way286 /// that the answer is incomplete; asking again shortens nothing, so the way
287 /// out is a narrower question (or a bigger cap).287 /// out is a narrower question (or a bigger cap).
@@ -299,11 +299,11 @@ struct ChatMessageResponse {
299 completed_at: Option<i64>,299 completed_at: Option<i64>,
300 }300 }
301 301
302-impl ChatMessageResponse {302+impl ChatbotMessageResponse {
303- fn new(message: &ChatMessage) -> Self {303+ fn new(message: &ChatbotMessage) -> Self {
304 Self {304 Self {
305 id: message.get_id().key().to_string(),305 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(),
307 role: message.get_role().as_str().to_string(),307 role: message.get_role().as_str().to_string(),
308 status: message.get_status().as_str().to_string(),308 status: message.get_status().as_str().to_string(),
309 content: message.get_content().as_str().to_string(),309 content: message.get_content().as_str().to_string(),
@@ -318,12 +318,12 @@ impl ChatMessageResponse {
318 /// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only.318 /// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only.
319 #[utoipa::path(319 #[utoipa::path(
320 get,320 get,
321- path = "/conversations/{id}/messages",321+ path = "/threads/{id}/messages",
322- tag = "chat",322+ tag = "chatbot",
323 security(("session_cookie" = [])),323 security(("session_cookie" = [])),
324- params(("id" = String, Path, description = "Conversation id"), PageParams),324+ params(("id" = String, Path, description = "ChatbotThread id"), PageParams),
325 responses(325 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>),
327 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),327 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
328 (status = 401, description = "Not authenticated", body = ErrorResponse),328 (status = 401, description = "Not authenticated", body = ErrorResponse),
329 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),329 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
@@ -334,14 +334,14 @@ async fn list_messages(
334 CurrentUser(user): CurrentUser,334 CurrentUser(user): CurrentUser,
335 Path(id): Path<String>,335 Path(id): Path<String>,
336 Query(page): Query<PageParams>,336 Query(page): Query<PageParams>,
337-) -> Result<Json<Page<ChatMessageResponse>>, AppError> {337+) -> Result<Json<Page<ChatbotMessageResponse>>, AppError> {
338 let (limit, offset) = page.resolve()?;338 let (limit, offset) = page.resolve()?;
339- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;339+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
340- let messages = ChatMessage::list_for_conversation(conversation.get_id(), &st.db).await?;340+ let messages = ChatbotMessage::list_for_thread(thread.get_id(), &st.db).await?;
341 let total = messages.len() as i64;341 let total = messages.len() as i64;
342 let items = paginate(&messages, limit, offset)342 let items = paginate(&messages, limit, offset)
343 .iter()343 .iter()
344- .map(ChatMessageResponse::new)344+ .map(ChatbotMessageResponse::new)
345 .collect();345 .collect();
346 Ok(Json(Page::new(items, total, limit, offset)))346 Ok(Json(Page::new(items, total, limit, offset)))
347 }347 }
@@ -358,14 +358,14 @@ async fn list_messages(
358 /// the boot sweep repairs whatever a process death left behind.358 /// the boot sweep repairs whatever a process death left behind.
359 #[utoipa::path(359 #[utoipa::path(
360 post,360 post,
361- path = "/conversations/{id}/messages",361+ path = "/threads/{id}/messages",
362- tag = "chat",362+ tag = "chatbot",
363 security(("session_cookie" = [])),363 security(("session_cookie" = [])),
364- params(("id" = String, Path, description = "Conversation id")),364+ params(("id" = String, Path, description = "ChatbotThread id")),
365- request_body = SendChatMessage,365+ request_body = SendChatbotMessage,
366 responses(366 responses(
367 (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse),367 (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),
369 (status = 401, description = "Not authenticated", body = ErrorResponse),369 (status = 401, description = "Not authenticated", body = ErrorResponse),
370 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),370 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
371 (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse),371 (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse),
@@ -376,12 +376,12 @@ async fn send_message(
376 State(st): State<AppState>,376 State(st): State<AppState>,
377 CurrentUser(user): CurrentUser,377 CurrentUser(user): CurrentUser,
378 Path(id): Path<String>,378 Path(id): Path<String>,
379- Json(req): Json<SendChatMessage>,379+ Json(req): Json<SendChatbotMessage>,
380 ) -> Result<Response, AppError> {380 ) -> Result<Response, AppError> {
381 // Charged first: a rejected turn must cost nothing and leave no row.381 // 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())?;
383 383
384- let conversation = own_conversation(&id, user.get_id(), &st.db).await?;384+ let thread = own_thread(&id, user.get_id(), &st.db).await?;
385 let settings = Settings::load(&st.db).await?;385 let settings = Settings::load(&st.db).await?;
386 let reply_cap = content_cap(&settings);386 let reply_cap = content_cap(&settings);
387 let length = req.content.chars().count();387 let length = req.content.chars().count();
@@ -406,23 +406,23 @@ async fn send_message(
406 return Ok(unavailable("no AI service is connected right now"));406 return Ok(unavailable("no AI service is connected right now"));
407 }407 }
408 408
409- let prompt = ChatMessage::append_user(409+ let prompt = ChatbotMessage::append_user(
410- conversation.get_id(),410+ thread.get_id(),
411 user.get_id(),411 user.get_id(),
412 content.clone(),412 content.clone(),
413 &st.db,413 &st.db,
414 )414 )
415 .await?;415 .await?;
416 let answer =416 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?;
418 // Never fatal: both rows are already written, and failing here would strand418 // Never fatal: both rows are already written, and failing here would strand
419 // the pending one with no task to answer it (it would only settle 300s419 // the pending one with no task to answer it (it would only settle 300s
420 // later, by projection). `updated_at` is the list's sort key — cosmetic420 // later, by projection). `updated_at` is the list's sort key — cosmetic
421 // next to a turn that has been accepted.421 // 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 {
423 tracing::warn!(423 tracing::warn!(
424- "could not stamp activity on conversation {}: {err}",424+ "could not stamp activity on thread {}: {err}",
425- conversation.get_id().key()425+ thread.get_id().key()
426 );426 );
427 }427 }
428 428
@@ -431,10 +431,10 @@ async fn send_message(
431 tokio::spawn(answer_turn(431 tokio::spawn(answer_turn(
432 bridge,432 bridge,
433 st.db.clone(),433 st.db.clone(),
434- conversation.get_id().clone(),434+ thread.get_id().clone(),
435 [prompt.get_id().clone(), answer.get_id().clone()],435 [prompt.get_id().clone(), answer.get_id().clone()],
436 content.as_str().to_string(),436 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,
438 reply_cap,438 reply_cap,
439 ));439 ));
440 440
@@ -451,7 +451,7 @@ async fn send_message(
451 /// The school's per-message character cap, never above the domain's hard451 /// The school's per-message character cap, never above the domain's hard
452 /// ceiling. Applied to what the user sends *and* to what the service answers.452 /// ceiling. Applied to what the user sends *and* to what the service answers.
453 fn content_cap(settings: &Settings) -> usize {453 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)
455 }455 }
456 456
457 /// The AI-unavailable `503`. Built here rather than as an `AppError` variant:457 /// The AI-unavailable `503`. Built here rather than as an `AppError` variant:
@@ -477,9 +477,9 @@ fn unavailable(message: &str) -> Response {
477 async fn answer_turn(477 async fn answer_turn(
478 bridge: AiBridge,478 bridge: AiBridge,
479 db: Database,479 db: Database,
480- conversation: ConversationId,480+ thread: ChatbotThreadId,
481 // The two rows this turn just wrote; both are excluded from the history.481 // The two rows this turn just wrote; both are excluded from the history.
482- fresh: [ChatMessageId; 2],482+ fresh: [ChatbotMessageId; 2],
483 prompt: String,483 prompt: String,
484 history_turns: usize,484 history_turns: usize,
485 reply_cap: usize,485 reply_cap: usize,
@@ -488,7 +488,7 @@ async fn answer_turn(
488 let settled = match fetch_reply(488 let settled = match fetch_reply(
489 &bridge,489 &bridge,
490 &db,490 &db,
491- &conversation,491+ &thread,
492 &fresh,492 &fresh,
493 prompt,493 prompt,
494 history_turns,494 history_turns,
@@ -496,16 +496,16 @@ async fn answer_turn(
496 )496 )
497 .await497 .await
498 {498 {
499- Ok((text, truncated)) => ChatMessage::complete(&answer_id, text, truncated, &db).await,499+ Ok((text, truncated)) => ChatbotMessage::complete(&answer_id, text, truncated, &db).await,
500 Err(code) => {500 Err(code) => {
501 tracing::warn!("chat answer {} failed: {code}", answer_id.key());501 tracing::warn!("chat answer {} failed: {code}", answer_id.key());
502- ChatMessage::fail(&answer_id, &code, &db).await502+ ChatbotMessage::fail(&answer_id, &code, &db).await
503 }503 }
504 };504 };
505 match settled {505 match settled {
506 Ok(_) => {}506 Ok(_) => {}
507 // The row was no longer `pending`: the boot sweep or a stale-timeout507 // 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.
509 // Benign — the user is not waiting on this row any more.509 // Benign — the user is not waiting on this row any more.
510 Err(AppError::NotFound) => {510 Err(AppError::NotFound) => {
511 tracing::info!("chat answer {} was already settled", answer_id.key());511 tracing::info!("chat answer {} was already settled", answer_id.key());
@@ -518,13 +518,13 @@ async fn answer_turn(
518 async fn fetch_reply(518 async fn fetch_reply(
519 bridge: &AiBridge,519 bridge: &AiBridge,
520 db: &Database,520 db: &Database,
521- conversation: &ConversationId,521+ thread: &ChatbotThreadId,
522- fresh: &[ChatMessageId; 2],522+ fresh: &[ChatbotMessageId; 2],
523 prompt: String,523 prompt: String,
524 history_turns: usize,524 history_turns: usize,
525 reply_cap: usize,525 reply_cap: usize,
526 ) -> Result<(ChatContent, bool), String> {526 ) -> 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 {
528 Ok(history) => history,528 Ok(history) => history,
529 Err(err) => {529 Err(err) => {
530 tracing::warn!("could not load chat history: {err}");530 tracing::warn!("could not load chat history: {err}");
@@ -571,21 +571,21 @@ async fn fetch_reply(
571 Ok((content, truncated))571 Ok((content, truncated))
572 }572 }
573 573
574-/// The tail of the conversation replayed to the service: oldest first, only574+/// The tail of the thread replayed to the service: oldest first, only
575 /// settled turns with text, and never the two rows this turn just wrote (the575 /// settled turns with text, and never the two rows this turn just wrote (the
576 /// new prompt rides in `message`, the answer does not exist yet).576 /// new prompt rides in `message`, the answer does not exist yet).
577 async fn history_for(577 async fn history_for(
578 db: &Database,578 db: &Database,
579- conversation: &ConversationId,579+ thread: &ChatbotThreadId,
580- fresh: &[ChatMessageId; 2],580+ fresh: &[ChatbotMessageId; 2],
581 turns: usize,581 turns: usize,
582 ) -> Result<Vec<ChatTurn>, AppError> {582 ) -> Result<Vec<ChatTurn>, AppError> {
583 // The query counts only settled rows with text, so a run of failed answers583 // The query counts only settled rows with text, so a run of failed answers
584 // makes the window reach *further back* instead of shrinking it — that is584 // makes the window reach *further back* instead of shrinking it — that is
585- // what "the last `chat_history_turns` settled turns" means. +2 so dropping585+ // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping
586 // this turn's own two rows cannot shorten it either (only the user one can586 // this turn's own two rows cannot shorten it either (only the user one can
587 // match: the assistant row is still `pending`).587 // 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?;
589 let mut history: Vec<ChatTurn> = tail589 let mut history: Vec<ChatTurn> = tail
590 .iter()590 .iter()
591 .filter(|message| !fresh.contains(message.get_id()))591 .filter(|message| !fresh.contains(message.get_id()))
@@ -629,15 +629,15 @@ fn failure_code(err: AiError) -> String {
629 /// so the two can never disagree about a turn's state.629 /// so the two can never disagree about a turn's state.
630 #[utoipa::path(630 #[utoipa::path(
631 get,631 get,
632- path = "/conversations/{id}/messages/{mid}",632+ path = "/threads/{id}/messages/{mid}",
633- tag = "chat",633+ tag = "chatbot",
634 security(("session_cookie" = [])),634 security(("session_cookie" = [])),
635 params(635 params(
636- ("id" = String, Path, description = "Conversation id"),636+ ("id" = String, Path, description = "ChatbotThread id"),
637 ("mid" = String, Path, description = "Message id"),637 ("mid" = String, Path, description = "Message id"),
638 ),638 ),
639 responses(639 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),
641 (status = 401, description = "Not authenticated", body = ErrorResponse),641 (status = 401, description = "Not authenticated", body = ErrorResponse),
642 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),642 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
643 ),643 ),
@@ -646,28 +646,28 @@ async fn read_message(
646 State(st): State<AppState>,646 State(st): State<AppState>,
647 CurrentUser(user): CurrentUser,647 CurrentUser(user): CurrentUser,
648 Path((id, mid)): Path<(String, String)>,648 Path((id, mid)): Path<(String, String)>,
649-) -> Result<Json<ChatMessageResponse>, AppError> {649+) -> Result<Json<ChatbotMessageResponse>, AppError> {
650 let message = own_message(&id, &mid, user.get_id(), &st.db).await?;650 let message = own_message(&id, &mid, user.get_id(), &st.db).await?;
651- Ok(Json(ChatMessageResponse::new(&message)))651+ Ok(Json(ChatbotMessageResponse::new(&message)))
652 }652 }
653 653
654 /// Read one turn only if the caller owns it *and* it belongs to the named654 /// 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.
656 async fn own_message(656 async fn own_message(
657- conversation: &str,657+ thread: &str,
658 message: &str,658 message: &str,
659 user: &UserId,659 user: &UserId,
660 db: &Database,660 db: &Database,
661-) -> Result<ChatMessage, AppError> {661+) -> Result<ChatbotMessage, AppError> {
662- ChatMessage::read_for(&ChatMessageId::from_key(message), user, db)662+ ChatbotMessage::read_for(&ChatbotMessageId::from_key(message), user, db)
663 .await?663 .await?
664- .filter(|message| message.get_conversation_id().key() == conversation)664+ .filter(|message| message.get_thread_id().key() == thread)
665 .ok_or(AppError::NotFound)665 .ok_or(AppError::NotFound)
666 }666 }
667 667
668 /// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a668 /// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a
669 /// single `done` carrying the finished message, or one `error`. The stream669 /// 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.
671 ///671 ///
672 /// Works whatever state the turn is in when the stream opens: an answer that672 /// Works whatever state the turn is in when the stream opens: an answer that
673 /// already landed replays as `delta`s and a `done` straight away, so a client673 /// already landed replays as `delta`s and a `done` straight away, so a client
@@ -675,11 +675,11 @@ async fn own_message(
675 /// (cookies ride along on same-site / credentialed requests).675 /// (cookies ride along on same-site / credentialed requests).
676 #[utoipa::path(676 #[utoipa::path(
677 get,677 get,
678- path = "/conversations/{id}/messages/{mid}/stream",678+ path = "/threads/{id}/messages/{mid}/stream",
679- tag = "chat",679+ tag = "chatbot",
680 security(("session_cookie" = [])),680 security(("session_cookie" = [])),
681 params(681 params(
682- ("id" = String, Path, description = "Conversation id"),682+ ("id" = String, Path, description = "ChatbotThread id"),
683 ("mid" = String, Path, description = "Message id"),683 ("mid" = String, Path, description = "Message id"),
684 ),684 ),
685 responses(685 responses(
@@ -699,7 +699,7 @@ async fn stream_message(
699 699
700 let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2);700 let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2);
701 let (message_id, user_id, db) = (701 let (message_id, user_id, db) = (
702- ChatMessageId::from_key(&mid),702+ ChatbotMessageId::from_key(&mid),
703 user.get_id().clone(),703 user.get_id().clone(),
704 st.db.clone(),704 st.db.clone(),
705 );705 );
@@ -719,7 +719,7 @@ async fn stream_message(
719 _ = ticker.tick() => {}719 _ = ticker.tick() => {}
720 _ = tx.closed() => return,720 _ = tx.closed() => return,
721 }721 }
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 {
723 Ok(Some(message)) => message,723 Ok(Some(message)) => message,
724 // Deleted mid-stream (the thread went away) — say so and stop.724 // Deleted mid-stream (the thread went away) — say so and stop.
725 Ok(None) => {725 Ok(None) => {
@@ -744,7 +744,7 @@ async fn stream_message(
744 return;744 return;
745 }745 }
746 }746 }
747- let done = json!({ "message": ChatMessageResponse::new(&message) });747+ let done = json!({ "message": ChatbotMessageResponse::new(&message) });
748 let _ = send(&tx, "done", done).await;748 let _ = send(&tx, "done", done).await;
749 return;749 return;
750 }750 }
@@ -845,43 +845,43 @@ mod tests {
845 // shrink it: filtering a fixed-size tail after the fact handed the845 // shrink it: filtering a fixed-size tail after the fact handed the
846 // service a handful of unanswered prompts and nothing older.846 // service a handful of unanswered prompts and nothing older.
847 let db = crate::database::init_mem().await.unwrap();847 let db = crate::database::init_mem().await.unwrap();
848- let conversation = ConversationId::from_key("c");848+ let thread = ChatbotThreadId::from_key("c");
849 let user = UserId::from_key("u");849 let user = UserId::from_key("u");
850 let say = |text: String| ChatContent::try_new(&text).unwrap();850 let say = |text: String| ChatContent::try_new(&text).unwrap();
851 851
852 for turn in 0..10 {852 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)
854 .await854 .await
855 .unwrap();855 .unwrap();
856- let answer = ChatMessage::append_pending_assistant(&conversation, &user, &db)856+ let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
857 .await857 .await
858 .unwrap();858 .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)
860 .await860 .await
861 .unwrap();861 .unwrap();
862 }862 }
863 // Five turns in a row whose answer never landed.863 // Five turns in a row whose answer never landed.
864 for turn in 0..5 {864 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)
866 .await866 .await
867 .unwrap();867 .unwrap();
868- let answer = ChatMessage::append_pending_assistant(&conversation, &user, &db)868+ let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
869 .await869 .await
870 .unwrap();870 .unwrap();
871- ChatMessage::fail(answer.get_id(), "timed_out", &db)871+ ChatbotMessage::fail(answer.get_id(), "timed_out", &db)
872 .await872 .await
873 .unwrap();873 .unwrap();
874 }874 }
875 // And this turn's own two rows, which never belong in the history.875 // 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)
877 .await877 .await
878 .unwrap();878 .unwrap();
879- let pending = ChatMessage::append_pending_assistant(&conversation, &user, &db)879+ let pending = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
880 .await880 .await
881 .unwrap();881 .unwrap();
882 let fresh = [prompt.get_id().clone(), pending.get_id().clone()];882 let fresh = [prompt.get_id().clone(), pending.get_id().clone()];
883 883
884- let history = history_for(&db, &conversation, &fresh, 6).await.unwrap();884+ let history = history_for(&db, &thread, &fresh, 6).await.unwrap();
885 let texts: Vec<&str> = history.iter().map(|turn| turn.content.as_str()).collect();885 let texts: Vec<&str> = history.iter().map(|turn| turn.content.as_str()).collect();
886 assert_eq!(886 assert_eq!(
887 texts,887 texts,
src/web/mod.rsmodified+1 -1
@@ -7,7 +7,7 @@ pub mod ai;
7 pub mod appointments;7 pub mod appointments;
8 pub mod attendance;8 pub mod attendance;
9 pub mod auth;9 pub mod auth;
10-pub mod chat;10+pub mod chatbot;
11 pub mod courses;11 pub mod courses;
12 pub mod events;12 pub mod events;
13 pub mod exam_ws;13 pub mod exam_ws;
src/web/settings.rsmodified+21 -21
@@ -65,15 +65,15 @@ struct SettingsResponse {
65 /// Per-file size limit for note uploads, in bytes.65 /// Per-file size limit for note uploads, in bytes.
66 #[schema(example = 5_242_880)]66 #[schema(example = 5_242_880)]
67 max_file_bytes: i64,67 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.
69 #[schema(example = 10)]69 #[schema(example = 10)]
70- chat_history_turns: i64,70+ chatbot_history_turns: i64,
71- /// How many chatbot conversations one user may keep.71+ /// How many chatbot threads one user may keep.
72 #[schema(example = 50)]72 #[schema(example = 50)]
73- max_chat_conversations: i64,73+ max_chatbot_threads: i64,
74 /// Character limit on one chat message.74 /// Character limit on one chat message.
75 #[schema(example = 4000)]75 #[schema(example = 4000)]
76- max_chat_message_len: i64,76+ max_chatbot_message_len: i64,
77 }77 }
78 78
79 impl SettingsResponse {79 impl SettingsResponse {
@@ -97,9 +97,9 @@ impl SettingsResponse {
97 })97 })
98 .collect(),98 .collect(),
99 max_file_bytes: settings.get_max_file_bytes(),99 max_file_bytes: settings.get_max_file_bytes(),
100- chat_history_turns: settings.get_chat_history_turns(),100+ chatbot_history_turns: settings.get_chatbot_history_turns(),
101- max_chat_conversations: settings.get_max_chat_conversations(),101+ max_chatbot_threads: settings.get_max_chatbot_threads(),
102- max_chat_message_len: settings.get_max_chat_message_len(),102+ max_chatbot_message_len: settings.get_max_chatbot_message_len(),
103 }103 }
104 }104 }
105 }105 }
@@ -119,18 +119,18 @@ struct UpdateSettings {
119 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.119 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.
120 #[schema(example = 5_242_880)]120 #[schema(example = 5_242_880)]
121 max_file_bytes: Option<i64>,121 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,
123 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.123 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.
124 #[schema(example = 10)]124 #[schema(example = 10)]
125- chat_history_turns: Option<i64>,125+ chatbot_history_turns: Option<i64>,
126- /// How many chatbot conversations one user may keep, `1`–`500`. At the cap126+ /// How many chatbot threads one user may keep, `1`–`500`. At the cap
127- /// the user deletes an old conversation before starting a new one.127+ /// the user deletes an old thread before starting a new one.
128 #[schema(example = 50)]128 #[schema(example = 50)]
129- max_chat_conversations: Option<i64>,129+ max_chatbot_threads: Option<i64>,
130 /// Character limit on one chat message, `100`–`8000`. The ceiling is a130 /// Character limit on one chat message, `100`–`8000`. The ceiling is a
131 /// server hard cap.131 /// server hard cap.
132 #[schema(example = 4000)]132 #[schema(example = 4000)]
133- max_chat_message_len: Option<i64>,133+ max_chatbot_message_len: Option<i64>,
134 }134 }
135 135
136 /// The school's current policy. Any authenticated user — clients need it to136 /// The school's current policy. Any authenticated user — clients need it to
@@ -239,13 +239,13 @@ async fn update_settings(
239 params.attendance_statuses = attendance_statuses;239 params.attendance_statuses = attendance_statuses;
240 params.grade_bands = grade_bands;240 params.grade_bands = grade_bands;
241 params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes);241 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);242+ params.chatbot_history_turns = req.chatbot_history_turns.unwrap_or(params.chatbot_history_turns);
243- params.max_chat_conversations = req243+ params.max_chatbot_threads = req
244- .max_chat_conversations244+ .max_chatbot_threads
245- .unwrap_or(params.max_chat_conversations);245+ .unwrap_or(params.max_chatbot_threads);
246- params.max_chat_message_len = req246+ params.max_chatbot_message_len = req
247- .max_chat_message_len247+ .max_chatbot_message_len
248- .unwrap_or(params.max_chat_message_len);248+ .unwrap_or(params.max_chatbot_message_len);
249 249
250 let settings = Settings::try_new(params)?;250 let settings = Settings::try_new(params)?;
251 if let Some(saved) = settings.save_if_unchanged(&current, &st.db).await? {251 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
805 files_path: std::env::temp_dir(),805 files_path: std::env::temp_dir(),
806 cookie_secure: false,806 cookie_secure: false,
807 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),807 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
808- chat_limit: Default::default(),808+ chatbot_limit: Default::default(),
809 exam_presence: Default::default(),809 exam_presence: Default::default(),
810 db_up: Default::default(),810 db_up: Default::default(),
811 ai,811 ai,
@@ -924,7 +924,7 @@ fn payloads_are_opaque(v: Value) -> Value {
924 924
925 use axum::Router;925 use axum::Router;
926 use axum::http::StatusCode;926 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};
928 use hezarfen_backend::database::Database;928 use hezarfen_backend::database::Database;
929 use surrealdb::types::RecordId;929 use surrealdb::types::RecordId;
930 930
@@ -938,7 +938,7 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) {
938 files_path: common::files_dir(),938 files_path: common::files_dir(),
939 cookie_secure: false,939 cookie_secure: false,
940 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),940 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
941- chat_limit: Default::default(),941+ chatbot_limit: Default::default(),
942 exam_presence: Default::default(),942 exam_presence: Default::default(),
943 db_up: Default::default(),943 db_up: Default::default(),
944 ai: Some(bridge.clone()),944 ai: Some(bridge.clone()),
@@ -952,7 +952,7 @@ async fn chat_user(app: &Router, name: &str) -> (String, String) {
952 let res = common::send(952 let res = common::send(
953 app,953 app,
954 "POST",954 "POST",
955- "/chat/conversations",955+ "/chatbot/threads",
956 Some(&cookie),956 Some(&cookie),
957 Some(json!({})),957 Some(json!({})),
958 )958 )
@@ -963,11 +963,11 @@ async fn chat_user(app: &Router, name: &str) -> (String, String) {
963 }963 }
964 964
965 /// Ask one question (asserts `202`) and return the reserved assistant row's id.965 /// 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 {
967 let res = common::send(967 let res = common::send(
968 app,968 app,
969 "POST",969 "POST",
970- &format!("/chat/conversations/{conversation}/messages"),970+ &format!("/chatbot/threads/{thread}/messages"),
971 Some(cookie),971 Some(cookie),
972 Some(json!({ "content": text })),972 Some(json!({ "content": text })),
973 )973 )
@@ -982,12 +982,12 @@ async fn ask(app: &Router, cookie: &str, conversation: &str, text: &str) -> Stri
982 982
983 /// Poll a turn until it leaves `pending`. Bounded polling rather than a sleep983 /// Poll a turn until it leaves `pending`. Bounded polling rather than a sleep
984 /// sized to the answering task: the round trip settles when it settles.984 /// 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 {
986 for _ in 0..500 {986 for _ in 0..500 {
987 let res = common::send(987 let res = common::send(
988 app,988 app,
989 "GET",989 "GET",
990- &format!("/chat/conversations/{conversation}/messages/{mid}"),990+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
991 Some(cookie),991 Some(cookie),
992 None,992 None,
993 )993 )
@@ -1012,10 +1012,10 @@ async fn a_chat_turn_settles_complete_with_the_services_text() {
1012 .await;1012 .await;
1013 await_workers(&bridge, 1).await;1013 await_workers(&bridge, 1).await;
1014 let (app, _db) = chat_app(&bridge).await;1014 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;
1016 1016
1017- let mid = ask(&app, &cookie, &conversation, "ikinci yasa nedir?").await;1017+ let mid = ask(&app, &cookie, &thread, "ikinci yasa nedir?").await;
1018- let turn = settled(&app, &cookie, &conversation, &mid).await;1018+ let turn = settled(&app, &cookie, &thread, &mid).await;
1019 assert_eq!(turn["status"], "complete", "{turn}");1019 assert_eq!(turn["status"], "complete", "{turn}");
1020 assert_eq!(turn["content"], "F = ma");1020 assert_eq!(turn["content"], "F = ma");
1021 assert_eq!(turn["role"], "assistant");1021 assert_eq!(turn["role"], "assistant");
@@ -1050,28 +1050,28 @@ async fn the_history_a_service_receives_is_oldest_first_without_the_new_turn() {
1050 .await;1050 .await;
1051 await_workers(&bridge, 1).await;1051 await_workers(&bridge, 1).await;
1052 let (app, db) = chat_app(&bridge).await;1052 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;
1054 let user = common::me_id(&app, &cookie).await;1054 let user = common::me_id(&app, &cookie).await;
1055 1055
1056- let first = ask(&app, &cookie, &conversation, "birinci soru").await;1056+ let first = ask(&app, &cookie, &thread, "birinci soru").await;
1057 assert_eq!(1057 assert_eq!(
1058- settled(&app, &cookie, &conversation, &first).await["status"],1058+ settled(&app, &cookie, &thread, &first).await["status"],
1059 "complete"1059 "complete"
1060 );1060 );
1061 1061
1062 db.query(1062 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',
1064 content = '', status = 'pending', created_at = 1002;",1064 content = '', status = 'pending', created_at = 1002;",
1065 )1065 )
1066- .bind(("conv", RecordId::new("conversation", conversation.as_str())))1066+ .bind(("conv", RecordId::new("chatbot_thread", thread.as_str())))
1067 .bind(("usr", RecordId::new("user", user.as_str())))1067 .bind(("usr", RecordId::new("user", user.as_str())))
1068 .await1068 .await
1069 .expect("seed history")1069 .expect("seed history")
1070 .check()1070 .check()
1071 .expect("seed history");1071 .expect("seed history");
1072 1072
1073- let mid = ask(&app, &cookie, &conversation, "ikinci soru").await;1073+ let mid = ask(&app, &cookie, &thread, "ikinci soru").await;
1074- let turn = settled(&app, &cookie, &conversation, &mid).await;1074+ let turn = settled(&app, &cookie, &thread, &mid).await;
1075 assert_eq!(turn["status"], "complete", "{turn}");1075 assert_eq!(turn["status"], "complete", "{turn}");
1076 1076
1077 let seen = service.seen();1077 let seen = service.seen();
@@ -1103,10 +1103,10 @@ async fn a_refused_chat_turn_carries_the_services_own_error_code() {
1103 .await;1103 .await;
1104 await_workers(&bridge, 1).await;1104 await_workers(&bridge, 1).await;
1105 let (app, _db) = chat_app(&bridge).await;1105 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;
1107 1107
1108- let mid = ask(&app, &cookie, &conversation, "bir soru").await;1108+ let mid = ask(&app, &cookie, &thread, "bir soru").await;
1109- let turn = settled(&app, &cookie, &conversation, &mid).await;1109+ let turn = settled(&app, &cookie, &thread, &mid).await;
1110 assert_eq!(turn["status"], "failed", "{turn}");1110 assert_eq!(turn["status"], "failed", "{turn}");
1111 assert_eq!(turn["error_code"], "quota_exhausted");1111 assert_eq!(turn["error_code"], "quota_exhausted");
1112 assert_eq!(turn["content"], "", "a failed turn shows no text");1112 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() {
1120 // truncated (a clipped answer still helps), and on a character boundary —1120 // truncated (a clipped answer still helps), and on a character boundary —
1121 // a byte-wise clip of a multi-byte script would render as garbage. The cut1121 // a byte-wise clip of a multi-byte script would render as garbage. The cut
1122 // is flagged, so the UI never passes a clipped answer off as the whole one.1122 // 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;
1124 let bridge = bridge().await;1124 let bridge = bridge().await;
1125 let _service = connect_service(1125 let _service = connect_service(
1126 &bridge,1126 &bridge,
@@ -1130,10 +1130,10 @@ async fn an_over_long_chat_answer_is_clipped_rather_than_failed() {
1130 .await;1130 .await;
1131 await_workers(&bridge, 1).await;1131 await_workers(&bridge, 1).await;
1132 let (app, _db) = chat_app(&bridge).await;1132 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;
1134 1134
1135- let mid = ask(&app, &cookie, &conversation, "uzun cevap ver").await;1135+ let mid = ask(&app, &cookie, &thread, "uzun cevap ver").await;
1136- let turn = settled(&app, &cookie, &conversation, &mid).await;1136+ let turn = settled(&app, &cookie, &thread, &mid).await;
1137 assert_eq!(turn["status"], "complete", "{turn}");1137 assert_eq!(turn["status"], "complete", "{turn}");
1138 let text = turn["content"].as_str().expect("content");1138 let text = turn["content"].as_str().expect("content");
1139 assert_eq!(text.chars().count(), cap);1139 assert_eq!(text.chars().count(), cap);
@@ -1154,10 +1154,10 @@ async fn a_blank_chat_answer_fails_as_empty_reply() {
1154 .await;1154 .await;
1155 await_workers(&bridge, 1).await;1155 await_workers(&bridge, 1).await;
1156 let (app, _db) = chat_app(&bridge).await;1156 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;
1158 1158
1159- let mid = ask(&app, &cookie, &conversation, "bir soru").await;1159+ let mid = ask(&app, &cookie, &thread, "bir soru").await;
1160- let turn = settled(&app, &cookie, &conversation, &mid).await;1160+ let turn = settled(&app, &cookie, &thread, &mid).await;
1161 assert_eq!(turn["status"], "failed", "{turn}");1161 assert_eq!(turn["status"], "failed", "{turn}");
1162 assert_eq!(turn["error_code"], "empty_reply");1162 assert_eq!(turn["error_code"], "empty_reply");
1163 }1163 }
tests/common/mod.rsmodified+1 -1
@@ -47,7 +47,7 @@ pub async fn app_and_db() -> (Router, Database) {
47 // Off, so suites hammering the API never trip a limit; the dedicated47 // Off, so suites hammering the API never trip a limit; the dedicated
48 // `rate_limit` test binary opts into tight configs on purpose.48 // `rate_limit` test binary opts into tight configs on purpose.
49 rate_limit: RateLimitConfig::unlimited(),49 rate_limit: RateLimitConfig::unlimited(),
50- chat_limit: Default::default(),50+ chatbot_limit: Default::default(),
51 exam_presence: Default::default(),51 exam_presence: Default::default(),
52 db_up: Default::default(),52 db_up: Default::default(),
53 ai: None,53 ai: None,
tests/e2e.rsmodified+14 -14
@@ -27,7 +27,7 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St
27 // Every request here comes from 127.0.0.1, so per-IP limits would27 // Every request here comes from 127.0.0.1, so per-IP limits would
28 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.28 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
29 rate_limit: RateLimitConfig::unlimited(),29 rate_limit: RateLimitConfig::unlimited(),
30- chat_limit: Default::default(),30+ chatbot_limit: Default::default(),
31 exam_presence: Default::default(),31 exam_presence: Default::default(),
32 db_up: Default::default(),32 db_up: Default::default(),
33 ai,33 ai,
@@ -1936,7 +1936,7 @@ async fn chat_service(text: &str) -> ChatService {
1936 /// Open a thread and ask one question. Returns (thread id, reserved answer id).1936 /// Open a thread and ask one question. Returns (thread id, reserved answer id).
1937 async fn ask(client: &Client, base: &str) -> (String, String) {1937 async fn ask(client: &Client, base: &str) -> (String, String) {
1938 let thread: Value = client1938 let thread: Value = client
1939- .post(format!("{base}/chat/conversations"))1939+ .post(format!("{base}/chatbot/threads"))
1940 .json(&json!({ "title": "Fizik" }))1940 .json(&json!({ "title": "Fizik" }))
1941 .send()1941 .send()
1942 .await1942 .await
@@ -1944,10 +1944,10 @@ async fn ask(client: &Client, base: &str) -> (String, String) {
1944 .json()1944 .json()
1945 .await1945 .await
1946 .unwrap();1946 .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();
1948 1948
1949 let res = client1949 let res = client
1950- .post(format!("{base}/chat/conversations/{conversation}/messages"))1950+ .post(format!("{base}/chatbot/threads/{thread}/messages"))
1951 .json(&json!({ "content": "ikinci yasa nedir?" }))1951 .json(&json!({ "content": "ikinci yasa nedir?" }))
1952 .send()1952 .send()
1953 .await1953 .await
@@ -1959,7 +1959,7 @@ async fn ask(client: &Client, base: &str) -> (String, String) {
1959 .as_str()1959 .as_str()
1960 .expect("message id")1960 .expect("message id")
1961 .to_string();1961 .to_string();
1962- (conversation, mid)1962+ (thread, mid)
1963 }1963 }
1964 1964
1965 /// Read the SSE stream until its terminal event (`done` or `error`), returning1965 /// 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)
2036 /// must reach the same conclusion about the very same turn.2036 /// must reach the same conclusion about the very same turn.
2037 #[tokio::test]2037 #[tokio::test]
2038 async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {2038 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;
2040 let service = chat_service(&"é".repeat(cap + 500)).await;2040 let service = chat_service(&"é".repeat(cap + 500)).await;
2041 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;2041 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
2042 let ali = client();2042 let ali = client();
2043 register(&ali, &base, "ali").await;2043 register(&ali, &base, "ali").await;
2044 login(&ali, &base, "ali").await;2044 login(&ali, &base, "ali").await;
2045 2045
2046- let (conversation, mid) = ask(&ali, &base).await;2046+ let (thread, mid) = ask(&ali, &base).await;
2047 2047
2048 let mut res = ali2048 let mut res = ali
2049 .get(format!(2049 .get(format!(
2050- "{base}/chat/conversations/{conversation}/messages/{mid}/stream"2050+ "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
2051 ))2051 ))
2052 .send()2052 .send()
2053 .await2053 .await
@@ -2071,7 +2071,7 @@ async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {
2071 // The same row, read the other way: identical verdict, field for field.2071 // The same row, read the other way: identical verdict, field for field.
2072 let polled: Value = ali2072 let polled: Value = ali
2073 .get(format!(2073 .get(format!(
2074- "{base}/chat/conversations/{conversation}/messages/{mid}"2074+ "{base}/chatbot/threads/{thread}/messages/{mid}"
2075 ))2075 ))
2076 .send()2076 .send()
2077 .await2077 .await
@@ -2091,13 +2091,13 @@ async fn chat_stream_delivers_deltas_then_done_over_http() {
2091 register(&ali, &base, "ali").await;2091 register(&ali, &base, "ali").await;
2092 login(&ali, &base, "ali").await;2092 login(&ali, &base, "ali").await;
2093 2093
2094- let (conversation, mid) = ask(&ali, &base).await;2094+ let (thread, mid) = ask(&ali, &base).await;
2095 2095
2096 // The client opens the stream while the turn is still in flight; it stays2096 // The client opens the stream while the turn is still in flight; it stays
2097 // open until the answer lands, then closes after `done`.2097 // open until the answer lands, then closes after `done`.
2098 let mut res = ali2098 let mut res = ali
2099 .get(format!(2099 .get(format!(
2100- "{base}/chat/conversations/{conversation}/messages/{mid}/stream"2100+ "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
2101 ))2101 ))
2102 .send()2102 .send()
2103 .await2103 .await
@@ -2137,7 +2137,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
2137 register(&ali, &base, "ali").await;2137 register(&ali, &base, "ali").await;
2138 login(&ali, &base, "ali").await;2138 login(&ali, &base, "ali").await;
2139 2139
2140- let (conversation, mid) = ask(&ali, &base).await;2140+ let (thread, mid) = ask(&ali, &base).await;
2141 2141
2142 // Wait — by polling, never by sleeping — until the turn has settled, so the2142 // Wait — by polling, never by sleeping — until the turn has settled, so the
2143 // stream below opens strictly after the answer landed.2143 // stream below opens strictly after the answer landed.
@@ -2145,7 +2145,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
2145 for _ in 0..500 {2145 for _ in 0..500 {
2146 let turn: Value = ali2146 let turn: Value = ali
2147 .get(format!(2147 .get(format!(
2148- "{base}/chat/conversations/{conversation}/messages/{mid}"2148+ "{base}/chatbot/threads/{thread}/messages/{mid}"
2149 ))2149 ))
2150 .send()2150 .send()
2151 .await2151 .await
@@ -2164,7 +2164,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() {
2164 2164
2165 let mut res = ali2165 let mut res = ali
2166 .get(format!(2166 .get(format!(
2167- "{base}/chat/conversations/{conversation}/messages/{mid}/stream"2167+ "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
2168 ))2168 ))
2169 .send()2169 .send()
2170 .await2170 .await
tests/integration.rsmodified+79 -79
@@ -9,8 +9,8 @@ use common::{
9 app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session,9 app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session,
10 create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,10 create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,
11 };11 };
12-use hezarfen_backend::domain::chat_message::ChatMessage;12+use hezarfen_backend::domain::chatbot_message::ChatbotMessage;
13-use hezarfen_backend::domain::conversation::ConversationId;13+use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;
14 use hezarfen_backend::domain::exam::ExamId;14 use hezarfen_backend::domain::exam::ExamId;
15 use hezarfen_backend::domain::exam_attempt::ExamAttempt;15 use hezarfen_backend::domain::exam_attempt::ExamAttempt;
16 use hezarfen_backend::domain::session::Session;16 use hezarfen_backend::domain::session::Session;
@@ -5224,7 +5224,7 @@ async fn session_cookie_secure_attribute_follows_config() {
5224 files_path: common::files_dir(),5224 files_path: common::files_dir(),
5225 cookie_secure: true,5225 cookie_secure: true,
5226 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),5226 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
5227- chat_limit: Default::default(),5227+ chatbot_limit: Default::default(),
5228 exam_presence: Default::default(),5228 exam_presence: Default::default(),
5229 db_up: Default::default(),5229 db_up: Default::default(),
5230 ai: None,5230 ai: None,
@@ -5263,7 +5263,7 @@ async fn db_down_refuses_before_touching_the_database() {
5263 files_path: common::files_dir(),5263 files_path: common::files_dir(),
5264 cookie_secure: false,5264 cookie_secure: false,
5265 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),5265 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
5266- chat_limit: Default::default(),5266+ chatbot_limit: Default::default(),
5267 exam_presence: Default::default(),5267 exam_presence: Default::default(),
5268 db_up: db_up.clone(),5268 db_up: db_up.clone(),
5269 ai: None,5269 ai: None,
@@ -14616,10 +14616,10 @@ async fn chat_app(ai: Option<AiBridge>) -> (axum::Router, Database) {
14616 }14616 }
14617 14617
14618 /// The same, with an explicit per-user chat tier — what14618 /// 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.
14620 async fn chat_app_limited(14620 async fn chat_app_limited(
14621 ai: Option<AiBridge>,14621 ai: Option<AiBridge>,
14622- chat_limit: hezarfen_backend::rate_limit::UserRateLimiter,14622+ chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter,
14623 ) -> (axum::Router, Database) {14623 ) -> (axum::Router, Database) {
14624 let db = database::init_mem().await.expect("in-memory db");14624 let db = database::init_mem().await.expect("in-memory db");
14625 let app = build_router(AppState {14625 let app = build_router(AppState {
@@ -14627,7 +14627,7 @@ async fn chat_app_limited(
14627 files_path: common::files_dir(),14627 files_path: common::files_dir(),
14628 cookie_secure: false,14628 cookie_secure: false,
14629 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),14629 rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
14630- chat_limit,14630+ chatbot_limit,
14631 exam_presence: Default::default(),14631 exam_presence: Default::default(),
14632 db_up: Default::default(),14632 db_up: Default::default(),
14633 ai,14633 ai,
@@ -14635,17 +14635,17 @@ async fn chat_app_limited(
14635 (app, db)14635 (app, db)
14636 }14636 }
14637 14637
14638-/// How many `conversation` and `chat_message` rows exist, anywhere.14638+/// How many `thread` and `chatbot_message` rows exist, anywhere.
14639 async fn chat_rows(db: &Database) -> (usize, usize) {14639 async fn chat_rows(db: &Database) -> (usize, usize) {
14640 let mut res = db14640 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;")
14642 .await14642 .await
14643 .expect("count query")14643 .expect("count query")
14644 .check()14644 .check()
14645 .expect("count check");14645 .expect("count check");
14646- let conversations: Vec<surrealdb::types::RecordId> = res.take(0).expect("conversation ids");14646+ let threads: Vec<surrealdb::types::RecordId> = res.take(0).expect("thread ids");
14647- let messages: Vec<surrealdb::types::RecordId> = res.take(1).expect("chat_message ids");14647+ let messages: Vec<surrealdb::types::RecordId> = res.take(1).expect("chatbot_message ids");
14648- (conversations.len(), messages.len())14648+ (threads.len(), messages.len())
14649 }14649 }
14650 14650
14651 /// Open a thread (asserts 201) and return its id.14651 /// Open a thread (asserts 201) and return its id.
@@ -14653,7 +14653,7 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String {
14653 let res = send(14653 let res = send(
14654 app,14654 app,
14655 "POST",14655 "POST",
14656- "/chat/conversations",14656+ "/chatbot/threads",
14657 Some(cookie),14657 Some(cookie),
14658 Some(json!({})),14658 Some(json!({})),
14659 )14659 )
@@ -14665,13 +14665,13 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String {
14665 async fn post_turn(14665 async fn post_turn(
14666 app: &axum::Router,14666 app: &axum::Router,
14667 cookie: &str,14667 cookie: &str,
14668- conversation: &str,14668+ thread: &str,
14669 content: &str,14669 content: &str,
14670 ) -> common::Res {14670 ) -> common::Res {
14671 send(14671 send(
14672 app,14672 app,
14673 "POST",14673 "POST",
14674- &format!("/chat/conversations/{conversation}/messages"),14674+ &format!("/chatbot/threads/{thread}/messages"),
14675 Some(cookie),14675 Some(cookie),
14676 Some(json!({ "content": content })),14676 Some(json!({ "content": content })),
14677 )14677 )
@@ -14683,13 +14683,13 @@ async fn post_turn(
14683 async fn open_stream(14683 async fn open_stream(
14684 app: &axum::Router,14684 app: &axum::Router,
14685 cookie: &str,14685 cookie: &str,
14686- conversation: &str,14686+ thread: &str,
14687 mid: &str,14687 mid: &str,
14688 ) -> StatusCode {14688 ) -> StatusCode {
14689 let request = Request::builder()14689 let request = Request::builder()
14690 .method("GET")14690 .method("GET")
14691 .uri(format!(14691 .uri(format!(
14692- "/chat/conversations/{conversation}/messages/{mid}/stream"14692+ "/chatbot/threads/{thread}/messages/{mid}/stream"
14693 ))14693 ))
14694 .header("cookie", cookie)14694 .header("cookie", cookie)
14695 .body(Body::empty())14695 .body(Body::empty())
@@ -14706,7 +14706,7 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
14706 let res = send(14706 let res = send(
14707 &app,14707 &app,
14708 "POST",14708 "POST",
14709- "/chat/conversations",14709+ "/chatbot/threads",
14710 Some(&cookie),14710 Some(&cookie),
14711 Some(json!({ "title": "Fizik" })),14711 Some(json!({ "title": "Fizik" })),
14712 )14712 )
@@ -14715,11 +14715,11 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
14715 assert_eq!(res.body["title"], "Fizik");14715 assert_eq!(res.body["title"], "Fizik");
14716 assert!(res.body["created_at"].is_i64(), "{}", res.body);14716 assert!(res.body["created_at"].is_i64(), "{}", res.body);
14717 assert!(res.body["updated_at"].is_i64(), "{}", res.body);14717 assert!(res.body["updated_at"].is_i64(), "{}", res.body);
14718- let conversation = id_of(&res.body);14718+ let thread = id_of(&res.body);
14719 14719
14720 // The receipt: the reserved row's id and nothing else. The answer is not14720 // The receipt: the reserved row's id and nothing else. The answer is not
14721 // here — it is being fetched.14721 // 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;
14723 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);14723 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
14724 assert_eq!(res.body["status"], "pending");14724 assert_eq!(res.body["status"], "pending");
14725 let mid = res.body["message_id"].as_str().expect("message_id");14725 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() {
14736 let res = send(14736 let res = send(
14737 &app,14737 &app,
14738 "GET",14738 "GET",
14739- &format!("/chat/conversations/{conversation}/messages/{mid}"),14739+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
14740 Some(&cookie),14740 Some(&cookie),
14741 None,14741 None,
14742 )14742 )
14743 .await;14743 .await;
14744 assert_eq!(res.status, StatusCode::OK, "{}", res.body);14744 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
14745- assert_eq!(res.body["conversation_id"], conversation);14745+ assert_eq!(res.body["thread_id"], thread);
14746 assert_eq!(res.body["role"], "assistant");14746 assert_eq!(res.body["role"], "assistant");
14747 assert_eq!(res.body["status"], "pending");14747 assert_eq!(res.body["status"], "pending");
14748 assert_eq!(res.body["content"], "");14748 assert_eq!(res.body["content"], "");
@@ -14756,7 +14756,7 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() {
14756 let res = send(14756 let res = send(
14757 &app,14757 &app,
14758 "GET",14758 "GET",
14759- &format!("/chat/conversations/{conversation}/messages"),14759+ &format!("/chatbot/threads/{thread}/messages"),
14760 Some(&cookie),14760 Some(&cookie),
14761 None,14761 None,
14762 )14762 )
@@ -14788,9 +14788,9 @@ async fn chat_send_without_a_service_is_503_and_writes_nothing() {
14788 for ai in [None, Some(idle)] {14788 for ai in [None, Some(idle)] {
14789 let (app, db) = chat_app(ai).await;14789 let (app, db) = chat_app(ai).await;
14790 let cookie = login(&app, "ali").await;14790 let cookie = login(&app, "ali").await;
14791- let conversation = new_thread(&app, &cookie).await;14791+ let thread = new_thread(&app, &cookie).await;
14792 14792
14793- let res = post_turn(&app, &cookie, &conversation, "bir soru").await;14793+ let res = post_turn(&app, &cookie, &thread, "bir soru").await;
14794 assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);14794 assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
14795 assert!(14795 assert!(
14796 res.body["error"]14796 res.body["error"]
@@ -14826,8 +14826,8 @@ async fn chat_lists_are_paged() {
14826 // list. Order is compared element for element: the id tie-break makes it14826 // list. Order is compared element for element: the id tie-break makes it
14827 // deterministic even for the two rows one POST writes in a millisecond.14827 // deterministic even for the two rows one POST writes in a millisecond.
14828 for (uri, expected) in [14828 for (uri, expected) in [
14829- ("/chat/conversations".to_string(), 3),14829+ ("/chatbot/threads".to_string(), 3),
14830- (format!("/chat/conversations/{}/messages", threads[0]), 6),14830+ (format!("/chatbot/threads/{}/messages", threads[0]), 6),
14831 ] {14831 ] {
14832 let res = send(14832 let res = send(
14833 &app,14833 &app,
@@ -14895,8 +14895,8 @@ async fn chat_threads_are_invisible_to_everyone_else() {
14895 let ai = chat_bridge().await;14895 let ai = chat_bridge().await;
14896 let (app, db) = chat_app(Some(ai.bridge.clone())).await;14896 let (app, db) = chat_app(Some(ai.bridge.clone())).await;
14897 let ali = login(&app, "ali").await;14897 let ali = login(&app, "ali").await;
14898- let conversation = new_thread(&app, &ali).await;14898+ let thread = new_thread(&app, &ali).await;
14899- let res = post_turn(&app, &ali, &conversation, "bir soru").await;14899+ let res = post_turn(&app, &ali, &thread, "bir soru").await;
14900 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);14900 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
14901 let mid = res.body["message_id"].as_str().unwrap().to_string();14901 let mid = res.body["message_id"].as_str().unwrap().to_string();
14902 14902
@@ -14909,21 +14909,21 @@ async fn chat_threads_are_invisible_to_everyone_else() {
14909 for (method, uri) in [14909 for (method, uri) in [
14910 (14910 (
14911 "GET",14911 "GET",
14912- format!("/chat/conversations/{conversation}/messages"),14912+ format!("/chatbot/threads/{thread}/messages"),
14913 ),14913 ),
14914 (14914 (
14915 "GET",14915 "GET",
14916- format!("/chat/conversations/{conversation}/messages/{mid}"),14916+ format!("/chatbot/threads/{thread}/messages/{mid}"),
14917 ),14917 ),
14918 (14918 (
14919 "GET",14919 "GET",
14920- format!("/chat/conversations/{conversation}/messages/{mid}/stream"),14920+ format!("/chatbot/threads/{thread}/messages/{mid}/stream"),
14921 ),14921 ),
14922- ("DELETE", format!("/chat/conversations/{conversation}")),14922+ ("DELETE", format!("/chatbot/threads/{thread}")),
14923- ("PATCH", format!("/chat/conversations/{conversation}")),14923+ ("PATCH", format!("/chatbot/threads/{thread}")),
14924 (14924 (
14925 "POST",14925 "POST",
14926- format!("/chat/conversations/{conversation}/messages"),14926+ format!("/chatbot/threads/{thread}/messages"),
14927 ),14927 ),
14928 ] {14928 ] {
14929 let body = match method {14929 let body = match method {
@@ -14935,13 +14935,13 @@ async fn chat_threads_are_invisible_to_everyone_else() {
14935 assert_eq!(res.status, StatusCode::NOT_FOUND, "{name} {method} {uri}");14935 assert_eq!(res.status, StatusCode::NOT_FOUND, "{name} {method} {uri}");
14936 }14936 }
14937 // Nor does someone else's thread show up in their own list.14937 // 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;
14939 assert!(common::items(&res.body).is_empty(), "{}", res.body);14939 assert!(common::items(&res.body).is_empty(), "{}", res.body);
14940 }14940 }
14941 14941
14942 // And the owner still has everything, untouched.14942 // And the owner still has everything, untouched.
14943 assert_eq!(chat_rows(&db).await, (1, 2));14943 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;
14945 assert_eq!(common::items(&res.body).len(), 1, "{}", res.body);14945 assert_eq!(common::items(&res.body).len(), 1, "{}", res.body);
14946 }14946 }
14947 14947
@@ -14954,7 +14954,7 @@ async fn chat_thread_count_is_capped_by_the_school() {
14954 "PATCH",14954 "PATCH",
14955 "/settings",14955 "/settings",
14956 Some(&manager),14956 Some(&manager),
14957- Some(json!({ "max_chat_conversations": 1 })),14957+ Some(json!({ "max_chatbot_threads": 1 })),
14958 )14958 )
14959 .await;14959 .await;
14960 assert_eq!(res.status, StatusCode::OK, "{}", res.body);14960 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -14964,7 +14964,7 @@ async fn chat_thread_count_is_capped_by_the_school() {
14964 let res = send(14964 let res = send(
14965 &app,14965 &app,
14966 "POST",14966 "POST",
14967- "/chat/conversations",14967+ "/chatbot/threads",
14968 Some(&ali),14968 Some(&ali),
14969 Some(json!({})),14969 Some(json!({})),
14970 )14970 )
@@ -14979,7 +14979,7 @@ async fn chat_thread_count_is_capped_by_the_school() {
14979 let res = send(14979 let res = send(
14980 &app,14980 &app,
14981 "DELETE",14981 "DELETE",
14982- &format!("/chat/conversations/{first}"),14982+ &format!("/chatbot/threads/{first}"),
14983 Some(&ali),14983 Some(&ali),
14984 None,14984 None,
14985 )14985 )
@@ -15004,7 +15004,7 @@ async fn concurrent_thread_creation_never_passes_the_cap() {
15004 "PATCH",15004 "PATCH",
15005 "/settings",15005 "/settings",
15006 Some(&manager),15006 Some(&manager),
15007- Some(json!({ "max_chat_conversations": CAP })),15007+ Some(json!({ "max_chatbot_threads": CAP })),
15008 )15008 )
15009 .await;15009 .await;
15010 assert_eq!(res.status, StatusCode::OK, "{}", res.body);15010 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -15021,7 +15021,7 @@ async fn concurrent_thread_creation_never_passes_the_cap() {
15021 send(15021 send(
15022 &app,15022 &app,
15023 "POST",15023 "POST",
15024- "/chat/conversations",15024+ "/chatbot/threads",
15025 Some(&cookie),15025 Some(&cookie),
15026 Some(json!({})),15026 Some(json!({})),
15027 )15027 )
@@ -15054,18 +15054,18 @@ async fn chat_turn_stamps_thread_activity() {
15054 let ai = chat_bridge().await;15054 let ai = chat_bridge().await;
15055 let (app, _db) = chat_app(Some(ai.bridge.clone())).await;15055 let (app, _db) = chat_app(Some(ai.bridge.clone())).await;
15056 let ali = login(&app, "ali").await;15056 let ali = login(&app, "ali").await;
15057- let conversation = new_thread(&app, &ali).await;15057+ let thread = new_thread(&app, &ali).await;
15058- let before = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;15058+ let before = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
15059 let opened = common::items(&before.body)[0]["updated_at"]15059 let opened = common::items(&before.body)[0]["updated_at"]
15060 .as_i64()15060 .as_i64()
15061 .unwrap();15061 .unwrap();
15062 15062
15063 // The stamp is in whole milliseconds; make sure the clock has moved.15063 // The stamp is in whole milliseconds; make sure the clock has moved.
15064 tokio::time::sleep(std::time::Duration::from_millis(5)).await;15064 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;
15066 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);15066 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
15067 15067
15068- let after = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;15068+ let after = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
15069 let stamped = common::items(&after.body)[0]["updated_at"]15069 let stamped = common::items(&after.body)[0]["updated_at"]
15070 .as_i64()15070 .as_i64()
15071 .unwrap();15071 .unwrap();
@@ -15083,11 +15083,11 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() {
15083 // count below is not drowned in the QUIC service's task churn.15083 // count below is not drowned in the QUIC service's task churn.
15084 let (app, db) = chat_app(None).await;15084 let (app, db) = chat_app(None).await;
15085 let ali = login(&app, "ali").await;15085 let ali = login(&app, "ali").await;
15086- let conversation = new_thread(&app, &ali).await;15086+ let thread = new_thread(&app, &ali).await;
15087 let me = send(&app, "GET", "/auth/me", Some(&ali), None).await;15087 let me = send(&app, "GET", "/auth/me", Some(&ali), None).await;
15088 let user = UserId::from_key(me.body["id"].as_str().unwrap());15088 let user = UserId::from_key(me.body["id"].as_str().unwrap());
15089 let pending =15089 let pending =
15090- ChatMessage::append_pending_assistant(&ConversationId::from_key(&conversation), &user, &db)15090+ ChatbotMessage::append_pending_assistant(&ChatbotThreadId::from_key(&thread), &user, &db)
15091 .await15091 .await
15092 .expect("reserve an assistant row");15092 .expect("reserve an assistant row");
15093 let mid = pending.get_id().key().to_string();15093 let mid = pending.get_id().key().to_string();
@@ -15108,7 +15108,7 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() {
15108 let request = Request::builder()15108 let request = Request::builder()
15109 .method("GET")15109 .method("GET")
15110 .uri(format!(15110 .uri(format!(
15111- "/chat/conversations/{conversation}/messages/{mid}/stream"15111+ "/chatbot/threads/{thread}/messages/{mid}/stream"
15112 ))15112 ))
15113 .header("cookie", &ali)15113 .header("cookie", &ali)
15114 .body(Body::empty())15114 .body(Body::empty())
@@ -15140,25 +15140,25 @@ async fn chat_content_is_required_and_capped_by_the_school() {
15140 "PATCH",15140 "PATCH",
15141 "/settings",15141 "/settings",
15142 Some(&manager),15142 Some(&manager),
15143- Some(json!({ "max_chat_message_len": 100 })),15143+ Some(json!({ "max_chatbot_message_len": 100 })),
15144 )15144 )
15145 .await;15145 .await;
15146 assert_eq!(res.status, StatusCode::OK, "{}", res.body);15146 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
15147 15147
15148 let ali = login(&app, "ali").await;15148 let ali = login(&app, "ali").await;
15149- let conversation = new_thread(&app, &ali).await;15149+ let thread = new_thread(&app, &ali).await;
15150 15150
15151 for empty in ["", " ", "\n\t"] {15151 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;
15153 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{empty:?} accepted");15153 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{empty:?} accepted");
15154 }15154 }
15155 // Counted in characters, not bytes: 101 multi-byte characters is 101.15155 // 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;
15157 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);15157 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
15158 // Nothing rejected was written.15158 // Nothing rejected was written.
15159 assert_eq!(chat_rows(&db).await, (1, 0));15159 assert_eq!(chat_rows(&db).await, (1, 0));
15160 15160
15161- let res = post_turn(&app, &ali, &conversation, &"é".repeat(100)).await;15161+ let res = post_turn(&app, &ali, &thread, &"é".repeat(100)).await;
15162 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);15162 assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
15163 }15163 }
15164 15164
@@ -15170,10 +15170,10 @@ async fn chat_rate_limit_refuses_before_anything_is_written() {
15170 let ai = chat_bridge().await;15170 let ai = chat_bridge().await;
15171 let (app, db) = chat_app(Some(ai.bridge.clone())).await;15171 let (app, db) = chat_app(Some(ai.bridge.clone())).await;
15172 let ali = login(&app, "ali").await;15172 let ali = login(&app, "ali").await;
15173- let conversation = new_thread(&app, &ali).await;15173+ let thread = new_thread(&app, &ali).await;
15174 15174
15175 for n in 1..=20 {15175 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;
15177 assert_eq!(res.status, StatusCode::ACCEPTED, "turn {n}: {}", res.body);15177 assert_eq!(res.status, StatusCode::ACCEPTED, "turn {n}: {}", res.body);
15178 }15178 }
15179 let before = chat_rows(&db).await;15179 let before = chat_rows(&db).await;
@@ -15182,7 +15182,7 @@ async fn chat_rate_limit_refuses_before_anything_is_written() {
15182 let (status, headers, _) = common::send_raw(15182 let (status, headers, _) = common::send_raw(
15183 &app,15183 &app,
15184 "POST",15184 "POST",
15185- &format!("/chat/conversations/{conversation}/messages"),15185+ &format!("/chatbot/threads/{thread}/messages"),
15186 Some(&ali),15186 Some(&ali),
15187 Some("application/json"),15187 Some("application/json"),
15188 json!({ "content": "yirmi birinci" })15188 json!({ "content": "yirmi birinci" })
@@ -15222,16 +15222,16 @@ async fn every_role_may_chat_parents_included() {
15222 ("patron", "admin"),15222 ("patron", "admin"),
15223 ] {15223 ] {
15224 let cookie = login_as(&app, &db, name, role).await;15224 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;
15226 15226
15227- let res = post_turn(&app, &cookie, &conversation, "bir soru").await;15227+ let res = post_turn(&app, &cookie, &thread, "bir soru").await;
15228 assert_eq!(res.status, StatusCode::ACCEPTED, "{role}: {}", res.body);15228 assert_eq!(res.status, StatusCode::ACCEPTED, "{role}: {}", res.body);
15229 let mid = res.body["message_id"].as_str().unwrap().to_string();15229 let mid = res.body["message_id"].as_str().unwrap().to_string();
15230 15230
15231 let res = send(15231 let res = send(
15232 &app,15232 &app,
15233 "GET",15233 "GET",
15234- &format!("/chat/conversations/{conversation}/messages/{mid}"),15234+ &format!("/chatbot/threads/{thread}/messages/{mid}"),
15235 Some(&cookie),15235 Some(&cookie),
15236 None,15236 None,
15237 )15237 )
@@ -15241,7 +15241,7 @@ async fn every_role_may_chat_parents_included() {
15241 let res = send(15241 let res = send(
15242 &app,15242 &app,
15243 "GET",15243 "GET",
15244- &format!("/chat/conversations/{conversation}/messages"),15244+ &format!("/chatbot/threads/{thread}/messages"),
15245 Some(&cookie),15245 Some(&cookie),
15246 None,15246 None,
15247 )15247 )
@@ -15250,19 +15250,19 @@ async fn every_role_may_chat_parents_included() {
15250 assert_eq!(common::items(&res.body).len(), 2, "{role}: {}", res.body);15250 assert_eq!(common::items(&res.body).len(), 2, "{role}: {}", res.body);
15251 15251
15252 assert_eq!(15252 assert_eq!(
15253- open_stream(&app, &cookie, &conversation, &mid).await,15253+ open_stream(&app, &cookie, &thread, &mid).await,
15254 StatusCode::OK,15254 StatusCode::OK,
15255 "{role} may open the stream"15255 "{role} may open the stream"
15256 );15256 );
15257 15257
15258- let res = send(&app, "GET", "/chat/conversations", Some(&cookie), None).await;15258+ let res = send(&app, "GET", "/chatbot/threads", Some(&cookie), None).await;
15259 assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body);15259 assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body);
15260 assert_eq!(common::items(&res.body).len(), 1, "{role}: {}", res.body);15260 assert_eq!(common::items(&res.body).len(), 1, "{role}: {}", res.body);
15261 15261
15262 let res = send(15262 let res = send(
15263 &app,15263 &app,
15264 "DELETE",15264 "DELETE",
15265- &format!("/chat/conversations/{conversation}"),15265+ &format!("/chatbot/threads/{thread}"),
15266 Some(&cookie),15266 Some(&cookie),
15267 None,15267 None,
15268 )15268 )
@@ -15284,7 +15284,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15284 tokio::time::sleep(std::time::Duration::from_millis(5)).await;15284 tokio::time::sleep(std::time::Duration::from_millis(5)).await;
15285 let second = new_thread(&app, &ali).await;15285 let second = new_thread(&app, &ali).await;
15286 15286
15287- let listed = send(&app, "GET", "/chat/conversations", Some(&ali), None).await;15287+ let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await;
15288 let items = common::items(&listed.body);15288 let items = common::items(&listed.body);
15289 assert_eq!(id_of(&items[0]), second, "newest activity first");15289 assert_eq!(id_of(&items[0]), second, "newest activity first");
15290 let before = items[1]["updated_at"].as_i64().expect("updated_at");15290 let before = items[1]["updated_at"].as_i64().expect("updated_at");
@@ -15295,7 +15295,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15295 let res = send(15295 let res = send(
15296 &app,15296 &app,
15297 "PATCH",15297 "PATCH",
15298- &format!("/chat/conversations/{first}"),15298+ &format!("/chatbot/threads/{first}"),
15299 Some(&ali),15299 Some(&ali),
15300 Some(json!({ "title": " Fizik ödevi " })),15300 Some(json!({ "title": " Fizik ödevi " })),
15301 )15301 )
@@ -15307,7 +15307,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15307 assert!(stamped > before, "{stamped} !> {before}");15307 assert!(stamped > before, "{stamped} !> {before}");
15308 15308
15309 // The rename is durable and re-sorted the list.15309 // 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;
15311 let items = common::items(&listed.body);15311 let items = common::items(&listed.body);
15312 assert_eq!(id_of(&items[0]), first, "the renamed thread is now first");15312 assert_eq!(id_of(&items[0]), first, "the renamed thread is now first");
15313 assert_eq!(items[0]["title"], "Fizik ödevi");15313 assert_eq!(items[0]["title"], "Fizik ödevi");
@@ -15317,7 +15317,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15317 let res = send(15317 let res = send(
15318 &app,15318 &app,
15319 "PATCH",15319 "PATCH",
15320- &format!("/chat/conversations/{first}"),15320+ &format!("/chatbot/threads/{first}"),
15321 Some(&ali),15321 Some(&ali),
15322 Some(clearing.clone()),15322 Some(clearing.clone()),
15323 )15323 )
@@ -15329,7 +15329,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15329 send(15329 send(
15330 &app,15330 &app,
15331 "PATCH",15331 "PATCH",
15332- &format!("/chat/conversations/{first}"),15332+ &format!("/chatbot/threads/{first}"),
15333 Some(&ali),15333 Some(&ali),
15334 Some(json!({ "title": "geri" })),15334 Some(json!({ "title": "geri" })),
15335 )15335 )
@@ -15340,7 +15340,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15340 let res = send(15340 let res = send(
15341 &app,15341 &app,
15342 "PATCH",15342 "PATCH",
15343- &format!("/chat/conversations/{first}"),15343+ &format!("/chatbot/threads/{first}"),
15344 Some(&ali),15344 Some(&ali),
15345 Some(json!({ "title": "é".repeat(201) })),15345 Some(json!({ "title": "é".repeat(201) })),
15346 )15346 )
@@ -15349,7 +15349,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15349 let res = send(15349 let res = send(
15350 &app,15350 &app,
15351 "PATCH",15351 "PATCH",
15352- &format!("/chat/conversations/{first}"),15352+ &format!("/chatbot/threads/{first}"),
15353 Some(&ali),15353 Some(&ali),
15354 Some(json!({ "title": "é".repeat(200) })),15354 Some(json!({ "title": "é".repeat(200) })),
15355 )15355 )
@@ -15360,7 +15360,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15360 let res = send(15360 let res = send(
15361 &app,15361 &app,
15362 "PATCH",15362 "PATCH",
15363- "/chat/conversations/nosuchthread",15363+ "/chatbot/threads/nosuchthread",
15364 Some(&ali),15364 Some(&ali),
15365 Some(json!({ "title": "hayalet" })),15365 Some(json!({ "title": "hayalet" })),
15366 )15366 )
@@ -15370,7 +15370,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15370 let res = send(15370 let res = send(
15371 &app,15371 &app,
15372 "GET",15372 "GET",
15373- &format!("/chat/conversations/{second}/messages"),15373+ &format!("/chatbot/threads/{second}/messages"),
15374 Some(&ali),15374 Some(&ali),
15375 None,15375 None,
15376 )15376 )
@@ -15380,7 +15380,7 @@ async fn chat_thread_can_be_renamed_and_cleared() {
15380 15380
15381 #[tokio::test]15381 #[tokio::test]
15382 async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {15382 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 IP15383+ // `RATE_LIMIT_CHATBOT_PER_MINUTE`, the third tier, behaves like the two IP
15384 // ones: the configured number is honoured exactly and `0` switches it off.15384 // ones: the configured number is honoured exactly and `0` switches it off.
15385 // No bridge is needed — the limiter is charged before the availability15385 // No bridge is needed — the limiter is charged before the availability
15386 // gate, so a metered turn answers 503 and only the refused one answers 429.15386 // 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() {
15388 15388
15389 let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(3)).await;15389 let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(3)).await;
15390 let ali = login(&app, "ali").await;15390 let ali = login(&app, "ali").await;
15391- let conversation = new_thread(&app, &ali).await;15391+ let thread = new_thread(&app, &ali).await;
15392 for n in 1..=3 {15392 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;
15394 assert_eq!(15394 assert_eq!(
15395 res.status,15395 res.status,
15396 StatusCode::SERVICE_UNAVAILABLE,15396 StatusCode::SERVICE_UNAVAILABLE,
@@ -15398,7 +15398,7 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {
15398 res.body15398 res.body
15399 );15399 );
15400 }15400 }
15401- let res = post_turn(&app, &ali, &conversation, "dorduncu").await;15401+ let res = post_turn(&app, &ali, &thread, "dorduncu").await;
15402 assert_eq!(res.status, StatusCode::TOO_MANY_REQUESTS, "{}", res.body);15402 assert_eq!(res.status, StatusCode::TOO_MANY_REQUESTS, "{}", res.body);
15403 // Per user, still: a second caller starts with a full budget.15403 // Per user, still: a second caller starts with a full budget.
15404 let veli = login(&app, "veli").await;15404 let veli = login(&app, "veli").await;
@@ -15413,9 +15413,9 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() {
15413 // `0` disables the tier: well past the shipped default, nothing is refused.15413 // `0` disables the tier: well past the shipped default, nothing is refused.
15414 let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(0)).await;15414 let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(0)).await;
15415 let ali = login(&app, "ali").await;15415 let ali = login(&app, "ali").await;
15416- let conversation = new_thread(&app, &ali).await;15416+ let thread = new_thread(&app, &ali).await;
15417 for n in 1..=40 {15417 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;
15419 assert_eq!(15419 assert_eq!(
15420 res.status,15420 res.status,
15421 StatusCode::SERVICE_UNAVAILABLE,15421 StatusCode::SERVICE_UNAVAILABLE,
tests/persistence.rsmodified+33 -33
@@ -24,7 +24,7 @@ async fn reboot(db: &Database) -> Router {
24 files_path: common::files_dir(),24 files_path: common::files_dir(),
25 cookie_secure: false,25 cookie_secure: false,
26 rate_limit: RateLimitConfig::unlimited(),26 rate_limit: RateLimitConfig::unlimited(),
27- chat_limit: Default::default(),27+ chatbot_limit: Default::default(),
28 exam_presence: Default::default(),28 exam_presence: Default::default(),
29 db_up: Default::default(),29 db_up: Default::default(),
30 ai: None,30 ai: None,
@@ -729,13 +729,13 @@ async fn appointments_survive_remigration() {
729 }729 }
730 730
731 /// A chatbot thread and every turn in it die together: deleting the731 /// A chatbot thread and every turn in it die together: deleting the
732-/// conversation cascades its `chat_message` rows in one transaction, so no732+/// thread cascades its `chatbot_message` rows in one transaction, so no
733 /// orphan survives a reboot. And the thread is owner-scoped end to end — a733 /// 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.
735 #[tokio::test]735 #[tokio::test]
736 async fn chat_thread_delete_cascades_and_stays_owner_scoped() {736 async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
737- use hezarfen_backend::domain::chat_message::{ChatContent, ChatMessage, MessageStatus};737+ use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage, MessageStatus};
738- use hezarfen_backend::domain::conversation::Conversation;738+ use hezarfen_backend::domain::chatbot_thread::ChatbotThread;
739 use hezarfen_backend::domain::user::UserId;739 use hezarfen_backend::domain::user::UserId;
740 740
741 let (app, db) = common::app_and_db().await;741 let (app, db) = common::app_and_db().await;
@@ -744,11 +744,11 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
744 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);744 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);
745 let other = UserId::from_key(&me_id(&app, &other_cookie).await);745 let other = UserId::from_key(&me_id(&app, &other_cookie).await);
746 746
747- let conversation = Conversation::create(&owner, None, &db)747+ let thread = ChatbotThread::create(&owner, None, &db)
748 .await748 .await
749 .expect("create");749 .expect("create");
750- let id = conversation.get_id().clone();750+ let id = thread.get_id().clone();
751- let prompt = ChatMessage::append_user(751+ let prompt = ChatbotMessage::append_user(
752 &id,752 &id,
753 &owner,753 &owner,
754 ChatContent::try_new("selam").expect("content"),754 ChatContent::try_new("selam").expect("content"),
@@ -756,12 +756,12 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
756 )756 )
757 .await757 .await
758 .expect("append user");758 .expect("append user");
759- let reply = ChatMessage::append_pending_assistant(&id, &owner, &db)759+ let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db)
760 .await760 .await
761 .expect("append assistant");761 .expect("append assistant");
762 assert_eq!(reply.get_status(), MessageStatus::Pending);762 assert_eq!(reply.get_status(), MessageStatus::Pending);
763 763
764- let reply = ChatMessage::complete(764+ let reply = ChatbotMessage::complete(
765 reply.get_id(),765 reply.get_id(),
766 ChatContent::try_new("aleykum selam").expect("content"),766 ChatContent::try_new("aleykum selam").expect("content"),
767 false,767 false,
@@ -773,56 +773,56 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
773 assert_eq!(reply.get_content().as_str(), "aleykum selam");773 assert_eq!(reply.get_content().as_str(), "aleykum selam");
774 assert!(reply.get_completed_at().is_some());774 assert!(reply.get_completed_at().is_some());
775 assert_eq!(775 assert_eq!(
776- ChatMessage::list_for_conversation(&id, &db)776+ ChatbotMessage::list_for_thread(&id, &db)
777 .await777 .await
778 .expect("thread")778 .expect("thread")
779 .len(),779 .len(),
780 2780 2
781 );781 );
782 782
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.
784 assert!(784 assert!(
785- Conversation::read_for(&id, &other, &db)785+ ChatbotThread::read_for(&id, &other, &db)
786 .await786 .await
787- .expect("cross-user conversation")787+ .expect("cross-user thread")
788 .is_none()788 .is_none()
789 );789 );
790 assert!(790 assert!(
791- ChatMessage::read_for(prompt.get_id(), &other, &db)791+ ChatbotMessage::read_for(prompt.get_id(), &other, &db)
792 .await792 .await
793 .expect("cross-user message")793 .expect("cross-user message")
794 .is_none()794 .is_none()
795 );795 );
796 assert_eq!(796 assert_eq!(
797- Conversation::count_for_user(&other, &db)797+ ChatbotThread::count_for_user(&other, &db)
798 .await798 .await
799 .expect("count"),799 .expect("count"),
800 0800 0
801 );801 );
802 assert_eq!(802 assert_eq!(
803- Conversation::count_for_user(&owner, &db)803+ ChatbotThread::count_for_user(&owner, &db)
804 .await804 .await
805 .expect("count"),805 .expect("count"),
806 1806 1
807 );807 );
808 808
809- conversation.delete(&db).await.expect("delete");809+ thread.delete(&db).await.expect("delete");
810 assert!(810 assert!(
811- Conversation::read_for(&id, &owner, &db)811+ ChatbotThread::read_for(&id, &owner, &db)
812 .await812 .await
813- .expect("deleted conversation")813+ .expect("deleted thread")
814 .is_none()814 .is_none()
815 );815 );
816 assert_eq!(816 assert_eq!(
817- Conversation::list_for_user(&owner, &db)817+ ChatbotThread::list_for_user(&owner, &db)
818 .await818 .await
819 .unwrap()819 .unwrap()
820 .len(),820 .len(),
821 0821 0
822 );822 );
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.
824 let mut left = db824 let mut left = db
825- .query("SELECT VALUE id FROM chat_message")825+ .query("SELECT VALUE id FROM chatbot_message")
826 .await826 .await
827 .expect("sweep")827 .expect("sweep")
828 .check()828 .check()
@@ -839,8 +839,8 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
839 /// read back as whole, which is exactly how they were shown at the time.839 /// read back as whole, which is exactly how they were shown at the time.
840 #[tokio::test]840 #[tokio::test]
841 async fn legacy_chat_turns_backfill_to_untruncated() {841 async fn legacy_chat_turns_backfill_to_untruncated() {
842- use hezarfen_backend::domain::chat_message::{ChatContent, ChatMessage};842+ use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage};
843- use hezarfen_backend::domain::conversation::Conversation;843+ use hezarfen_backend::domain::chatbot_thread::ChatbotThread;
844 use hezarfen_backend::domain::user::UserId;844 use hezarfen_backend::domain::user::UserId;
845 845
846 let (app, db) = common::app_and_db().await;846 let (app, db) = common::app_and_db().await;
@@ -857,11 +857,11 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
857 .unwrap();857 .unwrap();
858 let owner = UserId::from_key(&me_id(&app, &cookie).await);858 let owner = UserId::from_key(&me_id(&app, &cookie).await);
859 859
860- let conversation = Conversation::create(&owner, None, &db)860+ let thread = ChatbotThread::create(&owner, None, &db)
861 .await861 .await
862 .expect("create");862 .expect("create");
863- let id = conversation.get_id().clone();863+ let id = thread.get_id().clone();
864- ChatMessage::append_user(864+ ChatbotMessage::append_user(
865 &id,865 &id,
866 &owner,866 &owner,
867 ChatContent::try_new("selam").expect("content"),867 ChatContent::try_new("selam").expect("content"),
@@ -869,10 +869,10 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
869 )869 )
870 .await870 .await
871 .expect("append user");871 .expect("append user");
872- let reply = ChatMessage::append_pending_assistant(&id, &owner, &db)872+ let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db)
873 .await873 .await
874 .expect("append assistant");874 .expect("append assistant");
875- ChatMessage::complete(875+ ChatbotMessage::complete(
876 reply.get_id(),876 reply.get_id(),
877 ChatContent::try_new("aleykum selam").expect("content"),877 ChatContent::try_new("aleykum selam").expect("content"),
878 false,878 false,
@@ -883,8 +883,8 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
883 883
884 // Strip the column the way a pre-flag binary's schema would have left it.884 // Strip the column the way a pre-flag binary's schema would have left it.
885 db.query(885 db.query(
886- "REMOVE FIELD IF EXISTS truncated ON TABLE chat_message;886+ "REMOVE FIELD IF EXISTS truncated ON TABLE chatbot_message;
887- UPDATE chat_message SET truncated = NONE;",887+ UPDATE chatbot_message SET truncated = NONE;",
888 )888 )
889 .await889 .await
890 .expect("strip truncated")890 .expect("strip truncated")
@@ -901,7 +901,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
901 let res = send(901 let res = send(
902 &app,902 &app,
903 "GET",903 "GET",
904- &format!("/chat/conversations/{}/messages", id.key()),904+ &format!("/chatbot/threads/{}/messages", id.key()),
905 Some(&cookie),905 Some(&cookie),
906 None,906 None,
907 )907 )
tests/rate_limit.rsmodified+2 -2
@@ -24,7 +24,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router {
24 files_path: tempfile::tempdir().expect("files dir").keep(),24 files_path: tempfile::tempdir().expect("files dir").keep(),
25 cookie_secure: false,25 cookie_secure: false,
26 rate_limit,26 rate_limit,
27- chat_limit: Default::default(),27+ chatbot_limit: Default::default(),
28 exam_presence: Default::default(),28 exam_presence: Default::default(),
29 db_up: Default::default(),29 db_up: Default::default(),
30 ai: None,30 ai: None,
@@ -318,7 +318,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String {
318 files_path: tempfile::tempdir().expect("files dir").keep(),318 files_path: tempfile::tempdir().expect("files dir").keep(),
319 cookie_secure: false,319 cookie_secure: false,
320 rate_limit,320 rate_limit,
321- chat_limit: Default::default(),321+ chatbot_limit: Default::default(),
322 exam_presence: Default::default(),322 exam_presence: Default::default(),
323 db_up: Default::default(),323 db_up: Default::default(),
324 ai: None,324 ai: None,