diff --git a/.env.example b/.env.example index ab839bd..f78d812 100644 --- a/.env.example +++ b/.env.example @@ -35,7 +35,7 @@ RUST_LOG=info,hezarfen_backend=debug # Chatbot messages per minute, per USER (not per IP) — the tier that rations # the AI service, so a shared-IP classroom can't spend one student's budget on # another's. 0 disables it, like the tiers above. -# RATE_LIMIT_CHAT_PER_MINUTE=20 +# RATE_LIMIT_CHATBOT_PER_MINUTE=20 # Key rate limits by the rightmost X-Forwarded-For entry instead of the TCP # peer address. Enable ONLY behind a reverse proxy that appends the client IP diff --git a/README.md b/README.md index 3b977bb..ad1d8bb 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ stream on that one connection — no correlation ids, no head-of-line blocking. The bridge's certificate is published at `GET /ai/certificate` so a service can pin it before dialling (see "AI bridge (QUIC)"). The first thing riding that bridge is the **chatbot**: every signed-in user -(`parent` included) keeps private conversations with an AI service, free-form — +(`parent` included) keeps private threads with an AI service, free-form — no rule tables, no canned answers, the backend only owns auth, limits, persistence and the payload format. Sending is asynchronous because an 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 — useful for load tests. Sending a chatbot message adds a third tier, and it is keyed by **user id**, -not by IP (`RATE_LIMIT_CHAT_PER_MINUTE`, default 20), because an inference +not by IP (`RATE_LIMIT_CHATBOT_PER_MINUTE`, default 20), because an inference costs the school real money and a shared-IP classroom must not spend one student's budget on another's. `0` disables it like the other two. It is charged before anything is written, so a `429` leaves no trace (see @@ -576,21 +576,21 @@ their existing shapes: the student exam-room reads | GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | -| 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` | +| 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` | | 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") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first · paged | | GET | `/terms/{id}` | student | Get one term | | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) | | DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course still links to it | -| POST | `/chat/conversations` | student | `{title?}` — start a chatbot conversation (every role incl. `parent`, always private to its owner); `409` at `max_chat_conversations` | -| GET | `/chat/conversations` | student | The caller's conversations, newest activity first · paged | -| 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 | -| DELETE | `/chat/conversations/{id}` | student | Delete own conversation and every message in it (someone else's is a `404`, never a `403`) | -| GET | `/chat/conversations/{id}/messages` | student | The conversation's turns, oldest first — user and assistant rows alike · paged | -| 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) | -| GET | `/chat/conversations/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` | -| 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") | +| POST | `/chatbot/threads` | student | `{title?}` — start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` | +| GET | `/chatbot/threads` | student | The caller's threads, newest activity first · paged | +| 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 | +| DELETE | `/chatbot/threads/{id}` | student | Delete own thread and every message in it (someone else's is a `404`, never a `403`) | +| GET | `/chatbot/threads/{id}/messages` | student | The thread's turns, oldest first — user and assistant rows alike · paged | +| 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) | +| GET | `/chatbot/threads/{id}/messages/{mid}` | student | Poll one turn: `pending` until the answer lands, then `complete` + `content` or `failed` + `error_code` | +| 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") | `status` must be one of the school's attendance statuses (`GET /settings`); 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, exam question images alike), in bytes: `1024` (1 KiB) to `26214400` (25 MiB; a server hard cap — uploads buffer in memory), default `5242880` (5 MiB). Checked at upload time only: lowering it never touches already-stored files. -- **`chat_history_turns`** — how many prior **messages** of a conversation the +- **`chatbot_history_turns`** — how many prior **messages** of a thread the chatbot is given as context, `1`–`50` (default `10`). The unit is messages, not exchanges: a question and its answer are two, so the default remembers five question/answer pairs. Every one of them is re-sent on every reply, so the number is both what the bot remembers and what each answer costs. -- **`max_chat_conversations`** — how many chatbot conversations one user may +- **`max_chatbot_threads`** — how many chatbot threads one user may keep, `1`–`500` (default `50`); at the cap the user deletes an old one first. Storage protection, not a usage quota — that is the per-minute message limit. -- **`max_chat_message_len`** — character limit on one chat message, +- **`max_chatbot_message_len`** — character limit on one chat message, `100`–`8000` (default `4000`); the ceiling is a server hard cap, because the message and its history must fit one bridge frame. @@ -1564,18 +1564,18 @@ only as trustworthy as that HTTP hop. On an untrusted network set ## Chatbot -Every signed-in user — `parent` included — keeps private conversations with an +Every signed-in user — `parent` included — keeps private threads with an AI service. The backend is a **relay**: it owns auth, the limits, the thread, the payload format, and the last look at the answer before anyone sees it; the words are the service's. There are deliberately **no rule, intent or -canned-answer tables** — the conversation is free-form, and a school that wants +canned-answer tables** — the thread is free-form, and a school that wants different behaviour changes its AI service, not this backend. A thread is private to its owner: no teacher, no admin, nobody reads someone else's, and -another user's conversation is a `404`, never a `403`. +another user's thread is a `404`, never a `403`. ### Sending is two-phase, and that is the point -`POST /chat/conversations/{id}/messages` answers `202 {message_id, status: +`POST /chatbot/threads/{id}/messages` answers `202 {message_id, status: "pending"}` instead of the answer, because an inference outlives a normal request (and the request-timeout layer that guards every handler). Before the AI is even called, two rows are written: the user's turn, and an **empty @@ -1586,9 +1586,9 @@ outlives the HTTP request. The client then reads that row either way it likes: -- **poll** `GET /chat/conversations/{id}/messages/{mid}` — `pending` until it +- **poll** `GET /chatbot/threads/{id}/messages/{mid}` — `pending` until it settles, then `complete` with `content` or `failed` with `error_code`; -- **stream** `GET /chat/conversations/{id}/messages/{mid}/stream` — the same +- **stream** `GET /chatbot/threads/{id}/messages/{mid}/stream` — the same row over Server-Sent Events. Both read the same row, so they can never disagree, in any state. @@ -1622,7 +1622,7 @@ unchanged frontend. ### The message DTO ```json -{ "id": "01J8…", "conversation_id": "01J8…", "role": "assistant", +{ "id": "01J8…", "thread_id": "01J8…", "role": "assistant", "status": "complete", "content": "…", "truncated": false, "error_code": null, "created_at": 1761820800000, "completed_at": 1761820803120 } ``` @@ -1631,7 +1631,7 @@ unchanged frontend. `failed` (a user turn is always `complete`). `content` is empty while pending, `error_code` is set only when failed, `completed_at` is `null` until the turn settles. `truncated` is `true` when `content` is only the first part of what -the assistant answered — the rest was over `max_chat_message_len` and was cut; +the assistant answered — the rest was over `max_chatbot_message_len` and was cut; it is always `false` for a user turn and for a failed one. Show it: a clipped answer that looks whole is worse than one the reader knows is clipped. The same 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. | code | when | | --- | --- | | `202` | the turn was accepted; the answer is on its way | -| `400` | empty message, or longer than the school's `max_chat_message_len` | -| `404` | no such conversation or message — or not the caller's | -| `409` | already at `max_chat_conversations`; delete a thread first | -| `429` | over `RATE_LIMIT_CHAT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` | +| `400` | empty message, or longer than the school's `max_chatbot_message_len` | +| `404` | no such thread or message — or not the caller's | +| `409` | already at `max_chatbot_threads`; delete a thread first | +| `429` | over `RATE_LIMIT_CHATBOT_PER_MINUTE` messages/minute for this **user**; see `Retry-After` | | `503` | no connected service offers `chat.reply` — **nothing was written**, retry later | The `503` ordering matters: the bridge is checked before the rows exist, so an @@ -1666,7 +1666,7 @@ three independent mechanisms: Two more verdicts come from inspecting the answer: an **empty** reply is reported as `failed`/`empty_reply` (a blank bubble is indistinguishable from a -bug), and an **over-long** one is truncated to `max_chat_message_len` — a +bug), and an **over-long** one is truncated to `max_chatbot_message_len` — a clipped answer still helps, a discarded one does not — with `truncated: true` on the stored turn, so the clip is never passed off as the whole answer. @@ -1689,14 +1689,14 @@ Requests then arrive as ordinary `hab/1` `Request` frames whose `payload` is: ``` `history` is **oldest first** (index 0 is furthest back), optional (absent or -`[]` = a fresh conversation), and **excludes** the new message — that one is -`message`. It carries the last `chat_history_turns` **settled messages** — +`[]` = a fresh thread), and **excludes** the new message — that one is +`message`. It carries the last `chatbot_history_turns` **settled messages** — entries, not exchanges: the default `10` is five question/answer pairs, and `history` is exactly that many entries long whenever the thread holds enough of them. Only settled turns count: a failed answer is skipped and the window reaches further back for a usable one, rather than coming up short. All of it is re-sent on every request, which is why the service may be stateless: it can -restart, scale out, or be replaced mid-conversation without losing context. +restart, scale out, or be replaced mid-thread without losing context. The answer is a `Response::Ok` whose payload is: @@ -1770,10 +1770,10 @@ src/ subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum) term.rs TermId · TermName · Term (school term window) settings.rs ExamKindDef · GradeBand · Settings (per-school policy) - conversation.rs ConversationId · ConversationTitle · Conversation (one + chatbot_thread.rs ChatbotThreadId · ChatbotThreadTitle · ChatbotThread (one chatbot thread, private to its owner) - chat_message.rs ChatMessageId · ChatContent · MessageRole · MessageStatus · - ChatMessage (one turn; the assistant row is written + chatbot_message.rs ChatbotMessageId · ChatContent · MessageRole · MessageStatus · + ChatbotMessage (one turn; the assistant row is written `pending` before the AI call and settled after) appointment_slot.rs AppointmentSlotId · SlotSeries · SlotNote · AppointmentSlot (a teacher's published availability; a @@ -1807,7 +1807,7 @@ src/ auth.rs users.rs notes.rs messages.rs events.rs appointments.rs courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs - ai.rs chat.rs + ai.rs chatbot.rs ``` Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 7e74374..5cfa355 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -18,7 +18,7 @@ //! * [`tls`] — the listener's certificate //! //! The transport is generic; the features land on top of it. So far that is -//! the chatbot (`web::chat`), which routes on the `chat.reply` capability. +//! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability. pub mod chat; pub mod error; diff --git a/src/config.rs b/src/config.rs index df29255..524bab1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,7 +10,7 @@ pub const DEFAULT_API_RATE_LIMIT: u32 = 300; /// Default chatbot messages per minute *per user*. Sits far above a human /// typing while still blunting a scripted fan-out at the AI service behind the /// bridge — which is the cost this tier rations, not this process. -pub const DEFAULT_CHAT_RATE_LIMIT: u32 = 20; +pub const DEFAULT_CHATBOT_RATE_LIMIT: u32 = 20; /// Runtime configuration, sourced from environment variables (see `.env.example`). #[derive(Clone, Debug)] @@ -33,10 +33,10 @@ pub struct Config { /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier. pub rate_limit: RateLimitConfig, /// Chatbot messages one user may send per minute - /// (`RATE_LIMIT_CHAT_PER_MINUTE`). `0` disables the tier. Kept out of + /// (`RATE_LIMIT_CHATBOT_PER_MINUTE`). `0` disables the tier. Kept out of /// [`RateLimitConfig`], which is the per-IP middleware bundle: this tier is /// keyed by user and is enforced inside the handler. - pub chat_per_minute: u32, + pub chatbot_per_minute: u32, /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are /// set, an admin account with these credentials is created at boot if the /// username doesn't exist yet. Blank values count as unset. @@ -82,9 +82,9 @@ impl Config { ), trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()), }, - chat_per_minute: parse_limit( - env::var("RATE_LIMIT_CHAT_PER_MINUTE").ok(), - DEFAULT_CHAT_RATE_LIMIT, + chatbot_per_minute: parse_limit( + env::var("RATE_LIMIT_CHATBOT_PER_MINUTE").ok(), + DEFAULT_CHATBOT_RATE_LIMIT, ), admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()), admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()), diff --git a/src/constant.rs b/src/constant.rs index a5940fd..8490705 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -291,31 +291,31 @@ pub const AI_CHAT_CAPABILITY: &str = "chat.reply"; /// Hard ceiling on one chat message's characters — the newtype bound, above /// which no school setting can reach. Sized for a pasted question with its /// working, well under [`AI_MAX_FRAME_BYTES`] once history rides along. -pub const MAX_CHAT_MESSAGE_LEN: usize = 8_000; +pub const MAX_CHATBOT_MESSAGE_LEN: usize = 8_000; -/// The school-adjustable per-message character cap (`max_chat_message_len` in +/// The school-adjustable per-message character cap (`max_chatbot_message_len` in /// settings): its default and the inclusive range a manager may set. The -/// ceiling is [`MAX_CHAT_MESSAGE_LEN`] — a longer prompt costs the AI service +/// ceiling is [`MAX_CHATBOT_MESSAGE_LEN`] — a longer prompt costs the AI service /// context it needs for the history. -pub const DEFAULT_MAX_CHAT_MESSAGE_LEN: i64 = 4_000; -pub const MIN_MAX_CHAT_MESSAGE_LEN: i64 = 100; -pub const MAX_MAX_CHAT_MESSAGE_LEN: i64 = MAX_CHAT_MESSAGE_LEN as i64; +pub const DEFAULT_MAX_CHATBOT_MESSAGE_LEN: i64 = 4_000; +pub const MIN_MAX_CHATBOT_MESSAGE_LEN: i64 = 100; +pub const MAX_MAX_CHATBOT_MESSAGE_LEN: i64 = MAX_CHATBOT_MESSAGE_LEN as i64; -/// How many prior user/assistant turns of a conversation are replayed to the -/// AI service as context (`chat_history_turns` in settings): its default and +/// How many prior user/assistant turns of a thread are replayed to the +/// AI service as context (`chatbot_history_turns` in settings): its default and /// the inclusive range a manager may set. Every turn is re-sent on every /// request, so the ceiling bounds both the frame size and the inference cost. -pub const DEFAULT_CHAT_HISTORY_TURNS: i64 = 10; -pub const MIN_CHAT_HISTORY_TURNS: i64 = 1; -pub const MAX_CHAT_HISTORY_TURNS: i64 = 50; +pub const DEFAULT_CHATBOT_HISTORY_TURNS: i64 = 10; +pub const MIN_CHATBOT_HISTORY_TURNS: i64 = 1; +pub const MAX_CHATBOT_HISTORY_TURNS: i64 = 50; -/// How many conversations one user may keep (`max_chat_conversations` in +/// How many threads one user may keep (`max_chatbot_threads` in /// settings): its default and the inclusive range a manager may set. Reached, -/// the user deletes an old conversation before starting a new one — the cap is +/// the user deletes an old thread before starting a new one — the cap is /// storage protection, not a usage quota. -pub const DEFAULT_MAX_CHAT_CONVERSATIONS: i64 = 50; -pub const MIN_MAX_CHAT_CONVERSATIONS: i64 = 1; -pub const MAX_MAX_CHAT_CONVERSATIONS: i64 = 500; +pub const DEFAULT_MAX_CHATBOT_THREADS: i64 = 50; +pub const MIN_MAX_CHATBOT_THREADS: i64 = 1; +pub const MAX_MAX_CHATBOT_THREADS: i64 = 500; /// How often the chat stream re-reads a `pending` assistant message while it /// 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; /// [`AI_DEFAULT_REQUEST_TIMEOUT_SECS`] (which `AI_REQUEST_TIMEOUT_SECS` may /// raise), because the answering task normally stamps the failure itself — /// this only catches the row whose task died with the process. -pub const CHAT_PENDING_STALE_SECS: i64 = 300; +pub const CHATBOT_PENDING_STALE_SECS: i64 = 300; /// How long a dialling AI service has to complete its `Hello`/`Welcome` /// exchange before the connection is dropped. Short: the handshake is one diff --git a/src/database.rs b/src/database.rs index 660bf04..508b698 100644 --- a/src/database.rs +++ b/src/database.rs @@ -54,8 +54,8 @@ pub const HOMEWORK_TABLE: &str = "homework"; pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission"; pub const HOMEWORK_FILE_TABLE: &str = "homework_file"; pub const HOMEWORK_RESULT_TABLE: &str = "homework_result"; -pub const CONVERSATION_TABLE: &str = "conversation"; -pub const CHAT_MESSAGE_TABLE: &str = "chat_message"; +pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread"; +pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message"; pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot"; pub const APPOINTMENT_TABLE: &str = "appointment"; @@ -120,30 +120,30 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS size ON note_file TYPE int; DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; - -- Chatbot relay (2026-07-23): a `conversation` groups the turns, one - -- `chat_message` is one turn. `user_id` rides on the message too so an + -- Chatbot relay (2026-07-23): a `thread` groups the turns, one + -- `chatbot_message` is one turn. `user_id` rides on the message too so an -- ownership check needs no join. An assistant turn is born `pending` and -- is completed (or failed) by the task holding the AI-bridge stream — -- hence the BACKFILL sweep, since that task dies with the process. - DEFINE TABLE IF NOT EXISTS conversation SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user_id ON conversation TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS title ON conversation TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON conversation TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS updated_at ON conversation TYPE int; - DEFINE INDEX IF NOT EXISTS conversation_user_updated ON conversation FIELDS user_id, updated_at; - - DEFINE TABLE IF NOT EXISTS chat_message SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS conversation_id ON chat_message TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS user_id ON chat_message TYPE record READONLY; - DEFINE FIELD IF NOT EXISTS role ON chat_message TYPE string READONLY; - DEFINE FIELD IF NOT EXISTS content ON chat_message TYPE string; - DEFINE FIELD IF NOT EXISTS status ON chat_message TYPE string; - DEFINE FIELD IF NOT EXISTS truncated ON chat_message TYPE bool DEFAULT false; - DEFINE FIELD IF NOT EXISTS error_code ON chat_message TYPE option; - DEFINE FIELD IF NOT EXISTS created_at ON chat_message TYPE int READONLY; - DEFINE FIELD IF NOT EXISTS completed_at ON chat_message TYPE option; - DEFINE INDEX IF NOT EXISTS chat_message_conversation_created ON chat_message FIELDS conversation_id, created_at; - DEFINE INDEX IF NOT EXISTS chat_message_user ON chat_message FIELDS user_id; + DEFINE TABLE IF NOT EXISTS chatbot_thread SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user_id ON chatbot_thread TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS title ON chatbot_thread TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON chatbot_thread TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS updated_at ON chatbot_thread TYPE int; + DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at; + + DEFINE TABLE IF NOT EXISTS chatbot_message SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS thread_id ON chatbot_message TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS user_id ON chatbot_message TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS role ON chatbot_message TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS content ON chatbot_message TYPE string; + DEFINE FIELD IF NOT EXISTS status ON chatbot_message TYPE string; + DEFINE FIELD IF NOT EXISTS truncated ON chatbot_message TYPE bool DEFAULT false; + DEFINE FIELD IF NOT EXISTS error_code ON chatbot_message TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON chatbot_message TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS completed_at ON chatbot_message TYPE option; + DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; + DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; DEFINE TABLE IF NOT EXISTS event SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON event TYPE record; @@ -346,9 +346,9 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS chat_history_turns ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS max_chat_conversations ON settings TYPE option; - DEFINE FIELD IF NOT EXISTS max_chat_message_len ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option; + DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option; -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students -- submit files + optional text, a teacher grades a status + optional mark. @@ -471,12 +471,12 @@ const BACKFILL: &str = " -- Turns written before the clipped-answer flag existed (2026-07-23): the -- clip was silent then, so nothing can be recovered — they read as whole, -- which is what they were presented as all along. - UPDATE chat_message SET truncated = false WHERE truncated = NONE; + UPDATE chatbot_message SET truncated = false WHERE truncated = NONE; -- An assistant turn is answered by an in-process task, so a restart leaves -- its row `pending` with nobody left to complete it: fail it at boot rather - -- than let a reader wait out `CHAT_PENDING_STALE_SECS` on every load. - UPDATE chat_message SET status = 'failed', error_code = 'interrupted', + -- than let a reader wait out `CHATBOT_PENDING_STALE_SECS` on every load. + UPDATE chatbot_message SET status = 'failed', error_code = 'interrupted', completed_at = time::unix(time::now()) * 1000 WHERE status = 'pending'; -- Promotion out of student now deletes the user's enrollments (2026-07-18); @@ -546,14 +546,14 @@ pub async fn migrate(db: &Surreal) -> Result<(), AppError> { #[cfg(test)] mod tests { #[tokio::test] - async fn boot_fails_chat_messages_left_pending() { + async fn boot_fails_chatbot_messages_left_pending() { let db = super::init_mem().await.unwrap(); db.query( "CREATE user:u SET username = 'u', password_hash = 'x'; - CREATE conversation:c SET user_id = user:u, created_at = 1, updated_at = 1; - CREATE chat_message:m SET conversation_id = conversation:c, user_id = user:u, + CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; + CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, role = 'assistant', content = '', status = 'pending', created_at = 1; - CREATE chat_message:done SET conversation_id = conversation:c, user_id = user:u, + CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u, role = 'assistant', content = 'hi', status = 'complete', created_at = 1;", ) .await @@ -566,7 +566,7 @@ mod tests { super::migrate(&db).await.unwrap(); let mut rows = db - .query("SELECT id, status, error_code, completed_at FROM chat_message ORDER BY id") + .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id") .await .unwrap(); let rows: Vec = rows.take(0).unwrap(); diff --git a/src/domain/chat_message.rs b/src/domain/chatbot_message.rs similarity index 80% rename from src/domain/chat_message.rs rename to src/domain/chatbot_message.rs index 3847bf4..9726d91 100644 --- a/src/domain/chat_message.rs +++ b/src/domain/chatbot_message.rs @@ -5,7 +5,7 @@ //! a code) — and if that task dies with the process, the boot sweep in //! `database.rs` fails the row instead. //! -//! `user_id` is duplicated from the conversation onto every message so an +//! `user_id` is duplicated from the thread onto every message so an //! ownership check is one read, with no join. use std::sync::{LazyLock, Mutex}; @@ -13,9 +13,9 @@ use std::sync::{LazyLock, Mutex}; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::{Generator, Ulid}; -use crate::constant::{CHAT_PENDING_STALE_SECS, MAX_CHAT_MESSAGE_LEN}; +use crate::constant::{CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN}; use crate::database::{CHAT_MESSAGE_TABLE, Database}; -use crate::domain::conversation::ConversationId; +use crate::domain::chatbot_thread::ChatbotThreadId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -33,7 +33,7 @@ const MAX_ERROR_CODE_LEN: usize = 64; /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random /// low bits sort arbitrarily among ids minted in the same millisecond, this /// increments the previous id — so the `id` tie-break in the `ORDER BY` of -/// [`ChatMessage::list_for_conversation`] / [`ChatMessage::list_tail`] is the +/// [`ChatbotMessage::list_for_thread`] / [`ChatbotMessage::list_tail`] is the /// order the rows were written. The user prompt and the assistant row one POST /// writes back-to-back routinely share a millisecond, and a random tie-break /// there renders the answer *above* its own question — and hands the AI @@ -41,9 +41,9 @@ const MAX_ERROR_CODE_LEN: usize = 64; static IDS: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatMessageId(RecordId); +pub struct ChatbotMessageId(RecordId); -impl ChatMessageId { +impl ChatbotMessageId { pub fn generate() -> Self { let mut ids = IDS.lock().expect("chat id generator poisoned"); // The only error is overflow of the random bits *within* one @@ -115,13 +115,13 @@ impl MessageStatus { } /// One turn's text. The hard ceiling only — the school-adjustable -/// `max_chat_message_len` is the web layer's to enforce, below this. +/// `max_chatbot_message_len` is the web layer's to enforce, below this. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ChatContent(String); impl ChatContent { pub fn try_new(value: &str) -> Result { - validate_required("content", value, MAX_CHAT_MESSAGE_LEN)?; + validate_required("content", value, MAX_CHATBOT_MESSAGE_LEN)?; Ok(Self(value.to_string())) } @@ -137,9 +137,9 @@ impl ChatContent { } #[derive(Debug, Clone, SurrealValue)] -pub struct ChatMessage { - id: ChatMessageId, - conversation_id: ConversationId, +pub struct ChatbotMessage { + id: ChatbotMessageId, + thread_id: ChatbotThreadId, user_id: UserId, role: MessageRole, content: ChatContent, @@ -153,13 +153,13 @@ pub struct ChatMessage { completed_at: Option, } -impl ChatMessage { - pub fn get_id(&self) -> &ChatMessageId { +impl ChatbotMessage { + pub fn get_id(&self) -> &ChatbotMessageId { &self.id } - pub fn get_conversation_id(&self) -> &ConversationId { - &self.conversation_id + pub fn get_thread_id(&self) -> &ChatbotThreadId { + &self.thread_id } pub fn get_user_id(&self) -> &UserId { @@ -194,7 +194,7 @@ impl ChatMessage { self.completed_at } - /// A row still `pending` past [`CHAT_PENDING_STALE_SECS`] has lost the task + /// A row still `pending` past [`CHATBOT_PENDING_STALE_SECS`] has lost the task /// that owed it an answer; present it as failed. /// /// Read-time projection, not a lazy write-back: the read paths (poll loop, @@ -204,7 +204,7 @@ impl ChatMessage { /// (a dead process) already happens once, at boot. The stored row stays /// truthful; only the answer handed to the caller is projected. fn projected(mut self) -> Self { - let stale_at = self.created_at.as_millis() + CHAT_PENDING_STALE_SECS * 1_000; + let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000; if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at { self.status = MessageStatus::Failed; self.error_code = Some(STALE_ERROR_CODE.to_string()); @@ -212,24 +212,24 @@ impl ChatMessage { self } - async fn insert(message: ChatMessage, db: &Database) -> Result { - let created: Option = db.create(message.id.record()).content(message).await?; + async fn insert(message: ChatbotMessage, db: &Database) -> Result { + let created: Option = db.create(message.id.record()).content(message).await?; created.ok_or_else(|| AppError::Internal("failed to create chat message".into())) } /// Append the user's prompt. Nothing is awaited for it, so it is born /// complete. pub async fn append_user( - conversation: &ConversationId, + thread: &ChatbotThreadId, user: &UserId, content: ChatContent, db: &Database, - ) -> Result { + ) -> Result { let now = Timestamp::now(); Self::insert( - ChatMessage { - id: ChatMessageId::generate(), - conversation_id: conversation.clone(), + ChatbotMessage { + id: ChatbotMessageId::generate(), + thread_id: thread.clone(), user_id: user.clone(), role: MessageRole::User, content, @@ -247,14 +247,14 @@ impl ChatMessage { /// Reserve the assistant's answer *before* the AI call: the row exists, /// empty and `pending`, so a reload finds the turn and can wait on it. pub async fn append_pending_assistant( - conversation: &ConversationId, + thread: &ChatbotThreadId, user: &UserId, db: &Database, - ) -> Result { + ) -> Result { Self::insert( - ChatMessage { - id: ChatMessageId::generate(), - conversation_id: conversation.clone(), + ChatbotMessage { + id: ChatbotMessageId::generate(), + thread_id: thread.clone(), user_id: user.clone(), role: MessageRole::Assistant, content: ChatContent::empty(), @@ -271,22 +271,22 @@ impl ChatMessage { /// The whole thread, oldest first — the order both the UI and the AI /// history payload read in. - pub async fn list_for_conversation( - conversation: &ConversationId, + pub async fn list_for_thread( + thread: &ChatbotThreadId, db: &Database, - ) -> Result, AppError> { + ) -> Result, AppError> { let mut result = db .query( - "SELECT * FROM chat_message WHERE conversation_id = $conv \ + "SELECT * FROM chatbot_message WHERE thread_id = $conv \ ORDER BY created_at ASC, id ASC", ) - .bind(("conv", conversation.record())) + .bind(("conv", thread.record())) .await? .check()?; Ok(result - .take::>(0)? + .take::>(0)? .into_iter() - .map(ChatMessage::projected) + .map(ChatbotMessage::projected) .collect()) } @@ -294,23 +294,23 @@ impl ChatMessage { /// AI service as context. Taken newest-first in the database (so the /// `LIMIT` keeps the *recent* end) and flipped back here. pub async fn list_tail( - conversation: &ConversationId, + thread: &ChatbotThreadId, limit: usize, db: &Database, - ) -> Result, AppError> { + ) -> Result, AppError> { let mut result = db .query( - "SELECT * FROM chat_message WHERE conversation_id = $conv \ + "SELECT * FROM chatbot_message WHERE thread_id = $conv \ ORDER BY created_at DESC, id DESC LIMIT $limit", ) - .bind(("conv", conversation.record())) + .bind(("conv", thread.record())) .bind(("limit", limit as i64)) .await? .check()?; - let mut messages: Vec = result - .take::>(0)? + let mut messages: Vec = result + .take::>(0)? .into_iter() - .map(ChatMessage::projected) + .map(ChatbotMessage::projected) .collect(); messages.reverse(); Ok(messages) @@ -323,35 +323,35 @@ impl ChatMessage { /// instead of reaching further back. No projection is applied — it only /// ever rewrites a `pending` row, and none is selected here. pub async fn list_settled_tail( - conversation: &ConversationId, + thread: &ChatbotThreadId, limit: usize, db: &Database, - ) -> Result, AppError> { + ) -> Result, AppError> { let mut result = db .query( - "SELECT * FROM chat_message WHERE conversation_id = $conv \ + "SELECT * FROM chatbot_message WHERE thread_id = $conv \ AND status = 'complete' AND content != '' \ ORDER BY created_at DESC, id DESC LIMIT $limit", ) - .bind(("conv", conversation.record())) + .bind(("conv", thread.record())) .bind(("limit", limit as i64)) .await? .check()?; - let mut messages: Vec = result.take(0)?; + let mut messages: Vec = result.take(0)?; messages.reverse(); Ok(messages) } /// Read one turn only if `user` owns it — the poll loop's read. pub async fn read_for( - id: &ChatMessageId, + id: &ChatbotMessageId, user: &UserId, db: &Database, - ) -> Result, AppError> { - let message: Option = db.select(id.record()).await?; + ) -> Result, AppError> { + let message: Option = db.select(id.record()).await?; Ok(message .filter(|message| &message.user_id == user) - .map(ChatMessage::projected)) + .map(ChatbotMessage::projected)) } /// Land the answer, recording whether it had to be clipped to fit the @@ -359,32 +359,32 @@ impl ChatMessage { /// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a /// timeout) already failed, and two answers can't both apply. pub async fn complete( - id: &ChatMessageId, + id: &ChatbotMessageId, text: ChatContent, truncated: bool, db: &Database, - ) -> Result { + ) -> Result { Self::settle(id, Some(text), truncated, None, db).await } /// Mark the answer failed with a short code (`unavailable`, the service's - /// own error code, …). Same pending gate as [`ChatMessage::complete`]. + /// own error code, …). Same pending gate as [`ChatbotMessage::complete`]. pub async fn fail( - id: &ChatMessageId, + id: &ChatbotMessageId, error_code: &str, db: &Database, - ) -> Result { + ) -> Result { // A failed turn has no text, so there is nothing that could be clipped. Self::settle(id, None, false, Some(error_code), db).await } async fn settle( - id: &ChatMessageId, + id: &ChatbotMessageId, text: Option, truncated: bool, error_code: Option<&str>, db: &Database, - ) -> Result { + ) -> Result { let status = if text.is_some() { MessageStatus::Complete } else { @@ -407,7 +407,7 @@ impl ChatMessage { .await? .check()?; result - .take::>(0)? + .take::>(0)? .into_iter() .next() .ok_or(AppError::NotFound) @@ -422,8 +422,8 @@ mod tests { #[tokio::test] async fn content_is_required_and_capped() { assert!(ChatContent::try_new("").is_err()); - assert!(ChatContent::try_new(&"x".repeat(MAX_CHAT_MESSAGE_LEN)).is_ok()); - assert!(ChatContent::try_new(&"x".repeat(MAX_CHAT_MESSAGE_LEN + 1)).is_err()); + assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN)).is_ok()); + assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err()); } #[tokio::test] @@ -455,24 +455,24 @@ mod tests { // inverted a fifth of the pairs; here every pair must read back // question-then-answer, from both read paths. let db = crate::database::init_mem().await.unwrap(); - let conversation = ConversationId::from_key("c"); + let thread = ChatbotThreadId::from_key("c"); let user = UserId::from_key("u"); const TURNS: usize = 200; for turn in 0..TURNS { let content = ChatContent::try_new(&format!("soru {turn}")).unwrap(); - ChatMessage::append_user(&conversation, &user, content, &db) + ChatbotMessage::append_user(&thread, &user, content, &db) .await .unwrap(); - ChatMessage::append_pending_assistant(&conversation, &user, &db) + ChatbotMessage::append_pending_assistant(&thread, &user, &db) .await .unwrap(); } - let whole = ChatMessage::list_for_conversation(&conversation, &db) + let whole = ChatbotMessage::list_for_thread(&thread, &db) .await .unwrap(); - let tail = ChatMessage::list_tail(&conversation, TURNS * 2, &db) + let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db) .await .unwrap(); for messages in [&whole, &tail] { @@ -488,9 +488,9 @@ mod tests { #[tokio::test] async fn stale_pending_projects_as_failed() { let aged = |secs: i64| { - ChatMessage { - id: ChatMessageId::generate(), - conversation_id: ConversationId::from_key("c"), + ChatbotMessage { + id: ChatbotMessageId::generate(), + thread_id: ChatbotThreadId::from_key("c"), user_id: UserId::from_key("u"), role: MessageRole::Assistant, content: ChatContent::empty(), @@ -507,7 +507,7 @@ mod tests { assert_eq!(fresh.get_status(), MessageStatus::Pending); assert_eq!(fresh.get_error_code(), None); - let stale = aged(CHAT_PENDING_STALE_SECS + 1); + let stale = aged(CHATBOT_PENDING_STALE_SECS + 1); assert_eq!(stale.get_status(), MessageStatus::Failed); assert_eq!(stale.get_error_code(), Some(STALE_ERROR_CODE)); } diff --git a/src/domain/conversation.rs b/src/domain/chatbot_thread.rs similarity index 61% rename from src/domain/conversation.rs rename to src/domain/chatbot_thread.rs index 1755c90..14d0f20 100644 --- a/src/domain/conversation.rs +++ b/src/domain/chatbot_thread.rs @@ -1,40 +1,40 @@ //! A chatbot thread. It only groups turns and carries the ordering key the //! list view sorts on: `updated_at` moves on every new turn, so a user's -//! conversations list newest-activity-first. The turns themselves live in -//! [`crate::domain::chat_message`], and deleting a conversation cascades them. +//! threads list newest-activity-first. The turns themselves live in +//! [`crate::domain::chatbot_message`], and deleting a thread cascades them. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use ulid::Ulid; -use crate::database::{CONVERSATION_TABLE, Database}; +use crate::database::{CHATBOT_THREAD_TABLE, Database}; use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; -/// Serializes thread creation so the `max_chat_conversations` check (count, +/// Serializes thread creation so the `max_chatbot_threads` check (count, /// then write) can't over-admit under concurrency — the database's optimistic /// transactions don't serialize cross-record counts against concurrent /// inserts. Same reasoning, and the same shape, as `ENROLL_LOCK`. -static CONVERSATION_LOCK: Mutex<()> = Mutex::const_new(()); +static CHATBOT_THREAD_LOCK: Mutex<()> = Mutex::const_new(()); /// Bound on a thread's display name. Local to this module because /// `constant.rs` is another task's file; move it there with the rest of the /// chat limits when they are next touched. -const MAX_CONVERSATION_TITLE_LEN: usize = 200; +const MAX_CHATBOT_THREAD_TITLE_LEN: usize = 200; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ConversationId(RecordId); +pub struct ChatbotThreadId(RecordId); -impl ConversationId { +impl ChatbotThreadId { pub fn generate() -> Self { - Self(RecordId::new(CONVERSATION_TABLE, Ulid::new().to_string())) + Self(RecordId::new(CHATBOT_THREAD_TABLE, Ulid::new().to_string())) } pub fn from_key(key: &str) -> Self { - Self(RecordId::new(CONVERSATION_TABLE, key)) + Self(RecordId::new(CHATBOT_THREAD_TABLE, key)) } pub fn record(&self) -> RecordId { @@ -50,13 +50,13 @@ impl ConversationId { } /// A user-chosen thread name. Required-and-bounded here; "untitled" is -/// `Option` on the row. +/// `Option` on the row. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ConversationTitle(String); +pub struct ChatbotThreadTitle(String); -impl ConversationTitle { +impl ChatbotThreadTitle { pub fn try_new(value: &str) -> Result { - validate_required("title", value, MAX_CONVERSATION_TITLE_LEN)?; + validate_required("title", value, MAX_CHATBOT_THREAD_TITLE_LEN)?; Ok(Self(value.to_string())) } @@ -66,16 +66,16 @@ impl ConversationTitle { } #[derive(Debug, Clone, SurrealValue)] -pub struct Conversation { - id: ConversationId, +pub struct ChatbotThread { + id: ChatbotThreadId, user_id: UserId, - title: Option, + title: Option, created_at: Timestamp, updated_at: Timestamp, } -impl Conversation { - pub fn get_id(&self) -> &ConversationId { +impl ChatbotThread { + pub fn get_id(&self) -> &ChatbotThreadId { &self.id } @@ -83,7 +83,7 @@ impl Conversation { &self.user_id } - pub fn get_title(&self) -> Option<&ConversationTitle> { + pub fn get_title(&self) -> Option<&ChatbotThreadTitle> { self.title.as_ref() } @@ -97,62 +97,62 @@ impl Conversation { pub async fn create( user: &UserId, - title: Option, + title: Option, db: &Database, - ) -> Result { + ) -> Result { let now = Timestamp::now(); - let conversation = Conversation { - id: ConversationId::generate(), + let thread = ChatbotThread { + id: ChatbotThreadId::generate(), user_id: user.clone(), title, created_at: now, updated_at: now, }; - let created: Option = db - .create(conversation.id.record()) - .content(conversation) + let created: Option = db + .create(thread.id.record()) + .content(thread) .await?; - created.ok_or_else(|| AppError::Internal("failed to create conversation".into())) + created.ok_or_else(|| AppError::Internal("failed to create thread".into())) } /// Start a thread unless `user` is already at the school's - /// `max_chat_conversations`. The whole check-then-write runs under - /// [`CONVERSATION_LOCK`], and the cap is re-read inside it, since neither + /// `max_chatbot_threads`. The whole check-then-write runs under + /// [`CHATBOT_THREAD_LOCK`], and the cap is re-read inside it, since neither /// the transaction model nor a caller-supplied number survives a concurrent /// settings PATCH. pub async fn create_capped( user: &UserId, - title: Option, + title: Option, db: &Database, - ) -> Result { - let _guard = CONVERSATION_LOCK.lock().await; - let cap = Settings::load(db).await?.get_max_chat_conversations(); + ) -> Result { + let _guard = CHATBOT_THREAD_LOCK.lock().await; + let cap = Settings::load(db).await?.get_max_chatbot_threads(); if Self::count_for_user(user, db).await? as i64 >= cap { return Err(AppError::Conflict( - "you have reached the school's limit on saved conversations — delete one first", + "you have reached the school's limit on saved threads — delete one first", )); } Self::create(user, title, db).await } /// A user's threads, most recently active first — the sort the - /// `conversation_user_updated` index exists for. + /// `chatbot_thread_user_updated` index exists for. pub async fn list_for_user( user: &UserId, db: &Database, - ) -> Result, AppError> { + ) -> Result, AppError> { let mut result = db - .query("SELECT * FROM conversation WHERE user_id = $usr ORDER BY updated_at DESC") + .query("SELECT * FROM chatbot_thread WHERE user_id = $usr ORDER BY updated_at DESC") .bind(("usr", user.record())) .await? .check()?; - Ok(result.take::>(0)?) + Ok(result.take::>(0)?) } - /// How many threads `user` keeps — the `max_chat_conversations` cap check. + /// How many threads `user` keeps — the `max_chatbot_threads` cap check. pub async fn count_for_user(user: &UserId, db: &Database) -> Result { let mut result = db - .query("SELECT VALUE count() FROM conversation WHERE user_id = $usr GROUP ALL") + .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL") .bind(("usr", user.record())) .await? .check()?; @@ -167,17 +167,17 @@ impl Conversation { /// Read a thread only if `user` owns it — a foreign id reads as absent, so /// the web layer answers 404 rather than leaking that it exists. pub async fn read_for( - id: &ConversationId, + id: &ChatbotThreadId, user: &UserId, db: &Database, - ) -> Result, AppError> { - let conversation: Option = db.select(id.record()).await?; - Ok(conversation.filter(|conversation| &conversation.user_id == user)) + ) -> Result, AppError> { + let thread: Option = db.select(id.record()).await?; + Ok(thread.filter(|thread| &thread.user_id == user)) } /// Stamp new activity. Field-scoped: a rename may be landing concurrently, /// and a whole-row save would clobber it. - pub async fn touch(&self, db: &Database) -> Result { + pub async fn touch(&self, db: &Database) -> Result { let mut result = db .query("UPDATE $id SET updated_at = $now RETURN AFTER") .bind(("id", self.id.record())) @@ -185,7 +185,7 @@ impl Conversation { .await? .check()?; result - .take::>(0)? + .take::>(0)? .into_iter() .next() .ok_or(AppError::NotFound) @@ -193,12 +193,12 @@ impl Conversation { /// Rename the thread (`None` clears the name back to untitled), stamping /// the edit as activity. Field-scoped for the same reason as - /// [`Conversation::touch`]: a turn may be landing concurrently. + /// [`ChatbotThread::touch`]: a turn may be landing concurrently. pub async fn rename( &self, - title: Option, + title: Option, db: &Database, - ) -> Result { + ) -> Result { let mut result = db .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER") .bind(("id", self.id.record())) @@ -207,27 +207,27 @@ impl Conversation { .await? .check()?; result - .take::>(0)? + .take::>(0)? .into_iter() .next() .ok_or(AppError::NotFound) } /// Delete the thread and every turn in it — one transaction, so a crash - /// can't orphan messages under a vanished conversation. - pub async fn delete(self, db: &Database) -> Result { + /// can't orphan messages under a vanished thread. + pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( "BEGIN TRANSACTION; - DELETE chat_message WHERE conversation_id = $conv; + DELETE chatbot_message WHERE thread_id = $conv; DELETE $conv RETURN BEFORE; COMMIT TRANSACTION;", ) .bind(("conv", self.id.record())) .await? .check()?; - // BEGIN is slot 0; the conversation's own DELETE is slot 2. - let deleted: Option = result.take::>(2)?.into_iter().next(); + // BEGIN is slot 0; the thread's own DELETE is slot 2. + let deleted: Option = result.take::>(2)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } @@ -239,10 +239,10 @@ mod tests { #[tokio::test] async fn title_is_required_and_bounded() { assert_eq!( - ConversationTitle::try_new("Fizik").unwrap().as_str(), + ChatbotThreadTitle::try_new("Fizik").unwrap().as_str(), "Fizik" ); - assert!(ConversationTitle::try_new(" ").is_err()); - assert!(ConversationTitle::try_new(&"x".repeat(201)).is_err()); + assert!(ChatbotThreadTitle::try_new(" ").is_err()); + assert!(ChatbotThreadTitle::try_new(&"x".repeat(201)).is_err()); } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index f9c7dcd..b8e612b 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -6,8 +6,8 @@ pub mod answer_image; pub mod appointment; pub mod appointment_slot; pub mod attendance; -pub mod chat_message; -pub mod conversation; +pub mod chatbot_message; +pub mod chatbot_thread; pub mod course; pub mod course_session; pub mod enrollment; diff --git a/src/domain/settings.rs b/src/domain/settings.rs index b76f81c..dfa1890 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -14,12 +14,12 @@ use surrealdb::types::{RecordId, SurrealValue}; use crate::constant::{ - DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHAT_HISTORY_TURNS, DEFAULT_EXAM_KINDS, - DEFAULT_MAX_CHAT_CONVERSATIONS, DEFAULT_MAX_CHAT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES, - MAX_CHAT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, - MAX_MAX_CHAT_CONVERSATIONS, MAX_MAX_CHAT_MESSAGE_LEN, MAX_MAX_FILE_BYTES, - MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHAT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, - MIN_MARK, MIN_MAX_CHAT_CONVERSATIONS, MIN_MAX_CHAT_MESSAGE_LEN, MIN_MAX_FILE_BYTES, + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS, + DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_FILE_BYTES, + MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, + MAX_MAX_CHATBOT_THREADS, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_FILE_BYTES, + MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, + MIN_MARK, MIN_MAX_CHATBOT_THREADS, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_FILE_BYTES, }; use crate::database::{Database, SETTINGS_TABLE}; use crate::error::{AppError, ValidationError}; @@ -118,9 +118,9 @@ pub struct Settings { /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. max_file_bytes: Option, /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`. - chat_history_turns: Option, - max_chat_conversations: Option, - max_chat_message_len: Option, + chatbot_history_turns: Option, + max_chatbot_threads: Option, + max_chatbot_message_len: Option, } /// Everything [`Settings::try_new`] validates, in one struct — the knobs @@ -132,9 +132,9 @@ pub struct SettingsParams { pub attendance_statuses: Vec, pub grade_bands: Vec, pub max_file_bytes: i64, - pub chat_history_turns: i64, - pub max_chat_conversations: i64, - pub max_chat_message_len: i64, + pub chatbot_history_turns: i64, + pub max_chatbot_threads: i64, + pub max_chatbot_message_len: i64, } impl Settings { @@ -156,9 +156,9 @@ impl Settings { attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), grade_bands: Vec::new(), max_file_bytes: None, - chat_history_turns: None, - max_chat_conversations: None, - max_chat_message_len: None, + chatbot_history_turns: None, + max_chatbot_threads: None, + max_chatbot_message_len: None, } } @@ -170,9 +170,9 @@ impl Settings { attendance_statuses: self.attendance_statuses.clone(), grade_bands: self.grade_bands.clone(), max_file_bytes: self.get_max_file_bytes(), - chat_history_turns: self.get_chat_history_turns(), - max_chat_conversations: self.get_max_chat_conversations(), - max_chat_message_len: self.get_max_chat_message_len(), + chatbot_history_turns: self.get_chatbot_history_turns(), + max_chatbot_threads: self.get_max_chatbot_threads(), + max_chatbot_message_len: self.get_max_chatbot_message_len(), } } @@ -190,9 +190,9 @@ impl Settings { attendance_statuses, grade_bands, max_file_bytes, - chat_history_turns, - max_chat_conversations, - max_chat_message_len, + chatbot_history_turns, + max_chatbot_threads, + max_chatbot_message_len, } = params; in_range( "max_file_bytes", @@ -201,21 +201,21 @@ impl Settings { "must be between 1024 (1 KiB) and 26214400 (25 MiB)", )?; in_range( - "chat_history_turns", - chat_history_turns, - MIN_CHAT_HISTORY_TURNS..=MAX_CHAT_HISTORY_TURNS, + "chatbot_history_turns", + chatbot_history_turns, + MIN_CHATBOT_HISTORY_TURNS..=MAX_CHATBOT_HISTORY_TURNS, "must be between 1 and 50", )?; in_range( - "max_chat_conversations", - max_chat_conversations, - MIN_MAX_CHAT_CONVERSATIONS..=MAX_MAX_CHAT_CONVERSATIONS, + "max_chatbot_threads", + max_chatbot_threads, + MIN_MAX_CHATBOT_THREADS..=MAX_MAX_CHATBOT_THREADS, "must be between 1 and 500", )?; in_range( - "max_chat_message_len", - max_chat_message_len, - MIN_MAX_CHAT_MESSAGE_LEN..=MAX_MAX_CHAT_MESSAGE_LEN, + "max_chatbot_message_len", + max_chatbot_message_len, + MIN_MAX_CHATBOT_MESSAGE_LEN..=MAX_MAX_CHATBOT_MESSAGE_LEN, "must be between 100 and 8000 characters", )?; // Per-entry rules (name shape, weight range) hold structurally on any @@ -267,9 +267,9 @@ impl Settings { attendance_statuses, grade_bands, max_file_bytes: Some(max_file_bytes), - chat_history_turns: Some(chat_history_turns), - max_chat_conversations: Some(max_chat_conversations), - max_chat_message_len: Some(max_chat_message_len), + chatbot_history_turns: Some(chatbot_history_turns), + max_chatbot_threads: Some(max_chatbot_threads), + max_chatbot_message_len: Some(max_chatbot_message_len), }) } @@ -302,25 +302,25 @@ impl Settings { self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES) } - /// How many prior conversation turns ride along as context on an AI + /// How many prior thread turns ride along as context on an AI /// request; the built-in default while the school never set one. - pub fn get_chat_history_turns(&self) -> i64 { - self.chat_history_turns - .unwrap_or(DEFAULT_CHAT_HISTORY_TURNS) + pub fn get_chatbot_history_turns(&self) -> i64 { + self.chatbot_history_turns + .unwrap_or(DEFAULT_CHATBOT_HISTORY_TURNS) } - /// How many conversations one user may keep; the built-in default while + /// How many threads one user may keep; the built-in default while /// the school never set one. - pub fn get_max_chat_conversations(&self) -> i64 { - self.max_chat_conversations - .unwrap_or(DEFAULT_MAX_CHAT_CONVERSATIONS) + pub fn get_max_chatbot_threads(&self) -> i64 { + self.max_chatbot_threads + .unwrap_or(DEFAULT_MAX_CHATBOT_THREADS) } /// Character cap on one chat message; the built-in default while the /// school never set one. - pub fn get_max_chat_message_len(&self) -> i64 { - self.max_chat_message_len - .unwrap_or(DEFAULT_MAX_CHAT_MESSAGE_LEN) + pub fn get_max_chatbot_message_len(&self) -> i64 { + self.max_chatbot_message_len + .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN) } /// The label of the band `mark` falls into: the band with the greatest @@ -374,9 +374,9 @@ impl Settings { AND attendance_statuses = $st AND grade_bands = $gb AND max_file_bytes = $mf - AND chat_history_turns = $ct - AND max_chat_conversations = $cc - AND max_chat_message_len = $cl; + AND chatbot_history_turns = $ct + AND max_chatbot_threads = $cc + AND max_chatbot_message_len = $cl; COMMIT TRANSACTION;", ) .bind(("expected", expected.clone())) @@ -386,9 +386,9 @@ impl Settings { .bind(("st", expected.attendance_statuses.clone())) .bind(("gb", expected.grade_bands.clone())) .bind(("mf", expected.max_file_bytes)) - .bind(("ct", expected.chat_history_turns)) - .bind(("cc", expected.max_chat_conversations)) - .bind(("cl", expected.max_chat_message_len)) + .bind(("ct", expected.chatbot_history_turns)) + .bind(("cc", expected.max_chatbot_threads)) + .bind(("cl", expected.max_chatbot_message_len)) .await? .check()?; // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An @@ -450,7 +450,7 @@ fn validate_list(field: &'static str, values: Vec) -> Result #[cfg(test)] mod tests { use super::*; - use crate::constant::MAX_CHAT_MESSAGE_LEN; + use crate::constant::MAX_CHATBOT_MESSAGE_LEN; fn kinds(list: &[&str]) -> Vec { list.iter() @@ -618,49 +618,49 @@ mod tests { #[tokio::test] async fn chat_knobs_are_bounded() { // Each knob is held to its own inclusive range; the edges are legal. - let turns = |chat_history_turns| { + let turns = |chatbot_history_turns| { Settings::try_new(SettingsParams { - chat_history_turns, + chatbot_history_turns, ..params() }) }; assert_eq!( - turns(MAX_CHAT_HISTORY_TURNS) + turns(MAX_CHATBOT_HISTORY_TURNS) .unwrap() - .get_chat_history_turns(), - MAX_CHAT_HISTORY_TURNS + .get_chatbot_history_turns(), + MAX_CHATBOT_HISTORY_TURNS ); - assert!(turns(MIN_CHAT_HISTORY_TURNS).is_ok()); + assert!(turns(MIN_CHATBOT_HISTORY_TURNS).is_ok()); assert!(turns(0).is_err()); - assert!(turns(MAX_CHAT_HISTORY_TURNS + 1).is_err()); + assert!(turns(MAX_CHATBOT_HISTORY_TURNS + 1).is_err()); - let convos = |max_chat_conversations| { + let convos = |max_chatbot_threads| { Settings::try_new(SettingsParams { - max_chat_conversations, + max_chatbot_threads, ..params() }) }; assert_eq!( - convos(7).unwrap().get_max_chat_conversations(), + convos(7).unwrap().get_max_chatbot_threads(), 7, "an in-range cap survives validation" ); - assert!(convos(MIN_MAX_CHAT_CONVERSATIONS).is_ok()); - assert!(convos(MAX_MAX_CHAT_CONVERSATIONS).is_ok()); + assert!(convos(MIN_MAX_CHATBOT_THREADS).is_ok()); + assert!(convos(MAX_MAX_CHATBOT_THREADS).is_ok()); assert!(convos(0).is_err()); - assert!(convos(MAX_MAX_CHAT_CONVERSATIONS + 1).is_err()); + assert!(convos(MAX_MAX_CHATBOT_THREADS + 1).is_err()); - let len = |max_chat_message_len| { + let len = |max_chatbot_message_len| { Settings::try_new(SettingsParams { - max_chat_message_len, + max_chatbot_message_len, ..params() }) }; - assert!(len(MIN_MAX_CHAT_MESSAGE_LEN).is_ok()); - assert!(len(MAX_MAX_CHAT_MESSAGE_LEN).is_ok()); - assert!(len(MIN_MAX_CHAT_MESSAGE_LEN - 1).is_err()); + assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN).is_ok()); + assert!(len(MAX_MAX_CHATBOT_MESSAGE_LEN).is_ok()); + assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN - 1).is_err()); // The ceiling is the newtype's hard cap: no school can raise it. - assert!(len(MAX_CHAT_MESSAGE_LEN as i64 + 1).is_err()); + assert!(len(MAX_CHATBOT_MESSAGE_LEN as i64 + 1).is_err()); } #[tokio::test] @@ -671,14 +671,14 @@ mod tests { Settings::defaults().save(&db).await.unwrap(); let loaded = Settings::load(&db).await.unwrap(); assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES); - assert_eq!(loaded.get_chat_history_turns(), DEFAULT_CHAT_HISTORY_TURNS); + assert_eq!(loaded.get_chatbot_history_turns(), DEFAULT_CHATBOT_HISTORY_TURNS); assert_eq!( - loaded.get_max_chat_conversations(), - DEFAULT_MAX_CHAT_CONVERSATIONS + loaded.get_max_chatbot_threads(), + DEFAULT_MAX_CHATBOT_THREADS ); assert_eq!( - loaded.get_max_chat_message_len(), - DEFAULT_MAX_CHAT_MESSAGE_LEN + loaded.get_max_chatbot_message_len(), + DEFAULT_MAX_CHATBOT_MESSAGE_LEN ); // And a snapshot of that old row still passes the compare-and-set. let saved = Settings::try_new(SettingsParams { @@ -708,7 +708,7 @@ mod tests { exam_kinds: kinds(&["lab"]), grade_bands: bands(&[(0, "F"), (50, "P")]), max_file_bytes: 2048, - chat_history_turns: 3, + chatbot_history_turns: 3, ..params() }) .unwrap() @@ -720,7 +720,7 @@ mod tests { assert_eq!(loaded.get_grade_bands().len(), 2); assert_eq!(loaded.grade_label(60.0), Some("P")); assert_eq!(loaded.get_max_file_bytes(), 2048); - assert_eq!(loaded.get_chat_history_turns(), 3); + assert_eq!(loaded.get_chatbot_history_turns(), 3); // A second save lands on the same singleton row, not a new one. Settings::try_new(SettingsParams { exam_kinds: kinds(&["quiz"]), diff --git a/src/lib.rs b/src/lib.rs index 8c50016..a1683ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,7 +42,7 @@ use crate::state::AppState; (name = "meta", description = "Liveness and service metadata"), (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"), (name = "auth", description = "Registration, login, session lifecycle"), - (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"), + (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"), (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"), (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`)"), (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 { .routes(routes!(server_time)) .nest("/ai", web::ai::routes()) .nest("/auth", web::auth::routes(&state.rate_limit)) - .nest("/chat", web::chat::routes()) + .nest("/chatbot", web::chatbot::routes()) .nest("/users", web::users::routes()) .nest("/notes", web::notes::routes()) .nest("/messages", web::messages::routes()) diff --git a/src/main.rs b/src/main.rs index 2d76d6c..573487d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,7 +30,7 @@ async fn main() -> anyhow::Result<()> { files_path: cfg.files_path.clone().into(), cookie_secure: cfg.cookie_secure, rate_limit: cfg.rate_limit.clone(), - chat_limit: UserRateLimiter::per_user_minute(cfg.chat_per_minute), + chatbot_limit: UserRateLimiter::per_user_minute(cfg.chatbot_per_minute), exam_presence: Default::default(), db_up, ai, diff --git a/src/rate_limit.rs b/src/rate_limit.rs index 0a6c868..c401145 100644 --- a/src/rate_limit.rs +++ b/src/rate_limit.rs @@ -95,13 +95,13 @@ impl Default for UserRateLimiter { /// The chatbot tier at its shipped default, for tests and any caller that /// has no [`crate::config::Config`] to hand. fn default() -> Self { - Self::per_user_minute(crate::config::DEFAULT_CHAT_RATE_LIMIT) + Self::per_user_minute(crate::config::DEFAULT_CHATBOT_RATE_LIMIT) } } impl UserRateLimiter { /// The chatbot tier: `max` messages per user per minute, from - /// `RATE_LIMIT_CHAT_PER_MINUTE`. `max == 0` disables it, like the IP tiers. + /// `RATE_LIMIT_CHATBOT_PER_MINUTE`. `max == 0` disables it, like the IP tiers. pub fn per_user_minute(max: u32) -> Self { Self::new(max, false) } @@ -346,7 +346,7 @@ mod tests { #[tokio::test(start_paused = true)] async fn users_get_independent_windows_that_reset() { let limiter = UserRateLimiter::default(); - for _ in 0..crate::config::DEFAULT_CHAT_RATE_LIMIT { + for _ in 0..crate::config::DEFAULT_CHATBOT_RATE_LIMIT { assert!(limiter.enforce_user("user:a").is_ok()); } assert!(matches!( diff --git a/src/state.rs b/src/state.rs index 66c7419..5850ca8 100644 --- a/src/state.rs +++ b/src/state.rs @@ -22,10 +22,10 @@ pub struct AppState { /// Read once by [`crate::build_router`] when the limiters are built. pub rate_limit: RateLimitConfig, /// Per-user chatbot limit (see [`UserRateLimiter`], built from - /// [`crate::config::Config::chat_per_minute`]). Not middleware: the + /// [`crate::config::Config::chatbot_per_minute`]). Not middleware: the /// caller is only known after `CurrentUser` has run, so handlers call it /// themselves. - pub chat_limit: UserRateLimiter, + pub chatbot_limit: UserRateLimiter, /// Who is inside which exam room right now (see [`ExamPresence`]). pub exam_presence: ExamPresence, /// Whether the database socket answered its last ping (see [`DbHealth`]). diff --git a/src/web/chat.rs b/src/web/chatbot.rs similarity index 80% rename from src/web/chat.rs rename to src/web/chatbot.rs index 9594967..08cfa2a 100644 --- a/src/web/chat.rs +++ b/src/web/chatbot.rs @@ -2,7 +2,7 @@ //! //! The backend owns everything except the answer itself — auth, the per-user //! rate limit, the thread, the payload format, and the last look at the reply -//! before it is stored. There are no intent or rule tables: the conversation is +//! before it is stored. There are no intent or rule tables: the thread is //! free-form on purpose. //! //! Sending is asynchronous by design. `POST .../messages` writes the user's @@ -30,12 +30,12 @@ use utoipa_axum::routes; use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; use crate::ai::{AiBridge, AiError}; -use crate::constant::{AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHAT_MESSAGE_LEN}; +use crate::constant::{AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN}; use crate::database::Database; -use crate::domain::chat_message::{ - ChatContent, ChatMessage, ChatMessageId, MessageRole, MessageStatus, +use crate::domain::chatbot_message::{ + ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus, }; -use crate::domain::conversation::{Conversation, ConversationId, ConversationTitle}; +use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; use crate::domain::settings::Settings; use crate::domain::user::UserId; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -45,8 +45,8 @@ use super::{CurrentUser, Page, PageParams, paginate}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() - .routes(routes!(create_conversation, list_conversations)) - .routes(routes!(rename_conversation, delete_conversation)) + .routes(routes!(create_thread, list_threads)) + .routes(routes!(rename_thread, delete_thread)) .routes(routes!(list_messages, send_message)) .routes(routes!(read_message)) .routes(routes!(stream_message)) @@ -57,10 +57,10 @@ pub fn routes() -> OpenApiRouter { const REPLY_CHUNKS: usize = 8; const MIN_CHUNK_CHARS: usize = 24; -// ---- conversations ---------------------------------------------------------- +// ---- threads ---------------------------------------------------------- #[derive(Deserialize, ToSchema)] -struct CreateConversation { +struct CreateChatbotThread { /// Optional thread name, up to 200 characters. Blank counts as absent — /// an untitled thread is normal (the UI labels it from its first turn). #[schema(example = "Fizik ödevi")] @@ -70,7 +70,7 @@ struct CreateConversation { /// One chatbot thread. `updated_at` moves on every turn, and the list is /// sorted by it, so the thread just written to is always first. #[derive(Serialize, ToSchema)] -struct ConversationResponse { +struct ChatbotThreadResponse { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] id: String, #[schema(example = "Fizik ödevi")] @@ -81,55 +81,55 @@ struct ConversationResponse { updated_at: i64, } -impl ConversationResponse { - fn new(conversation: &Conversation) -> Self { +impl ChatbotThreadResponse { + fn new(thread: &ChatbotThread) -> Self { Self { - id: conversation.get_id().key().to_string(), - title: conversation + id: thread.get_id().key().to_string(), + title: thread .get_title() .map(|title| title.as_str().to_string()), - created_at: conversation.get_created_at().as_millis(), - updated_at: conversation.get_updated_at().as_millis(), + created_at: thread.get_created_at().as_millis(), + updated_at: thread.get_updated_at().as_millis(), } } } /// Start a new chatbot thread, optionally named. Every authenticated role may /// chat, parents included. A user may keep up to the school's -/// `max_chat_conversations` threads; at the cap the request is refused (409) +/// `max_chatbot_threads` threads; at the cap the request is refused (409) /// until an old thread is deleted — the cap is storage protection, not a /// usage quota (that is the per-minute message limit). #[utoipa::path( post, - path = "/conversations", - tag = "chat", + path = "/threads", + tag = "chatbot", security(("session_cookie" = [])), - request_body = CreateConversation, + request_body = CreateChatbotThread, responses( - (status = 201, description = "The new thread", body = ConversationResponse), + (status = 201, description = "The new thread", body = ChatbotThreadResponse), (status = 400, description = "Invalid title", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 409, description = "At the school's conversation cap", body = ErrorResponse), + (status = 409, description = "At the school's thread cap", body = ErrorResponse), ), )] -async fn create_conversation( +async fn create_thread( State(st): State, CurrentUser(user): CurrentUser, - Json(req): Json, -) -> Result<(StatusCode, Json), AppError> { + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { // Blank is "untitled", not an error — same rule as a message's label. let title = match req.title.as_deref().map(str::trim).unwrap_or_default() { "" => None, - value => Some(ConversationTitle::try_new(value)?), + value => Some(ChatbotThreadTitle::try_new(value)?), }; // The cap is checked and the row written as one critical section in the // domain: counting here and creating after would over-admit under // concurrency (the database does not serialize a count against inserts). - let conversation = Conversation::create_capped(user.get_id(), title, &st.db).await?; + let thread = ChatbotThread::create_capped(user.get_id(), title, &st.db).await?; Ok(( StatusCode::CREATED, - Json(ConversationResponse::new(&conversation)), + Json(ChatbotThreadResponse::new(&thread)), )) } @@ -137,33 +137,33 @@ async fn create_conversation( /// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's. #[utoipa::path( get, - path = "/conversations", - tag = "chat", + path = "/threads", + tag = "chatbot", security(("session_cookie" = [])), params(PageParams), responses( - (status = 200, description = "A page of the caller's threads", body = Page), + (status = 200, description = "A page of the caller's threads", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] -async fn list_conversations( +async fn list_threads( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, -) -> Result>, AppError> { +) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let conversations = Conversation::list_for_user(user.get_id(), &st.db).await?; - let total = conversations.len() as i64; - let items = paginate(&conversations, limit, offset) + let threads = ChatbotThread::list_for_user(user.get_id(), &st.db).await?; + let total = threads.len() as i64; + let items = paginate(&threads, limit, offset) .iter() - .map(ConversationResponse::new) + .map(ChatbotThreadResponse::new) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } #[derive(Deserialize, ToSchema)] -struct RenameConversation { +struct RenameChatbotThread { /// The new name, up to 200 characters. `null` — or blank — clears it back /// to untitled, the same rule the create route applies. #[schema(example = "Fizik ödevi")] @@ -179,65 +179,65 @@ struct RenameConversation { /// title, and the AI service is never asked for one. #[utoipa::path( patch, - path = "/conversations/{id}", - tag = "chat", + path = "/threads/{id}", + tag = "chatbot", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Conversation id")), - request_body = RenameConversation, + params(("id" = String, Path, description = "ChatbotThread id")), + request_body = RenameChatbotThread, responses( - (status = 200, description = "The renamed thread", body = ConversationResponse), + (status = 200, description = "The renamed thread", body = ChatbotThreadResponse), (status = 400, description = "Invalid title", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), ), )] -async fn rename_conversation( +async fn rename_thread( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, - Json(req): Json, -) -> Result, AppError> { + Json(req): Json, +) -> Result, AppError> { let title = match req.title.as_deref().map(str::trim).unwrap_or_default() { "" => None, - value => Some(ConversationTitle::try_new(value)?), + value => Some(ChatbotThreadTitle::try_new(value)?), }; - let conversation = own_conversation(&id, user.get_id(), &st.db).await?; - let renamed = conversation.rename(title, &st.db).await?; - Ok(Json(ConversationResponse::new(&renamed))) + let thread = own_thread(&id, user.get_id(), &st.db).await?; + let renamed = thread.rename(title, &st.db).await?; + Ok(Json(ChatbotThreadResponse::new(&renamed))) } /// Delete a thread and every turn in it, permanently. Owner only; someone /// else's thread is a `404`, never a `403` (its existence is not leaked). #[utoipa::path( delete, - path = "/conversations/{id}", - tag = "chat", + path = "/threads/{id}", + tag = "chatbot", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Conversation id")), + params(("id" = String, Path, description = "ChatbotThread id")), responses( (status = 204, description = "Deleted, with its messages"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), ), )] -async fn delete_conversation( +async fn delete_thread( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result { - let conversation = own_conversation(&id, user.get_id(), &st.db).await?; - conversation.delete(&st.db).await?; + let thread = own_thread(&id, user.get_id(), &st.db).await?; + thread.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable /// from a missing one. -async fn own_conversation( +async fn own_thread( id: &str, user: &UserId, db: &Database, -) -> Result { - Conversation::read_for(&ConversationId::from_key(id), user, db) +) -> Result { + ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db) .await? .ok_or(AppError::NotFound) } @@ -245,15 +245,15 @@ async fn own_conversation( // ---- turns ------------------------------------------------------------------ #[derive(Deserialize, ToSchema)] -struct SendChatMessage { +struct SendChatbotMessage { /// What to ask. Required, and capped by the school's - /// `max_chat_message_len` (`GET /settings`). + /// `max_chatbot_message_len` (`GET /settings`). #[schema(example = "Newton'un ikinci yasasını açıklar mısın?")] content: String, } /// The receipt for an accepted turn. The answer is *not* here: it is being -/// fetched. Poll `GET /chat/conversations/{id}/messages/{mid}` or open its +/// fetched. Poll `GET /chatbot/threads/{id}/messages/{mid}` or open its /// `/stream`. #[derive(Serialize, ToSchema)] struct AcceptedResponse { @@ -268,11 +268,11 @@ struct AcceptedResponse { /// One turn. `content` is empty while `status` is `pending`; `error_code` is /// set only when `status` is `failed`. #[derive(Serialize, ToSchema)] -struct ChatMessageResponse { +struct ChatbotMessageResponse { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] id: String, #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] - conversation_id: String, + thread_id: String, /// `user` or `assistant`. #[schema(example = "assistant")] role: String, @@ -281,7 +281,7 @@ struct ChatMessageResponse { status: String, content: String, /// `true` when `content` is only the first part of what the assistant - /// answered — the rest was over the school's `max_chat_message_len` and was + /// answered — the rest was over the school's `max_chatbot_message_len` and was /// cut. Always `false` for a user turn and for a failed one. Show the user /// that the answer is incomplete; asking again shortens nothing, so the way /// out is a narrower question (or a bigger cap). @@ -299,11 +299,11 @@ struct ChatMessageResponse { completed_at: Option, } -impl ChatMessageResponse { - fn new(message: &ChatMessage) -> Self { +impl ChatbotMessageResponse { + fn new(message: &ChatbotMessage) -> Self { Self { id: message.get_id().key().to_string(), - conversation_id: message.get_conversation_id().key().to_string(), + thread_id: message.get_thread_id().key().to_string(), role: message.get_role().as_str().to_string(), status: message.get_status().as_str().to_string(), content: message.get_content().as_str().to_string(), @@ -318,12 +318,12 @@ impl ChatMessageResponse { /// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only. #[utoipa::path( get, - path = "/conversations/{id}/messages", - tag = "chat", + path = "/threads/{id}/messages", + tag = "chatbot", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Conversation id"), PageParams), + params(("id" = String, Path, description = "ChatbotThread id"), PageParams), responses( - (status = 200, description = "A page of the thread's turns", body = Page), + (status = 200, description = "A page of the thread's turns", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), @@ -334,14 +334,14 @@ async fn list_messages( CurrentUser(user): CurrentUser, Path(id): Path, Query(page): Query, -) -> Result>, AppError> { +) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let conversation = own_conversation(&id, user.get_id(), &st.db).await?; - let messages = ChatMessage::list_for_conversation(conversation.get_id(), &st.db).await?; + let thread = own_thread(&id, user.get_id(), &st.db).await?; + let messages = ChatbotMessage::list_for_thread(thread.get_id(), &st.db).await?; let total = messages.len() as i64; let items = paginate(&messages, limit, offset) .iter() - .map(ChatMessageResponse::new) + .map(ChatbotMessageResponse::new) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -358,14 +358,14 @@ async fn list_messages( /// the boot sweep repairs whatever a process death left behind. #[utoipa::path( post, - path = "/conversations/{id}/messages", - tag = "chat", + path = "/threads/{id}/messages", + tag = "chatbot", security(("session_cookie" = [])), - params(("id" = String, Path, description = "Conversation id")), - request_body = SendChatMessage, + params(("id" = String, Path, description = "ChatbotThread id")), + request_body = SendChatbotMessage, responses( (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse), - (status = 400, description = "Empty message, or longer than the school's `max_chat_message_len`", body = ErrorResponse), + (status = 400, description = "Empty message, or longer than the school's `max_chatbot_message_len`", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse), @@ -376,12 +376,12 @@ async fn send_message( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, - Json(req): Json, + Json(req): Json, ) -> Result { // Charged first: a rejected turn must cost nothing and leave no row. - st.chat_limit.enforce_user(user.get_id().key())?; + st.chatbot_limit.enforce_user(user.get_id().key())?; - let conversation = own_conversation(&id, user.get_id(), &st.db).await?; + let thread = own_thread(&id, user.get_id(), &st.db).await?; let settings = Settings::load(&st.db).await?; let reply_cap = content_cap(&settings); let length = req.content.chars().count(); @@ -406,23 +406,23 @@ async fn send_message( return Ok(unavailable("no AI service is connected right now")); } - let prompt = ChatMessage::append_user( - conversation.get_id(), + let prompt = ChatbotMessage::append_user( + thread.get_id(), user.get_id(), content.clone(), &st.db, ) .await?; let answer = - ChatMessage::append_pending_assistant(conversation.get_id(), user.get_id(), &st.db).await?; + ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?; // Never fatal: both rows are already written, and failing here would strand // the pending one with no task to answer it (it would only settle 300s // later, by projection). `updated_at` is the list's sort key — cosmetic // next to a turn that has been accepted. - if let Err(err) = conversation.touch(&st.db).await { + if let Err(err) = thread.touch(&st.db).await { tracing::warn!( - "could not stamp activity on conversation {}: {err}", - conversation.get_id().key() + "could not stamp activity on thread {}: {err}", + thread.get_id().key() ); } @@ -431,10 +431,10 @@ async fn send_message( tokio::spawn(answer_turn( bridge, st.db.clone(), - conversation.get_id().clone(), + thread.get_id().clone(), [prompt.get_id().clone(), answer.get_id().clone()], content.as_str().to_string(), - settings.get_chat_history_turns().max(0) as usize, + settings.get_chatbot_history_turns().max(0) as usize, reply_cap, )); @@ -451,7 +451,7 @@ async fn send_message( /// The school's per-message character cap, never above the domain's hard /// ceiling. Applied to what the user sends *and* to what the service answers. fn content_cap(settings: &Settings) -> usize { - (settings.get_max_chat_message_len().max(0) as usize).min(MAX_CHAT_MESSAGE_LEN) + (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN) } /// The AI-unavailable `503`. Built here rather than as an `AppError` variant: @@ -477,9 +477,9 @@ fn unavailable(message: &str) -> Response { async fn answer_turn( bridge: AiBridge, db: Database, - conversation: ConversationId, + thread: ChatbotThreadId, // The two rows this turn just wrote; both are excluded from the history. - fresh: [ChatMessageId; 2], + fresh: [ChatbotMessageId; 2], prompt: String, history_turns: usize, reply_cap: usize, @@ -488,7 +488,7 @@ async fn answer_turn( let settled = match fetch_reply( &bridge, &db, - &conversation, + &thread, &fresh, prompt, history_turns, @@ -496,16 +496,16 @@ async fn answer_turn( ) .await { - Ok((text, truncated)) => ChatMessage::complete(&answer_id, text, truncated, &db).await, + Ok((text, truncated)) => ChatbotMessage::complete(&answer_id, text, truncated, &db).await, Err(code) => { tracing::warn!("chat answer {} failed: {code}", answer_id.key()); - ChatMessage::fail(&answer_id, &code, &db).await + ChatbotMessage::fail(&answer_id, &code, &db).await } }; match settled { Ok(_) => {} // The row was no longer `pending`: the boot sweep or a stale-timeout - // already spoke for it, or the conversation was deleted mid-flight. + // already spoke for it, or the thread was deleted mid-flight. // Benign — the user is not waiting on this row any more. Err(AppError::NotFound) => { tracing::info!("chat answer {} was already settled", answer_id.key()); @@ -518,13 +518,13 @@ async fn answer_turn( async fn fetch_reply( bridge: &AiBridge, db: &Database, - conversation: &ConversationId, - fresh: &[ChatMessageId; 2], + thread: &ChatbotThreadId, + fresh: &[ChatbotMessageId; 2], prompt: String, history_turns: usize, reply_cap: usize, ) -> Result<(ChatContent, bool), String> { - let history = match history_for(db, conversation, fresh, history_turns).await { + let history = match history_for(db, thread, fresh, history_turns).await { Ok(history) => history, Err(err) => { tracing::warn!("could not load chat history: {err}"); @@ -571,21 +571,21 @@ async fn fetch_reply( Ok((content, truncated)) } -/// The tail of the conversation replayed to the service: oldest first, only +/// The tail of the thread replayed to the service: oldest first, only /// settled turns with text, and never the two rows this turn just wrote (the /// new prompt rides in `message`, the answer does not exist yet). async fn history_for( db: &Database, - conversation: &ConversationId, - fresh: &[ChatMessageId; 2], + thread: &ChatbotThreadId, + fresh: &[ChatbotMessageId; 2], turns: usize, ) -> Result, AppError> { // The query counts only settled rows with text, so a run of failed answers // makes the window reach *further back* instead of shrinking it — that is - // what "the last `chat_history_turns` settled turns" means. +2 so dropping + // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping // this turn's own two rows cannot shorten it either (only the user one can // match: the assistant row is still `pending`). - let tail = ChatMessage::list_settled_tail(conversation, turns.saturating_add(2), db).await?; + let tail = ChatbotMessage::list_settled_tail(thread, turns.saturating_add(2), db).await?; let mut history: Vec = tail .iter() .filter(|message| !fresh.contains(message.get_id())) @@ -629,15 +629,15 @@ fn failure_code(err: AiError) -> String { /// so the two can never disagree about a turn's state. #[utoipa::path( get, - path = "/conversations/{id}/messages/{mid}", - tag = "chat", + path = "/threads/{id}/messages/{mid}", + tag = "chatbot", security(("session_cookie" = [])), params( - ("id" = String, Path, description = "Conversation id"), + ("id" = String, Path, description = "ChatbotThread id"), ("mid" = String, Path, description = "Message id"), ), responses( - (status = 200, description = "The turn, in whatever state it is", body = ChatMessageResponse), + (status = 200, description = "The turn, in whatever state it is", body = ChatbotMessageResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), ), @@ -646,28 +646,28 @@ async fn read_message( State(st): State, CurrentUser(user): CurrentUser, Path((id, mid)): Path<(String, String)>, -) -> Result, AppError> { +) -> Result, AppError> { let message = own_message(&id, &mid, user.get_id(), &st.db).await?; - Ok(Json(ChatMessageResponse::new(&message))) + Ok(Json(ChatbotMessageResponse::new(&message))) } /// Read one turn only if the caller owns it *and* it belongs to the named -/// conversation — a mismatched pair is a `404`, like a foreign one. +/// thread — a mismatched pair is a `404`, like a foreign one. async fn own_message( - conversation: &str, + thread: &str, message: &str, user: &UserId, db: &Database, -) -> Result { - ChatMessage::read_for(&ChatMessageId::from_key(message), user, db) +) -> Result { + ChatbotMessage::read_for(&ChatbotMessageId::from_key(message), user, db) .await? - .filter(|message| message.get_conversation_id().key() == conversation) + .filter(|message| message.get_thread_id().key() == thread) .ok_or(AppError::NotFound) } /// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a /// single `done` carrying the finished message, or one `error`. The stream -/// closes after `done`/`error` — one stream per turn, not per conversation. +/// closes after `done`/`error` — one stream per turn, not per thread. /// /// Works whatever state the turn is in when the stream opens: an answer that /// already landed replays as `delta`s and a `done` straight away, so a client @@ -675,11 +675,11 @@ async fn own_message( /// (cookies ride along on same-site / credentialed requests). #[utoipa::path( get, - path = "/conversations/{id}/messages/{mid}/stream", - tag = "chat", + path = "/threads/{id}/messages/{mid}/stream", + tag = "chatbot", security(("session_cookie" = [])), params( - ("id" = String, Path, description = "Conversation id"), + ("id" = String, Path, description = "ChatbotThread id"), ("mid" = String, Path, description = "Message id"), ), responses( @@ -699,7 +699,7 @@ async fn stream_message( let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2); let (message_id, user_id, db) = ( - ChatMessageId::from_key(&mid), + ChatbotMessageId::from_key(&mid), user.get_id().clone(), st.db.clone(), ); @@ -719,7 +719,7 @@ async fn stream_message( _ = ticker.tick() => {} _ = tx.closed() => return, } - let message = match ChatMessage::read_for(&message_id, &user_id, &db).await { + let message = match ChatbotMessage::read_for(&message_id, &user_id, &db).await { Ok(Some(message)) => message, // Deleted mid-stream (the thread went away) — say so and stop. Ok(None) => { @@ -744,7 +744,7 @@ async fn stream_message( return; } } - let done = json!({ "message": ChatMessageResponse::new(&message) }); + let done = json!({ "message": ChatbotMessageResponse::new(&message) }); let _ = send(&tx, "done", done).await; return; } @@ -845,43 +845,43 @@ mod tests { // shrink it: filtering a fixed-size tail after the fact handed the // service a handful of unanswered prompts and nothing older. let db = crate::database::init_mem().await.unwrap(); - let conversation = ConversationId::from_key("c"); + let thread = ChatbotThreadId::from_key("c"); let user = UserId::from_key("u"); let say = |text: String| ChatContent::try_new(&text).unwrap(); for turn in 0..10 { - ChatMessage::append_user(&conversation, &user, say(format!("soru {turn}")), &db) + ChatbotMessage::append_user(&thread, &user, say(format!("soru {turn}")), &db) .await .unwrap(); - let answer = ChatMessage::append_pending_assistant(&conversation, &user, &db) + let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db) .await .unwrap(); - ChatMessage::complete(answer.get_id(), say(format!("cevap {turn}")), false, &db) + ChatbotMessage::complete(answer.get_id(), say(format!("cevap {turn}")), false, &db) .await .unwrap(); } // Five turns in a row whose answer never landed. for turn in 0..5 { - ChatMessage::append_user(&conversation, &user, say(format!("kayıp {turn}")), &db) + ChatbotMessage::append_user(&thread, &user, say(format!("kayıp {turn}")), &db) .await .unwrap(); - let answer = ChatMessage::append_pending_assistant(&conversation, &user, &db) + let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db) .await .unwrap(); - ChatMessage::fail(answer.get_id(), "timed_out", &db) + ChatbotMessage::fail(answer.get_id(), "timed_out", &db) .await .unwrap(); } // And this turn's own two rows, which never belong in the history. - let prompt = ChatMessage::append_user(&conversation, &user, say("yeni".into()), &db) + let prompt = ChatbotMessage::append_user(&thread, &user, say("yeni".into()), &db) .await .unwrap(); - let pending = ChatMessage::append_pending_assistant(&conversation, &user, &db) + let pending = ChatbotMessage::append_pending_assistant(&thread, &user, &db) .await .unwrap(); let fresh = [prompt.get_id().clone(), pending.get_id().clone()]; - let history = history_for(&db, &conversation, &fresh, 6).await.unwrap(); + let history = history_for(&db, &thread, &fresh, 6).await.unwrap(); let texts: Vec<&str> = history.iter().map(|turn| turn.content.as_str()).collect(); assert_eq!( texts, diff --git a/src/web/mod.rs b/src/web/mod.rs index 5f82d47..bd87776 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -7,7 +7,7 @@ pub mod ai; pub mod appointments; pub mod attendance; pub mod auth; -pub mod chat; +pub mod chatbot; pub mod courses; pub mod events; pub mod exam_ws; diff --git a/src/web/settings.rs b/src/web/settings.rs index 5a3032d..1f5a2f5 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -65,15 +65,15 @@ struct SettingsResponse { /// Per-file size limit for note uploads, in bytes. #[schema(example = 5_242_880)] max_file_bytes: i64, - /// How many prior turns of a conversation the chatbot is given as context. + /// How many prior turns of a thread the chatbot is given as context. #[schema(example = 10)] - chat_history_turns: i64, - /// How many chatbot conversations one user may keep. + chatbot_history_turns: i64, + /// How many chatbot threads one user may keep. #[schema(example = 50)] - max_chat_conversations: i64, + max_chatbot_threads: i64, /// Character limit on one chat message. #[schema(example = 4000)] - max_chat_message_len: i64, + max_chatbot_message_len: i64, } impl SettingsResponse { @@ -97,9 +97,9 @@ impl SettingsResponse { }) .collect(), max_file_bytes: settings.get_max_file_bytes(), - chat_history_turns: settings.get_chat_history_turns(), - max_chat_conversations: settings.get_max_chat_conversations(), - max_chat_message_len: settings.get_max_chat_message_len(), + chatbot_history_turns: settings.get_chatbot_history_turns(), + max_chatbot_threads: settings.get_max_chatbot_threads(), + max_chatbot_message_len: settings.get_max_chatbot_message_len(), } } } @@ -119,18 +119,18 @@ struct UpdateSettings { /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap. #[schema(example = 5_242_880)] max_file_bytes: Option, - /// How many prior turns of a conversation the chatbot is given as context, + /// How many prior turns of a thread the chatbot is given as context, /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens. #[schema(example = 10)] - chat_history_turns: Option, - /// How many chatbot conversations one user may keep, `1`–`500`. At the cap - /// the user deletes an old conversation before starting a new one. + chatbot_history_turns: Option, + /// How many chatbot threads one user may keep, `1`–`500`. At the cap + /// the user deletes an old thread before starting a new one. #[schema(example = 50)] - max_chat_conversations: Option, + max_chatbot_threads: Option, /// Character limit on one chat message, `100`–`8000`. The ceiling is a /// server hard cap. #[schema(example = 4000)] - max_chat_message_len: Option, + max_chatbot_message_len: Option, } /// The school's current policy. Any authenticated user — clients need it to @@ -239,13 +239,13 @@ async fn update_settings( params.attendance_statuses = attendance_statuses; params.grade_bands = grade_bands; params.max_file_bytes = req.max_file_bytes.unwrap_or(params.max_file_bytes); - params.chat_history_turns = req.chat_history_turns.unwrap_or(params.chat_history_turns); - params.max_chat_conversations = req - .max_chat_conversations - .unwrap_or(params.max_chat_conversations); - params.max_chat_message_len = req - .max_chat_message_len - .unwrap_or(params.max_chat_message_len); + params.chatbot_history_turns = req.chatbot_history_turns.unwrap_or(params.chatbot_history_turns); + params.max_chatbot_threads = req + .max_chatbot_threads + .unwrap_or(params.max_chatbot_threads); + params.max_chatbot_message_len = req + .max_chatbot_message_len + .unwrap_or(params.max_chatbot_message_len); let settings = Settings::try_new(params)?; if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 277b2ff..4512c03 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -805,7 +805,7 @@ async fn fetch_certificate(ai: Option) -> (axum::http::StatusCode, Val files_path: std::env::temp_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai, @@ -924,7 +924,7 @@ fn payloads_are_opaque(v: Value) -> Value { use axum::Router; use axum::http::StatusCode; -use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHAT_MESSAGE_LEN}; +use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHATBOT_MESSAGE_LEN}; use hezarfen_backend::database::Database; use surrealdb::types::RecordId; @@ -938,7 +938,7 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) { files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai: Some(bridge.clone()), @@ -952,7 +952,7 @@ async fn chat_user(app: &Router, name: &str) -> (String, String) { let res = common::send( app, "POST", - "/chat/conversations", + "/chatbot/threads", Some(&cookie), Some(json!({})), ) @@ -963,11 +963,11 @@ async fn chat_user(app: &Router, name: &str) -> (String, String) { } /// Ask one question (asserts `202`) and return the reserved assistant row's id. -async fn ask(app: &Router, cookie: &str, conversation: &str, text: &str) -> String { +async fn ask(app: &Router, cookie: &str, thread: &str, text: &str) -> String { let res = common::send( app, "POST", - &format!("/chat/conversations/{conversation}/messages"), + &format!("/chatbot/threads/{thread}/messages"), Some(cookie), Some(json!({ "content": text })), ) @@ -982,12 +982,12 @@ async fn ask(app: &Router, cookie: &str, conversation: &str, text: &str) -> Stri /// Poll a turn until it leaves `pending`. Bounded polling rather than a sleep /// sized to the answering task: the round trip settles when it settles. -async fn settled(app: &Router, cookie: &str, conversation: &str, mid: &str) -> Value { +async fn settled(app: &Router, cookie: &str, thread: &str, mid: &str) -> Value { for _ in 0..500 { let res = common::send( app, "GET", - &format!("/chat/conversations/{conversation}/messages/{mid}"), + &format!("/chatbot/threads/{thread}/messages/{mid}"), Some(cookie), None, ) @@ -1012,10 +1012,10 @@ async fn a_chat_turn_settles_complete_with_the_services_text() { .await; await_workers(&bridge, 1).await; let (app, _db) = chat_app(&bridge).await; - let (cookie, conversation) = chat_user(&app, "ali").await; + let (cookie, thread) = chat_user(&app, "ali").await; - let mid = ask(&app, &cookie, &conversation, "ikinci yasa nedir?").await; - let turn = settled(&app, &cookie, &conversation, &mid).await; + let mid = ask(&app, &cookie, &thread, "ikinci yasa nedir?").await; + let turn = settled(&app, &cookie, &thread, &mid).await; assert_eq!(turn["status"], "complete", "{turn}"); assert_eq!(turn["content"], "F = ma"); assert_eq!(turn["role"], "assistant"); @@ -1050,28 +1050,28 @@ async fn the_history_a_service_receives_is_oldest_first_without_the_new_turn() { .await; await_workers(&bridge, 1).await; let (app, db) = chat_app(&bridge).await; - let (cookie, conversation) = chat_user(&app, "ali").await; + let (cookie, thread) = chat_user(&app, "ali").await; let user = common::me_id(&app, &cookie).await; - let first = ask(&app, &cookie, &conversation, "birinci soru").await; + let first = ask(&app, &cookie, &thread, "birinci soru").await; assert_eq!( - settled(&app, &cookie, &conversation, &first).await["status"], + settled(&app, &cookie, &thread, &first).await["status"], "complete" ); db.query( - "CREATE chat_message:h3 SET conversation_id = $conv, user_id = $usr, role = 'assistant', + "CREATE chatbot_message:h3 SET thread_id = $conv, user_id = $usr, role = 'assistant', content = '', status = 'pending', created_at = 1002;", ) - .bind(("conv", RecordId::new("conversation", conversation.as_str()))) + .bind(("conv", RecordId::new("chatbot_thread", thread.as_str()))) .bind(("usr", RecordId::new("user", user.as_str()))) .await .expect("seed history") .check() .expect("seed history"); - let mid = ask(&app, &cookie, &conversation, "ikinci soru").await; - let turn = settled(&app, &cookie, &conversation, &mid).await; + let mid = ask(&app, &cookie, &thread, "ikinci soru").await; + let turn = settled(&app, &cookie, &thread, &mid).await; assert_eq!(turn["status"], "complete", "{turn}"); let seen = service.seen(); @@ -1103,10 +1103,10 @@ async fn a_refused_chat_turn_carries_the_services_own_error_code() { .await; await_workers(&bridge, 1).await; let (app, _db) = chat_app(&bridge).await; - let (cookie, conversation) = chat_user(&app, "ali").await; + let (cookie, thread) = chat_user(&app, "ali").await; - let mid = ask(&app, &cookie, &conversation, "bir soru").await; - let turn = settled(&app, &cookie, &conversation, &mid).await; + let mid = ask(&app, &cookie, &thread, "bir soru").await; + let turn = settled(&app, &cookie, &thread, &mid).await; assert_eq!(turn["status"], "failed", "{turn}"); assert_eq!(turn["error_code"], "quota_exhausted"); 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() { // truncated (a clipped answer still helps), and on a character boundary — // a byte-wise clip of a multi-byte script would render as garbage. The cut // is flagged, so the UI never passes a clipped answer off as the whole one. - let cap = DEFAULT_MAX_CHAT_MESSAGE_LEN as usize; + let cap = DEFAULT_MAX_CHATBOT_MESSAGE_LEN as usize; let bridge = bridge().await; let _service = connect_service( &bridge, @@ -1130,10 +1130,10 @@ async fn an_over_long_chat_answer_is_clipped_rather_than_failed() { .await; await_workers(&bridge, 1).await; let (app, _db) = chat_app(&bridge).await; - let (cookie, conversation) = chat_user(&app, "ali").await; + let (cookie, thread) = chat_user(&app, "ali").await; - let mid = ask(&app, &cookie, &conversation, "uzun cevap ver").await; - let turn = settled(&app, &cookie, &conversation, &mid).await; + let mid = ask(&app, &cookie, &thread, "uzun cevap ver").await; + let turn = settled(&app, &cookie, &thread, &mid).await; assert_eq!(turn["status"], "complete", "{turn}"); let text = turn["content"].as_str().expect("content"); assert_eq!(text.chars().count(), cap); @@ -1154,10 +1154,10 @@ async fn a_blank_chat_answer_fails_as_empty_reply() { .await; await_workers(&bridge, 1).await; let (app, _db) = chat_app(&bridge).await; - let (cookie, conversation) = chat_user(&app, "ali").await; + let (cookie, thread) = chat_user(&app, "ali").await; - let mid = ask(&app, &cookie, &conversation, "bir soru").await; - let turn = settled(&app, &cookie, &conversation, &mid).await; + let mid = ask(&app, &cookie, &thread, "bir soru").await; + let turn = settled(&app, &cookie, &thread, &mid).await; assert_eq!(turn["status"], "failed", "{turn}"); assert_eq!(turn["error_code"], "empty_reply"); } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 4560da5..fc13245 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -47,7 +47,7 @@ pub async fn app_and_db() -> (Router, Database) { // Off, so suites hammering the API never trip a limit; the dedicated // `rate_limit` test binary opts into tight configs on purpose. rate_limit: RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai: None, diff --git a/tests/e2e.rs b/tests/e2e.rs index 65f5436..7487cd2 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -27,7 +27,7 @@ async fn spawn_server_with_ai(ai: Option) -> (St // Every request here comes from 127.0.0.1, so per-IP limits would // meter the whole suite as one client. Off; `rate_limit.rs` covers it. rate_limit: RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai, @@ -1936,7 +1936,7 @@ async fn chat_service(text: &str) -> ChatService { /// Open a thread and ask one question. Returns (thread id, reserved answer id). async fn ask(client: &Client, base: &str) -> (String, String) { let thread: Value = client - .post(format!("{base}/chat/conversations")) + .post(format!("{base}/chatbot/threads")) .json(&json!({ "title": "Fizik" })) .send() .await @@ -1944,10 +1944,10 @@ async fn ask(client: &Client, base: &str) -> (String, String) { .json() .await .unwrap(); - let conversation = thread["id"].as_str().expect("thread id").to_string(); + let thread = thread["id"].as_str().expect("thread id").to_string(); let res = client - .post(format!("{base}/chat/conversations/{conversation}/messages")) + .post(format!("{base}/chatbot/threads/{thread}/messages")) .json(&json!({ "content": "ikinci yasa nedir?" })) .send() .await @@ -1959,7 +1959,7 @@ async fn ask(client: &Client, base: &str) -> (String, String) { .as_str() .expect("message id") .to_string(); - (conversation, mid) + (thread, mid) } /// 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) /// must reach the same conclusion about the very same turn. #[tokio::test] async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() { - let cap = hezarfen_backend::constant::DEFAULT_MAX_CHAT_MESSAGE_LEN as usize; + let cap = hezarfen_backend::constant::DEFAULT_MAX_CHATBOT_MESSAGE_LEN as usize; let service = chat_service(&"é".repeat(cap + 500)).await; let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await; let ali = client(); register(&ali, &base, "ali").await; login(&ali, &base, "ali").await; - let (conversation, mid) = ask(&ali, &base).await; + let (thread, mid) = ask(&ali, &base).await; let mut res = ali .get(format!( - "{base}/chat/conversations/{conversation}/messages/{mid}/stream" + "{base}/chatbot/threads/{thread}/messages/{mid}/stream" )) .send() .await @@ -2071,7 +2071,7 @@ async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() { // The same row, read the other way: identical verdict, field for field. let polled: Value = ali .get(format!( - "{base}/chat/conversations/{conversation}/messages/{mid}" + "{base}/chatbot/threads/{thread}/messages/{mid}" )) .send() .await @@ -2091,13 +2091,13 @@ async fn chat_stream_delivers_deltas_then_done_over_http() { register(&ali, &base, "ali").await; login(&ali, &base, "ali").await; - let (conversation, mid) = ask(&ali, &base).await; + let (thread, mid) = ask(&ali, &base).await; // The client opens the stream while the turn is still in flight; it stays // open until the answer lands, then closes after `done`. let mut res = ali .get(format!( - "{base}/chat/conversations/{conversation}/messages/{mid}/stream" + "{base}/chatbot/threads/{thread}/messages/{mid}/stream" )) .send() .await @@ -2137,7 +2137,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() { register(&ali, &base, "ali").await; login(&ali, &base, "ali").await; - let (conversation, mid) = ask(&ali, &base).await; + let (thread, mid) = ask(&ali, &base).await; // Wait — by polling, never by sleeping — until the turn has settled, so the // stream below opens strictly after the answer landed. @@ -2145,7 +2145,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() { for _ in 0..500 { let turn: Value = ali .get(format!( - "{base}/chat/conversations/{conversation}/messages/{mid}" + "{base}/chatbot/threads/{thread}/messages/{mid}" )) .send() .await @@ -2164,7 +2164,7 @@ async fn chat_stream_replays_an_answer_that_already_landed() { let mut res = ali .get(format!( - "{base}/chat/conversations/{conversation}/messages/{mid}/stream" + "{base}/chatbot/threads/{thread}/messages/{mid}/stream" )) .send() .await diff --git a/tests/integration.rs b/tests/integration.rs index 00e6f8e..0d468e5 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -9,8 +9,8 @@ use common::{ app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session, create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll, }; -use hezarfen_backend::domain::chat_message::ChatMessage; -use hezarfen_backend::domain::conversation::ConversationId; +use hezarfen_backend::domain::chatbot_message::ChatbotMessage; +use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; use hezarfen_backend::domain::session::Session; @@ -5224,7 +5224,7 @@ async fn session_cookie_secure_attribute_follows_config() { files_path: common::files_dir(), cookie_secure: true, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai: None, @@ -5263,7 +5263,7 @@ async fn db_down_refuses_before_touching_the_database() { files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: db_up.clone(), ai: None, @@ -14616,10 +14616,10 @@ async fn chat_app(ai: Option) -> (axum::Router, Database) { } /// The same, with an explicit per-user chat tier — what -/// `RATE_LIMIT_CHAT_PER_MINUTE` configures in production. +/// `RATE_LIMIT_CHATBOT_PER_MINUTE` configures in production. async fn chat_app_limited( ai: Option, - chat_limit: hezarfen_backend::rate_limit::UserRateLimiter, + chatbot_limit: hezarfen_backend::rate_limit::UserRateLimiter, ) -> (axum::Router, Database) { let db = database::init_mem().await.expect("in-memory db"); let app = build_router(AppState { @@ -14627,7 +14627,7 @@ async fn chat_app_limited( files_path: common::files_dir(), cookie_secure: false, rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), - chat_limit, + chatbot_limit, exam_presence: Default::default(), db_up: Default::default(), ai, @@ -14635,17 +14635,17 @@ async fn chat_app_limited( (app, db) } -/// How many `conversation` and `chat_message` rows exist, anywhere. +/// How many `thread` and `chatbot_message` rows exist, anywhere. async fn chat_rows(db: &Database) -> (usize, usize) { let mut res = db - .query("SELECT VALUE id FROM conversation; SELECT VALUE id FROM chat_message;") + .query("SELECT VALUE id FROM chatbot_thread; SELECT VALUE id FROM chatbot_message;") .await .expect("count query") .check() .expect("count check"); - let conversations: Vec = res.take(0).expect("conversation ids"); - let messages: Vec = res.take(1).expect("chat_message ids"); - (conversations.len(), messages.len()) + let threads: Vec = res.take(0).expect("thread ids"); + let messages: Vec = res.take(1).expect("chatbot_message ids"); + (threads.len(), messages.len()) } /// Open a thread (asserts 201) and return its id. @@ -14653,7 +14653,7 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String { let res = send( app, "POST", - "/chat/conversations", + "/chatbot/threads", Some(cookie), Some(json!({})), ) @@ -14665,13 +14665,13 @@ async fn new_thread(app: &axum::Router, cookie: &str) -> String { async fn post_turn( app: &axum::Router, cookie: &str, - conversation: &str, + thread: &str, content: &str, ) -> common::Res { send( app, "POST", - &format!("/chat/conversations/{conversation}/messages"), + &format!("/chatbot/threads/{thread}/messages"), Some(cookie), Some(json!({ "content": content })), ) @@ -14683,13 +14683,13 @@ async fn post_turn( async fn open_stream( app: &axum::Router, cookie: &str, - conversation: &str, + thread: &str, mid: &str, ) -> StatusCode { let request = Request::builder() .method("GET") .uri(format!( - "/chat/conversations/{conversation}/messages/{mid}/stream" + "/chatbot/threads/{thread}/messages/{mid}/stream" )) .header("cookie", cookie) .body(Body::empty()) @@ -14706,7 +14706,7 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() { let res = send( &app, "POST", - "/chat/conversations", + "/chatbot/threads", Some(&cookie), Some(json!({ "title": "Fizik" })), ) @@ -14715,11 +14715,11 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() { assert_eq!(res.body["title"], "Fizik"); assert!(res.body["created_at"].is_i64(), "{}", res.body); assert!(res.body["updated_at"].is_i64(), "{}", res.body); - let conversation = id_of(&res.body); + let thread = id_of(&res.body); // The receipt: the reserved row's id and nothing else. The answer is not // here — it is being fetched. - let res = post_turn(&app, &cookie, &conversation, "ikinci yasa nedir?").await; + let res = post_turn(&app, &cookie, &thread, "ikinci yasa nedir?").await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); assert_eq!(res.body["status"], "pending"); 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() { let res = send( &app, "GET", - &format!("/chat/conversations/{conversation}/messages/{mid}"), + &format!("/chatbot/threads/{thread}/messages/{mid}"), Some(&cookie), None, ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["conversation_id"], conversation); + assert_eq!(res.body["thread_id"], thread); assert_eq!(res.body["role"], "assistant"); assert_eq!(res.body["status"], "pending"); assert_eq!(res.body["content"], ""); @@ -14756,7 +14756,7 @@ async fn chat_send_is_accepted_with_a_reserved_assistant_row() { let res = send( &app, "GET", - &format!("/chat/conversations/{conversation}/messages"), + &format!("/chatbot/threads/{thread}/messages"), Some(&cookie), None, ) @@ -14788,9 +14788,9 @@ async fn chat_send_without_a_service_is_503_and_writes_nothing() { for ai in [None, Some(idle)] { let (app, db) = chat_app(ai).await; let cookie = login(&app, "ali").await; - let conversation = new_thread(&app, &cookie).await; + let thread = new_thread(&app, &cookie).await; - let res = post_turn(&app, &cookie, &conversation, "bir soru").await; + let res = post_turn(&app, &cookie, &thread, "bir soru").await; assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); assert!( res.body["error"] @@ -14826,8 +14826,8 @@ async fn chat_lists_are_paged() { // list. Order is compared element for element: the id tie-break makes it // deterministic even for the two rows one POST writes in a millisecond. for (uri, expected) in [ - ("/chat/conversations".to_string(), 3), - (format!("/chat/conversations/{}/messages", threads[0]), 6), + ("/chatbot/threads".to_string(), 3), + (format!("/chatbot/threads/{}/messages", threads[0]), 6), ] { let res = send( &app, @@ -14895,8 +14895,8 @@ async fn chat_threads_are_invisible_to_everyone_else() { let ai = chat_bridge().await; let (app, db) = chat_app(Some(ai.bridge.clone())).await; let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; - let res = post_turn(&app, &ali, &conversation, "bir soru").await; + let thread = new_thread(&app, &ali).await; + let res = post_turn(&app, &ali, &thread, "bir soru").await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); let mid = res.body["message_id"].as_str().unwrap().to_string(); @@ -14909,21 +14909,21 @@ async fn chat_threads_are_invisible_to_everyone_else() { for (method, uri) in [ ( "GET", - format!("/chat/conversations/{conversation}/messages"), + format!("/chatbot/threads/{thread}/messages"), ), ( "GET", - format!("/chat/conversations/{conversation}/messages/{mid}"), + format!("/chatbot/threads/{thread}/messages/{mid}"), ), ( "GET", - format!("/chat/conversations/{conversation}/messages/{mid}/stream"), + format!("/chatbot/threads/{thread}/messages/{mid}/stream"), ), - ("DELETE", format!("/chat/conversations/{conversation}")), - ("PATCH", format!("/chat/conversations/{conversation}")), + ("DELETE", format!("/chatbot/threads/{thread}")), + ("PATCH", format!("/chatbot/threads/{thread}")), ( "POST", - format!("/chat/conversations/{conversation}/messages"), + format!("/chatbot/threads/{thread}/messages"), ), ] { let body = match method { @@ -14935,13 +14935,13 @@ async fn chat_threads_are_invisible_to_everyone_else() { assert_eq!(res.status, StatusCode::NOT_FOUND, "{name} {method} {uri}"); } // Nor does someone else's thread show up in their own list. - let res = send(&app, "GET", "/chat/conversations", Some(&other), None).await; + let res = send(&app, "GET", "/chatbot/threads", Some(&other), None).await; assert!(common::items(&res.body).is_empty(), "{}", res.body); } // And the owner still has everything, untouched. assert_eq!(chat_rows(&db).await, (1, 2)); - let res = send(&app, "GET", "/chat/conversations", Some(&ali), None).await; + let res = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; assert_eq!(common::items(&res.body).len(), 1, "{}", res.body); } @@ -14954,7 +14954,7 @@ async fn chat_thread_count_is_capped_by_the_school() { "PATCH", "/settings", Some(&manager), - Some(json!({ "max_chat_conversations": 1 })), + Some(json!({ "max_chatbot_threads": 1 })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -14964,7 +14964,7 @@ async fn chat_thread_count_is_capped_by_the_school() { let res = send( &app, "POST", - "/chat/conversations", + "/chatbot/threads", Some(&ali), Some(json!({})), ) @@ -14979,7 +14979,7 @@ async fn chat_thread_count_is_capped_by_the_school() { let res = send( &app, "DELETE", - &format!("/chat/conversations/{first}"), + &format!("/chatbot/threads/{first}"), Some(&ali), None, ) @@ -15004,7 +15004,7 @@ async fn concurrent_thread_creation_never_passes_the_cap() { "PATCH", "/settings", Some(&manager), - Some(json!({ "max_chat_conversations": CAP })), + Some(json!({ "max_chatbot_threads": CAP })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -15021,7 +15021,7 @@ async fn concurrent_thread_creation_never_passes_the_cap() { send( &app, "POST", - "/chat/conversations", + "/chatbot/threads", Some(&cookie), Some(json!({})), ) @@ -15054,18 +15054,18 @@ async fn chat_turn_stamps_thread_activity() { let ai = chat_bridge().await; let (app, _db) = chat_app(Some(ai.bridge.clone())).await; let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; - let before = send(&app, "GET", "/chat/conversations", Some(&ali), None).await; + let thread = new_thread(&app, &ali).await; + let before = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; let opened = common::items(&before.body)[0]["updated_at"] .as_i64() .unwrap(); // The stamp is in whole milliseconds; make sure the clock has moved. tokio::time::sleep(std::time::Duration::from_millis(5)).await; - let res = post_turn(&app, &ali, &conversation, "bir soru").await; + let res = post_turn(&app, &ali, &thread, "bir soru").await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); - let after = send(&app, "GET", "/chat/conversations", Some(&ali), None).await; + let after = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; let stamped = common::items(&after.body)[0]["updated_at"] .as_i64() .unwrap(); @@ -15083,11 +15083,11 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() { // count below is not drowned in the QUIC service's task churn. let (app, db) = chat_app(None).await; let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; + let thread = new_thread(&app, &ali).await; let me = send(&app, "GET", "/auth/me", Some(&ali), None).await; let user = UserId::from_key(me.body["id"].as_str().unwrap()); let pending = - ChatMessage::append_pending_assistant(&ConversationId::from_key(&conversation), &user, &db) + ChatbotMessage::append_pending_assistant(&ChatbotThreadId::from_key(&thread), &user, &db) .await .expect("reserve an assistant row"); let mid = pending.get_id().key().to_string(); @@ -15108,7 +15108,7 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() { let request = Request::builder() .method("GET") .uri(format!( - "/chat/conversations/{conversation}/messages/{mid}/stream" + "/chatbot/threads/{thread}/messages/{mid}/stream" )) .header("cookie", &ali) .body(Body::empty()) @@ -15140,25 +15140,25 @@ async fn chat_content_is_required_and_capped_by_the_school() { "PATCH", "/settings", Some(&manager), - Some(json!({ "max_chat_message_len": 100 })), + Some(json!({ "max_chatbot_message_len": 100 })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; + let thread = new_thread(&app, &ali).await; for empty in ["", " ", "\n\t"] { - let res = post_turn(&app, &ali, &conversation, empty).await; + let res = post_turn(&app, &ali, &thread, empty).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{empty:?} accepted"); } // Counted in characters, not bytes: 101 multi-byte characters is 101. - let res = post_turn(&app, &ali, &conversation, &"é".repeat(101)).await; + let res = post_turn(&app, &ali, &thread, &"é".repeat(101)).await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); // Nothing rejected was written. assert_eq!(chat_rows(&db).await, (1, 0)); - let res = post_turn(&app, &ali, &conversation, &"é".repeat(100)).await; + let res = post_turn(&app, &ali, &thread, &"é".repeat(100)).await; assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); } @@ -15170,10 +15170,10 @@ async fn chat_rate_limit_refuses_before_anything_is_written() { let ai = chat_bridge().await; let (app, db) = chat_app(Some(ai.bridge.clone())).await; let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; + let thread = new_thread(&app, &ali).await; for n in 1..=20 { - let res = post_turn(&app, &ali, &conversation, &format!("soru {n}")).await; + let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await; assert_eq!(res.status, StatusCode::ACCEPTED, "turn {n}: {}", res.body); } let before = chat_rows(&db).await; @@ -15182,7 +15182,7 @@ async fn chat_rate_limit_refuses_before_anything_is_written() { let (status, headers, _) = common::send_raw( &app, "POST", - &format!("/chat/conversations/{conversation}/messages"), + &format!("/chatbot/threads/{thread}/messages"), Some(&ali), Some("application/json"), json!({ "content": "yirmi birinci" }) @@ -15222,16 +15222,16 @@ async fn every_role_may_chat_parents_included() { ("patron", "admin"), ] { let cookie = login_as(&app, &db, name, role).await; - let conversation = new_thread(&app, &cookie).await; + let thread = new_thread(&app, &cookie).await; - let res = post_turn(&app, &cookie, &conversation, "bir soru").await; + let res = post_turn(&app, &cookie, &thread, "bir soru").await; assert_eq!(res.status, StatusCode::ACCEPTED, "{role}: {}", res.body); let mid = res.body["message_id"].as_str().unwrap().to_string(); let res = send( &app, "GET", - &format!("/chat/conversations/{conversation}/messages/{mid}"), + &format!("/chatbot/threads/{thread}/messages/{mid}"), Some(&cookie), None, ) @@ -15241,7 +15241,7 @@ async fn every_role_may_chat_parents_included() { let res = send( &app, "GET", - &format!("/chat/conversations/{conversation}/messages"), + &format!("/chatbot/threads/{thread}/messages"), Some(&cookie), None, ) @@ -15250,19 +15250,19 @@ async fn every_role_may_chat_parents_included() { assert_eq!(common::items(&res.body).len(), 2, "{role}: {}", res.body); assert_eq!( - open_stream(&app, &cookie, &conversation, &mid).await, + open_stream(&app, &cookie, &thread, &mid).await, StatusCode::OK, "{role} may open the stream" ); - let res = send(&app, "GET", "/chat/conversations", Some(&cookie), None).await; + let res = send(&app, "GET", "/chatbot/threads", Some(&cookie), None).await; assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body); assert_eq!(common::items(&res.body).len(), 1, "{role}: {}", res.body); let res = send( &app, "DELETE", - &format!("/chat/conversations/{conversation}"), + &format!("/chatbot/threads/{thread}"), Some(&cookie), None, ) @@ -15284,7 +15284,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { tokio::time::sleep(std::time::Duration::from_millis(5)).await; let second = new_thread(&app, &ali).await; - let listed = send(&app, "GET", "/chat/conversations", Some(&ali), None).await; + let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; let items = common::items(&listed.body); assert_eq!(id_of(&items[0]), second, "newest activity first"); let before = items[1]["updated_at"].as_i64().expect("updated_at"); @@ -15295,7 +15295,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { let res = send( &app, "PATCH", - &format!("/chat/conversations/{first}"), + &format!("/chatbot/threads/{first}"), Some(&ali), Some(json!({ "title": " Fizik ödevi " })), ) @@ -15307,7 +15307,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { assert!(stamped > before, "{stamped} !> {before}"); // The rename is durable and re-sorted the list. - let listed = send(&app, "GET", "/chat/conversations", Some(&ali), None).await; + let listed = send(&app, "GET", "/chatbot/threads", Some(&ali), None).await; let items = common::items(&listed.body); assert_eq!(id_of(&items[0]), first, "the renamed thread is now first"); assert_eq!(items[0]["title"], "Fizik ödevi"); @@ -15317,7 +15317,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { let res = send( &app, "PATCH", - &format!("/chat/conversations/{first}"), + &format!("/chatbot/threads/{first}"), Some(&ali), Some(clearing.clone()), ) @@ -15329,7 +15329,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { send( &app, "PATCH", - &format!("/chat/conversations/{first}"), + &format!("/chatbot/threads/{first}"), Some(&ali), Some(json!({ "title": "geri" })), ) @@ -15340,7 +15340,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { let res = send( &app, "PATCH", - &format!("/chat/conversations/{first}"), + &format!("/chatbot/threads/{first}"), Some(&ali), Some(json!({ "title": "é".repeat(201) })), ) @@ -15349,7 +15349,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { let res = send( &app, "PATCH", - &format!("/chat/conversations/{first}"), + &format!("/chatbot/threads/{first}"), Some(&ali), Some(json!({ "title": "é".repeat(200) })), ) @@ -15360,7 +15360,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { let res = send( &app, "PATCH", - "/chat/conversations/nosuchthread", + "/chatbot/threads/nosuchthread", Some(&ali), Some(json!({ "title": "hayalet" })), ) @@ -15370,7 +15370,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { let res = send( &app, "GET", - &format!("/chat/conversations/{second}/messages"), + &format!("/chatbot/threads/{second}/messages"), Some(&ali), None, ) @@ -15380,7 +15380,7 @@ async fn chat_thread_can_be_renamed_and_cleared() { #[tokio::test] async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() { - // `RATE_LIMIT_CHAT_PER_MINUTE`, the third tier, behaves like the two IP + // `RATE_LIMIT_CHATBOT_PER_MINUTE`, the third tier, behaves like the two IP // ones: the configured number is honoured exactly and `0` switches it off. // No bridge is needed — the limiter is charged before the availability // 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() { let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(3)).await; let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; + let thread = new_thread(&app, &ali).await; for n in 1..=3 { - let res = post_turn(&app, &ali, &conversation, &format!("soru {n}")).await; + let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await; assert_eq!( res.status, StatusCode::SERVICE_UNAVAILABLE, @@ -15398,7 +15398,7 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() { res.body ); } - let res = post_turn(&app, &ali, &conversation, "dorduncu").await; + let res = post_turn(&app, &ali, &thread, "dorduncu").await; assert_eq!(res.status, StatusCode::TOO_MANY_REQUESTS, "{}", res.body); // Per user, still: a second caller starts with a full budget. let veli = login(&app, "veli").await; @@ -15413,9 +15413,9 @@ async fn chat_rate_limit_tier_is_configurable_and_zero_disables_it() { // `0` disables the tier: well past the shipped default, nothing is refused. let (app, _db) = chat_app_limited(None, UserRateLimiter::per_user_minute(0)).await; let ali = login(&app, "ali").await; - let conversation = new_thread(&app, &ali).await; + let thread = new_thread(&app, &ali).await; for n in 1..=40 { - let res = post_turn(&app, &ali, &conversation, &format!("soru {n}")).await; + let res = post_turn(&app, &ali, &thread, &format!("soru {n}")).await; assert_eq!( res.status, StatusCode::SERVICE_UNAVAILABLE, diff --git a/tests/persistence.rs b/tests/persistence.rs index 7ff7209..21f9c54 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -24,7 +24,7 @@ async fn reboot(db: &Database) -> Router { files_path: common::files_dir(), cookie_secure: false, rate_limit: RateLimitConfig::unlimited(), - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai: None, @@ -729,13 +729,13 @@ async fn appointments_survive_remigration() { } /// A chatbot thread and every turn in it die together: deleting the -/// conversation cascades its `chat_message` rows in one transaction, so no +/// thread cascades its `chatbot_message` rows in one transaction, so no /// orphan survives a reboot. And the thread is owner-scoped end to end — a -/// second user reads neither the conversation nor its messages. +/// second user reads neither the thread nor its messages. #[tokio::test] async fn chat_thread_delete_cascades_and_stays_owner_scoped() { - use hezarfen_backend::domain::chat_message::{ChatContent, ChatMessage, MessageStatus}; - use hezarfen_backend::domain::conversation::Conversation; + use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage, MessageStatus}; + use hezarfen_backend::domain::chatbot_thread::ChatbotThread; use hezarfen_backend::domain::user::UserId; let (app, db) = common::app_and_db().await; @@ -744,11 +744,11 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { let owner = UserId::from_key(&me_id(&app, &owner_cookie).await); let other = UserId::from_key(&me_id(&app, &other_cookie).await); - let conversation = Conversation::create(&owner, None, &db) + let thread = ChatbotThread::create(&owner, None, &db) .await .expect("create"); - let id = conversation.get_id().clone(); - let prompt = ChatMessage::append_user( + let id = thread.get_id().clone(); + let prompt = ChatbotMessage::append_user( &id, &owner, ChatContent::try_new("selam").expect("content"), @@ -756,12 +756,12 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { ) .await .expect("append user"); - let reply = ChatMessage::append_pending_assistant(&id, &owner, &db) + let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db) .await .expect("append assistant"); assert_eq!(reply.get_status(), MessageStatus::Pending); - let reply = ChatMessage::complete( + let reply = ChatbotMessage::complete( reply.get_id(), ChatContent::try_new("aleykum selam").expect("content"), false, @@ -773,56 +773,56 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { assert_eq!(reply.get_content().as_str(), "aleykum selam"); assert!(reply.get_completed_at().is_some()); assert_eq!( - ChatMessage::list_for_conversation(&id, &db) + ChatbotMessage::list_for_thread(&id, &db) .await .expect("thread") .len(), 2 ); - // The other user sees nothing of it, by conversation or by message. + // The other user sees nothing of it, by thread or by message. assert!( - Conversation::read_for(&id, &other, &db) + ChatbotThread::read_for(&id, &other, &db) .await - .expect("cross-user conversation") + .expect("cross-user thread") .is_none() ); assert!( - ChatMessage::read_for(prompt.get_id(), &other, &db) + ChatbotMessage::read_for(prompt.get_id(), &other, &db) .await .expect("cross-user message") .is_none() ); assert_eq!( - Conversation::count_for_user(&other, &db) + ChatbotThread::count_for_user(&other, &db) .await .expect("count"), 0 ); assert_eq!( - Conversation::count_for_user(&owner, &db) + ChatbotThread::count_for_user(&owner, &db) .await .expect("count"), 1 ); - conversation.delete(&db).await.expect("delete"); + thread.delete(&db).await.expect("delete"); assert!( - Conversation::read_for(&id, &owner, &db) + ChatbotThread::read_for(&id, &owner, &db) .await - .expect("deleted conversation") + .expect("deleted thread") .is_none() ); assert_eq!( - Conversation::list_for_user(&owner, &db) + ChatbotThread::list_for_user(&owner, &db) .await .unwrap() .len(), 0 ); - // Not just the thread's own view: no `chat_message` row is left anywhere. + // Not just the thread's own view: no `chatbot_message` row is left anywhere. let mut left = db - .query("SELECT VALUE id FROM chat_message") + .query("SELECT VALUE id FROM chatbot_message") .await .expect("sweep") .check() @@ -839,8 +839,8 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { /// read back as whole, which is exactly how they were shown at the time. #[tokio::test] async fn legacy_chat_turns_backfill_to_untruncated() { - use hezarfen_backend::domain::chat_message::{ChatContent, ChatMessage}; - use hezarfen_backend::domain::conversation::Conversation; + use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage}; + use hezarfen_backend::domain::chatbot_thread::ChatbotThread; use hezarfen_backend::domain::user::UserId; let (app, db) = common::app_and_db().await; @@ -857,11 +857,11 @@ async fn legacy_chat_turns_backfill_to_untruncated() { .unwrap(); let owner = UserId::from_key(&me_id(&app, &cookie).await); - let conversation = Conversation::create(&owner, None, &db) + let thread = ChatbotThread::create(&owner, None, &db) .await .expect("create"); - let id = conversation.get_id().clone(); - ChatMessage::append_user( + let id = thread.get_id().clone(); + ChatbotMessage::append_user( &id, &owner, ChatContent::try_new("selam").expect("content"), @@ -869,10 +869,10 @@ async fn legacy_chat_turns_backfill_to_untruncated() { ) .await .expect("append user"); - let reply = ChatMessage::append_pending_assistant(&id, &owner, &db) + let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db) .await .expect("append assistant"); - ChatMessage::complete( + ChatbotMessage::complete( reply.get_id(), ChatContent::try_new("aleykum selam").expect("content"), false, @@ -883,8 +883,8 @@ async fn legacy_chat_turns_backfill_to_untruncated() { // Strip the column the way a pre-flag binary's schema would have left it. db.query( - "REMOVE FIELD IF EXISTS truncated ON TABLE chat_message; - UPDATE chat_message SET truncated = NONE;", + "REMOVE FIELD IF EXISTS truncated ON TABLE chatbot_message; + UPDATE chatbot_message SET truncated = NONE;", ) .await .expect("strip truncated") @@ -901,7 +901,7 @@ async fn legacy_chat_turns_backfill_to_untruncated() { let res = send( &app, "GET", - &format!("/chat/conversations/{}/messages", id.key()), + &format!("/chatbot/threads/{}/messages", id.key()), Some(&cookie), None, ) diff --git a/tests/rate_limit.rs b/tests/rate_limit.rs index feb9961..73240ec 100644 --- a/tests/rate_limit.rs +++ b/tests/rate_limit.rs @@ -24,7 +24,7 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router { files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit, - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai: None, @@ -318,7 +318,7 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String { files_path: tempfile::tempdir().expect("files dir").keep(), cookie_secure: false, rate_limit, - chat_limit: Default::default(), + chatbot_limit: Default::default(), exam_presence: Default::default(), db_up: Default::default(), ai: None,