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