From 00bed90d47dc9d3b64a3629f717c96d8b1d498c4 Mon Sep 17 00:00:00 2001 From: MITOM06 Date: Thu, 5 Nov 2026 18:29:25 +0700 Subject: [PATCH 01/12] =?UTF-8?q?docs(plan):=20AI=20chat=20threads=20(Chat?= =?UTF-8?q?GPT-style)=20=E2=80=94=20plan=20for=20review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-11-05-ai-chat-threads.md | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-05-ai-chat-threads.md diff --git a/docs/superpowers/plans/2026-11-05-ai-chat-threads.md b/docs/superpowers/plans/2026-11-05-ai-chat-threads.md new file mode 100644 index 00000000..f7084c92 --- /dev/null +++ b/docs/superpowers/plans/2026-11-05-ai-chat-threads.md @@ -0,0 +1,124 @@ +# AI Chat Threads (ChatGPT-style) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** "Cuộc trò chuyện mới" with the AI creates a separate conversation (own history, title, files), listed in an AI sidebar — like ChatGPT — on web and mobile. + +**Architecture:** An AI thread is an ordinary chat-service `direct` conversation between the user and the AI bot; the user may now own many of them. New endpoints create/list/rename threads; the existing `POST /api/conversations` 409 ("open my one AI chat") stays for old app versions. Everything already keyed by conversationId (ai_sessions, KB, search, persona) becomes per-thread for free. Clients get an AI thread sidebar and stop showing AI threads in the main chat list. + +**Tech Stack:** Spring Boot 3 (chat-service), NestJS (ai-service), Next.js + TanStack Query (web), Flutter + Riverpod + go_router (mobile). + +**Spec:** this plan (decisions D1–D5 below, confirmed with the user 2026-11-05). Flow map: current single-chat flow — `ConversationService.createConversation` 409 at `ConversationService.java:50-75`, `useOpenAiChat` (web), `getOrCreateConversation` (Flutter). + +## Decisions (confirm before implementing) + +| # | Decision | Default in this plan | +|---|---|---| +| D1 | Where AI threads are listed | **Only in the AI sidebar** (web: left column when on the AI hub or an AI thread; mobile: AI hub screen + drawer from the AI chat). The main chat list hides them; the sidebar's "Trợ lý AI" button opens the AI area. | +| D2 | Thread title | **First user message, trimmed to 60 chars**, set by chat-service on the first message (instant, free). Renamable. No LLM title. | +| D3 | Existing single AI chat | Becomes the **first thread** as is — no migration. Its title stays empty → shown as "Trò chuyện với AI" until renamed. | +| D4 | Files / knowledge base | **Per thread** (as ChatGPT): a file uploaded in one thread is not searched in another. Long-term memory facts (Qdrant, per user) still carry across threads. | +| D5 | Persona | A new thread **copies the persona** of the user's most recently active thread, so the assistant keeps the name/tone the user set. | + +## Global Constraints + +- Back-compat: `POST /api/conversations {participantId: AI_BOT}` keeps returning the existing (oldest) AI chat via 409; `GET /api/conversations` without the new param returns what it returns today. +- AI bot id `ai-bot-000000000000000000000001` (`AiConstants.AI_BOT_USER_ID`, web `AI_BOT_ID` in `lib/constants.ts`, Flutter `kAiBotUserId`). +- i18n: every new string in all 7 web `messages/*.json` and all 7 Flutter `lib/l10n/app_*.arb`, then `flutter gen-l10n`. +- Web ↔ mobile parity (`.claude/rules/sync.md`); no raw ids/URLs in UI (`.claude/rules/no-raw-system-data-in-ui.md`). +- File size limits: Flutter widgets ≤ 400 lines, web components ≤ 400 lines, services ≤ 500. +- Thread limit: list returns at most 100 threads, newest activity first. + +## Review Focus + +1. A user with an **existing** AI chat opens the AI area → that chat is listed as a thread and its messages are intact (Task 1 list test + Task 4/6 manual check). +2. **Old mobile app** (not updated) → still opens the one AI chat via the 409 path and still sees it in its list (Task 1: list without `excludeAi` unchanged). +3. Thread A's file is **not** used to answer in thread B (KB is per conversation — Task 1 test asserts new thread is a new conversationId; no KB change needed). +4. Deleting a thread hides it **only for the user** and it never reappears in the AI sidebar (Task 1: list honours `hiddenFor`/deleted state). +5. Sending the first message names the thread, but a **renamed** thread is never overwritten by later messages (Task 1 auto-title test). + +--- + +### Task 1: chat-service — AI thread endpoints, auto-title, list filter + +**Files:** +- Create: `apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java` +- Create: `apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java` +- Create: `apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java` +- Modify: `ConversationController.java` (`GET /api/conversations` gains `@RequestParam(defaultValue="false") boolean excludeAi`), `ConversationQueryService.java` (filter), message send path where a message is saved (`MessageService` / the method used by `ChatController` + `MessageController`) to call `aiThreadService.maybeAutoTitle(conversation, content)`. +- Test: `src/test/java/.../service/AiThreadServiceTest.java`, `src/test/java/.../controller/AiThreadControllerTest.java` + +**Interfaces:** +- Produces REST (JWT user): + - `POST /api/ai-threads` → `201 ConversationResponse` (new direct conversation `[me, AI_BOT]`, `status=accepted`, `name=null`, persona copied per D5). + - `GET /api/ai-threads` → `List` of the caller's AI conversations (participants = me + bot), excluding ones the caller deleted/hid, sorted `lastMessageAt` desc (fallback `createdAt`), max 100. + - `PATCH /api/ai-threads/{id}` body `{name}` → `ConversationResponse`; 404 when not the caller's AI thread; name trimmed, 1–80 chars else 400 `AI_THREAD_NAME_INVALID`. + - Delete = existing `DELETE /api/conversations/{id}` (per-user). + - `GET /api/conversations?excludeAi=true` → same as today minus AI conversations. +- Produces Java: `AiThreadService.maybeAutoTitle(Conversation c, String userText)` — sets `name` to the first 60 chars (whitespace-collapsed, `…` when cut) only when `c` is a direct AI conversation, `name` is blank, and the sender is not the bot; never overwrites. + +- [ ] **Step 1: Failing tests** — `AiThreadServiceTest`: + - `create_makesNewConversationEvenWhenOneExists` (two creates → two distinct ids, both `[me, bot]`, status accepted). + - `create_copiesPersonaFromMostRecentThread` (persona of latest-active thread copied; none → no persona). + - `list_returnsOnlyCallersAiThreads_newestFirst_skipsDeleted` (another user's thread, a human DM and a deleted thread are absent). + - `rename_rejectsBlankAndTooLong_andForeignThread` (400 / 400 / 404). + - `autoTitle_setsFirst60Chars_once` (`" Xin chào\n bạn "` → `"Xin chào bạn"`; 70-char text → 59 chars + `…`; second message leaves it; renamed title kept; group conversation untouched). + - Controller test: `GET /api/conversations?excludeAi=true` omits the AI chat; without the param it is present. +- [ ] **Step 2:** `mvn -q test -Dtest='AiThread*'` → FAIL (classes missing). +- [ ] **Step 3:** Implement. Reuse `ConversationRepository` queries; `isDirectAiConversation` logic for the "is AI thread" check; persona copy via `AiPersonaRepository` (find by most recent AI thread of the user, save a copy with the new conversationId). +- [ ] **Step 4:** `mvn -q test` → all pass. +- [ ] **Step 5:** Document the endpoints in `docs/api-spec.md`; commit `feat(chat): AI threads — create/list/rename, auto-title, excludeAi list filter`. + +### Task 2: ai-service — no daily digest for AI threads + +**Files:** Modify `apps/server/ai-service/src/scheduler/daily-digest.cron.ts` (`activeConversations`); Test `daily-digest.cron.spec.ts`. + +**Interfaces:** none new. + +- [ ] **Step 1: Failing test** `skips conversations whose participants include the AI bot` — messages yesterday in an AI thread and a group → only the group is digested. +- [ ] **Step 2:** `npx jest src/scheduler` → FAIL. +- [ ] **Step 3:** After `distinct('conversationId')`, drop ids whose `conversations` doc has the bot in `participants` (one `find({_id:{$in}}, {participants:1})`). +- [ ] **Step 4:** `npx jest` → all pass; `npx tsc --noEmit`. +- [ ] **Step 5:** Commit `fix(ai): no daily digest for 1-1 AI threads`. + +### Task 3: web — data layer + +**Files:** Create `apps/web/lib/api/ai-threads.ts`, `apps/web/lib/hooks/use-ai-threads.ts`; Modify `lib/hooks/use-open-ai-chat.ts`, the conversations list query (add `excludeAi: true`), STOMP cache updates for a new/renamed AI conversation; Tests next to them (`*.test.ts`). + +**Interfaces:** +- `aiThreadsApi.list(): Promise`, `.create(): Promise`, `.rename(id, name): Promise`. +- `useAiThreads()` (query key `['ai-threads']`), `useCreateAiThread()` (creates, inserts at top of `['ai-threads']`, returns the conversation), `useRenameAiThread()`. +- `useOpenAiChat()` → opens the most recent thread (`list()[0]`), or creates one when none. + +- [ ] **Step 1:** Failing tests: list/create/rename hit `/api/ai-threads`; `useOpenAiChat` opens newest thread, creates when empty; main list request carries `excludeAi=true`. +- [ ] **Step 2:** `pnpm vitest run lib` → FAIL. **Step 3:** implement. **Step 4:** pass + `tsc`. **Step 5:** commit. + +### Task 4: web — AI sidebar UI + +**Files:** Create `apps/web/components/ai/AiThreadList.tsx` (+ `AiThreadItem.tsx` if needed); Modify `app/(main)/layout.tsx` (show `AiThreadList` instead of `ConversationList` when the route is `/ai-hub` or the open conversation is an AI thread), `components/chat/ConversationSettingsDrawer.tsx` (remove `AiSessionPanel`), `ConversationHeader.tsx` (AI thread shows its title; "New chat" icon button), delete `components/chat/AiSessionPanel.tsx` + `lib/api/ai-session.ts` if unused; `messages/*.json` (7). + +**Interfaces:** consumes Task 3 hooks. + +- [ ] **Step 1:** Failing component tests: list renders titles (empty title → "Trò chuyện với AI" key `aiThreads.untitled`), newest first, active one highlighted; "Cuộc trò chuyện mới" creates and navigates to `/conversations/{id}`; rename inline (Enter saves, Esc cancels); delete asks confirm then removes and, if it was open, navigates to the next thread or `/ai-hub`; "Quay lại tin nhắn" link restores the normal list. +- [ ] **Step 2–4:** fail → implement → `pnpm vitest run` + `tsc` + `eslint` pass; mobile width (375px) usable. +- [ ] **Step 5:** commit `feat(web): ChatGPT-style AI threads sidebar`. + +### Task 5: Flutter — data layer + +**Files:** Create `apps/client/lib/features/ai_hub/data/ai_thread_repository.dart`, `.../domain/ai_threads_provider.dart`; Modify `chat_repository_conversation_ops.dart` (list with `excludeAi=true`), `ai_hub_screen.dart` `startAiChat` (open newest / create), STOMP conversation updates invalidate `aiThreadsProvider`; Tests under `test/features/ai_hub/`. + +**Interfaces:** `AiThreadRepository.list()/create()/rename(id, name)`; `aiThreadsProvider` (AsyncNotifier) with `create()`, `rename()`, `delete()`. + +- [ ] Steps as Task 3 (`flutter test test/features/ai_hub`, `flutter analyze`). + +### Task 6: Flutter — AI threads UI + +**Files:** Modify `ai_hub_screen.dart` (thread list + "Cuộc trò chuyện mới" button, empty state), `chat_app_bar.dart` (AI thread: title + "new chat" + "threads" actions opening a drawer/sheet with the list), conversation list (no AI threads), remove `ai_session_panel.dart` usage in `conversation_info_sidebar.dart`; `lib/l10n/app_*.arb` (7) + `flutter gen-l10n`. + +- [ ] Widget tests mirroring Task 4 (list, create+navigate, rename, delete+navigate); `flutter test` + `flutter analyze` clean; commit. + +### Task 7: Verification + +- [ ] Full suites: chat-service `mvn test`, ai-service `npx jest`, web `pnpm vitest run`, Flutter `flutter test`. +- [ ] Merge into `dev`, run locally / Vercel preview: existing AI chat appears as a thread; new thread is empty; a file uploaded in thread A is not cited in thread B; delete/rename; old behaviour of the main list without `excludeAi`. +- [ ] Single PR to `main` after `dev` passes. From 0c4b439e4b9e3cfd40fe7e83ad4816ddb46e4765 Mon Sep 17 00:00:00 2001 From: MITOM06 Date: Thu, 5 Nov 2026 18:36:44 +0700 Subject: [PATCH 02/12] =?UTF-8?q?feat(chat):=20AI=20threads=20=E2=80=94=20?= =?UTF-8?q?create/list/rename,=20auto-title,=20excludeAi=20list=20filter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../controller/AiThreadController.java | 56 ++++ .../controller/ConversationController.java | 8 +- .../dto/RenameAiThreadRequest.java | 4 + .../chatservice/exception/ErrorCodes.java | 3 + .../chatservice/service/AiThreadService.java | 151 ++++++++++ .../service/ConversationQueryService.java | 18 ++ .../chatservice/service/MessageService.java | 5 + .../controller/AiThreadControllerTest.java | 140 +++++++++ .../service/AiThreadServiceTest.java | 282 ++++++++++++++++++ .../chatservice/service/MessagePinTest.java | 3 +- .../chatservice/service/MessageSendTest.java | 3 +- .../service/UploadRefsActorTest.java | 3 +- docs/api-spec.md | 28 +- 13 files changed, 697 insertions(+), 7 deletions(-) create mode 100644 apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java create mode 100644 apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java create mode 100644 apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java create mode 100644 apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java create mode 100644 apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java new file mode 100644 index 00000000..251d400d --- /dev/null +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/AiThreadController.java @@ -0,0 +1,56 @@ +package com.platform.chatservice.controller; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.dto.RenameAiThreadRequest; +import com.platform.chatservice.exception.UnauthorizedException; +import com.platform.chatservice.security.UserPrincipal; +import com.platform.chatservice.service.AiThreadService; +import com.platform.chatservice.service.ConversationEventPublisher; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.*; + +/** + * ChatGPT-style AI threads. Deleting a thread is the existing {@code DELETE + * /api/conversations/{id}}. + */ +@RestController +@RequestMapping("/api/ai-threads") +@RequiredArgsConstructor +public class AiThreadController { + + private final AiThreadService aiThreadService; + private final ConversationEventPublisher events; + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public ConversationResponse create() { + String userId = currentUserId(); + ConversationResponse created = aiThreadService.create(userId); + // The user's other devices learn about the new thread via their own notification queue. + events.publishToUser(userId, created); + return created; + } + + @GetMapping + public List list() { + return aiThreadService.list(currentUserId()); + } + + @PatchMapping("/{id}") + public ConversationResponse rename( + @PathVariable String id, @RequestBody RenameAiThreadRequest request) { + ConversationResponse updated = aiThreadService.rename(currentUserId(), id, request.name()); + events.publishShared(updated); + return updated; + } + + private String currentUserId() { + if (SecurityContextHolder.getContext().getAuthentication() instanceof UserPrincipal p) { + return p.getUserId(); + } + throw new UnauthorizedException("Not authenticated"); + } +} diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java index eca86475..dd730120 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/controller/ConversationController.java @@ -64,20 +64,22 @@ public class ConversationController { /** * The caller's conversations. {@code archived=true} → only archived ones (default: archived ones - * excluded); {@code blocked=true} → the Blocked section. {@code size} is capped at 100. + * excluded); {@code blocked=true} → the Blocked section. {@code excludeAi=true} drops 1-1 chats + * with the AI bot (they live in the AI-thread list). {@code size} is capped at 100. */ @GetMapping public PageResponse listConversations( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size, @RequestParam(defaultValue = "false") boolean archived, - @RequestParam(defaultValue = "false") boolean blocked) { + @RequestParam(defaultValue = "false") boolean blocked, + @RequestParam(defaultValue = "false") boolean excludeAi) { if (blocked) { return conversationQueryService.listBlockedConversations( currentUserId(), PageLimits.of(page, size, 20)); } return conversationQueryService.listConversations( - currentUserId(), PageLimits.of(page, size, 20), archived); + currentUserId(), PageLimits.of(page, size, 20), archived, excludeAi); } @PostMapping diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java new file mode 100644 index 00000000..11412dc3 --- /dev/null +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/dto/RenameAiThreadRequest.java @@ -0,0 +1,4 @@ +package com.platform.chatservice.dto; + +/** Body of {@code PATCH /api/ai-threads/{id}}. */ +public record RenameAiThreadRequest(String name) {} diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java index e7b8a0b0..8751b97e 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/exception/ErrorCodes.java @@ -57,6 +57,9 @@ public final class ErrorCodes { public static final String PUBLIC_DEPARTMENT_CHANNEL_NOT_ALLOWED = "PUBLIC_DEPARTMENT_CHANNEL_NOT_ALLOWED"; + /** 400 — an AI thread name is blank or longer than 80 characters after trimming. */ + public static final String AI_THREAD_NAME_INVALID = "AI_THREAD_NAME_INVALID"; + // ── Meetings (/api/meetings) ────────────────────────────────────────────── /** 404 — no meeting with this id / code. */ diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java new file mode 100644 index 00000000..93533f0b --- /dev/null +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/AiThreadService.java @@ -0,0 +1,151 @@ +package com.platform.chatservice.service; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.exception.BadRequestException; +import com.platform.chatservice.exception.ConversationNotFoundException; +import com.platform.chatservice.exception.ErrorCodes; +import com.platform.chatservice.model.AiPersona; +import com.platform.chatservice.model.Conversation; +import com.platform.chatservice.repository.AiPersonaRepository; +import com.platform.chatservice.repository.ConversationRepository; +import java.time.Instant; +import java.util.Comparator; +import java.util.List; +import lombok.RequiredArgsConstructor; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Update; +import org.springframework.stereotype.Service; + +/** + * ChatGPT-style AI threads: every "new chat" with the assistant is its own {@code direct} + * conversation between the user and the AI bot. {@link ConversationService#createConversation} + * keeps refusing a second DM for the same pair (older clients rely on that 409), so threads are + * created here instead. + */ +@Service +@RequiredArgsConstructor +public class AiThreadService { + + static final int MAX_LIST = 100; + static final int MAX_NAME_LENGTH = 80; + static final int TITLE_LENGTH = 60; + + private final ConversationRepository conversationRepository; + private final ConversationCacheService conversationCacheService; + private final AiPersonaRepository aiPersonaRepository; + private final ConversationWriteSupport support; + private final ConversationEventPublisher events; + + /** + * New thread {@code [user, AI_BOT]}; the persona of the most recently active thread is copied. + */ + public ConversationResponse create(String userId) { + List existing = threadsOf(userId); + Conversation saved = + conversationCacheService.save( + Conversation.builder() + .participants(List.of(userId, AiConstants.AI_BOT_USER_ID)) + .type(Conversation.TYPE_DIRECT) + .createdBy(userId) + .status(Conversation.STATUS_ACCEPTED) + .build()); + existing.stream() + .max(ACTIVITY) + .flatMap(latest -> aiPersonaRepository.findByConversationId(latest.getId())) + .ifPresent(source -> aiPersonaRepository.save(copyPersona(source, saved.getId(), userId))); + return support.view(saved, userId, 0L); + } + + /** The caller's visible AI threads, newest activity first (max {@value #MAX_LIST}). */ + public List list(String userId) { + return threadsOf(userId).stream() + .filter(c -> c.getHiddenFor() == null || !c.getHiddenFor().contains(userId)) + .filter(c -> c.getBlockedBy() == null || !c.getBlockedBy().contains(userId)) + .sorted(ACTIVITY.reversed()) + .limit(MAX_LIST) + .map(c -> support.view(c, userId, 0L)) + .toList(); + } + + /** Rename. 404 unless {@code id} is one of the caller's AI threads; 400 on a bad name. */ + public ConversationResponse rename(String userId, String id, String rawName) { + Conversation thread = support.requireParticipant(userId, id); + if (!isAiThread(thread)) { + throw new ConversationNotFoundException(id); + } + String name = rawName == null ? "" : rawName.trim(); + if (name.isEmpty() || name.length() > MAX_NAME_LENGTH) { + throw new BadRequestException( + ErrorCodes.AI_THREAD_NAME_INVALID, "Thread name must be 1-80 characters"); + } + Conversation updated = support.update(id, null, new Update().set("name", name)); + return support.view(updated != null ? updated : thread, userId, 0L); + } + + /** + * Title an untitled AI thread from the user's first message: first {@value #TITLE_LENGTH} + * characters, whitespace collapsed, {@code …} when cut. Never overwrites an existing name (the + * write is guarded atomically, so a concurrent rename wins) and ignores non-AI conversations. + */ + public void maybeAutoTitle(Conversation conversation, String userText) { + if (conversation == null + || userText == null + || !isAiThread(conversation) + || (conversation.getName() != null && !conversation.getName().isBlank())) { + return; + } + String title = toTitle(userText); + if (title.isEmpty()) { + return; + } + Criteria unnamed = + new Criteria().orOperator(Criteria.where("name").is(null), Criteria.where("name").is("")); + Conversation updated = + support.update(conversation.getId(), unnamed, new Update().set("name", title)); + if (updated != null) { + events.publishShared(support.view(updated, null, 0L)); + } + } + + static String toTitle(String text) { + String collapsed = text.trim().replaceAll("\\s+", " "); + if (collapsed.length() <= TITLE_LENGTH) { + return collapsed; + } + int end = TITLE_LENGTH - 1; + if (Character.isHighSurrogate(collapsed.charAt(end - 1))) { + end--; + } + return collapsed.substring(0, end) + "…"; + } + + static boolean isAiThread(Conversation c) { + return !c.isGroup() + && c.getParticipants() != null + && c.getParticipants().size() == 2 + && c.getParticipants().contains(AiConstants.AI_BOT_USER_ID); + } + + private List threadsOf(String userId) { + return conversationRepository.findOneOnOneConversations( + List.of(userId, AiConstants.AI_BOT_USER_ID)); + } + + private static AiPersona copyPersona(AiPersona source, String conversationId, String userId) { + return AiPersona.builder() + .conversationId(conversationId) + .name(source.getName()) + .avatarUrl(source.getAvatarUrl()) + .tone(source.getTone()) + .systemPromptPrefix(source.getSystemPromptPrefix()) + .createdBy(userId) + .build(); + } + + /** {@code lastMessageAt}, falling back to {@code createdAt}. */ + private static final Comparator ACTIVITY = + Comparator.comparing( + (Conversation c) -> + c.getLastMessageAt() != null ? c.getLastMessageAt() : c.getCreatedAt(), + Comparator.nullsFirst(Comparator.naturalOrder())); +} diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java index d45ab5d4..e18d1cce 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/ConversationQueryService.java @@ -53,6 +53,12 @@ public PageResponse listConversations(String userId, Pagea */ public PageResponse listConversations( String userId, Pageable pageable, boolean archived) { + return listConversations(userId, pageable, archived, false); + } + + /** As above; {@code excludeAi} also drops direct chats with the AI bot (AI threads). */ + public PageResponse listConversations( + String userId, Pageable pageable, boolean archived, boolean excludeAi) { Criteria criteria = Criteria.where("participants") .is(userId) @@ -65,6 +71,18 @@ public PageResponse listConversations( } else { criteria = criteria.and("archivedBy").ne(userId); } + if (excludeAi) { + criteria = + new Criteria() + .andOperator( + criteria, + new Criteria() + .norOperator( + Criteria.where("participants") + .is(AiConstants.AI_BOT_USER_ID) + .and("type") + .ne(Conversation.TYPE_GROUP))); + } Query query = new Query(criteria) .with( diff --git a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java index 3805e32b..d80ea963 100644 --- a/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java +++ b/apps/server/chat-service/src/main/java/com/platform/chatservice/service/MessageService.java @@ -46,6 +46,7 @@ public class MessageService { private final AiMessageService aiMessageService; private final ConversationCacheService conversationCacheService; private final UploadRefs uploadRefs; + private final AiThreadService aiThreadService; /** * Outcome of a recall / edit: the updated message, and whether it was the conversation's newest @@ -103,6 +104,10 @@ public MessageResponse sendMessage(String senderId, SendMessageRequest request) update.set("status", Conversation.STATUS_ACCEPTED); } bumpConversation(request.conversationId(), update); + // First user text in an untitled AI thread becomes its title (shared by STOMP + REST sends). + if (MessageTypePolicy.triggersAssistant(type) && !AiConstants.AI_BOT_USER_ID.equals(senderId)) { + aiThreadService.maybeAutoTitle(conversation, request.content()); + } return toResponse(message); } diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java new file mode 100644 index 00000000..abfddeb8 --- /dev/null +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/controller/AiThreadControllerTest.java @@ -0,0 +1,140 @@ +package com.platform.chatservice.controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.dto.PageResponse; +import com.platform.chatservice.dto.RenameAiThreadRequest; +import com.platform.chatservice.model.Conversation; +import com.platform.chatservice.repository.ConversationRepository; +import com.platform.chatservice.repository.MessageRepository; +import com.platform.chatservice.security.UserPrincipal; +import com.platform.chatservice.service.AiConstants; +import com.platform.chatservice.service.AiThreadService; +import com.platform.chatservice.service.ConversationCacheService; +import com.platform.chatservice.service.ConversationEventPublisher; +import com.platform.chatservice.service.ConversationMapper; +import com.platform.chatservice.service.ConversationQueryService; +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.security.core.context.SecurityContextHolder; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AiThreadControllerTest { + + private static final String ME = "user-001"; + + @Mock private AiThreadService aiThreadService; + @Mock private ConversationEventPublisher events; + @Mock private ConversationRepository conversationRepository; + @Mock private ConversationCacheService cache; + @Mock private MongoTemplate mongoTemplate; + @Mock private MessageRepository messageRepository; + + @InjectMocks private AiThreadController controller; + + @BeforeEach + void setUp() { + SecurityContextHolder.getContext().setAuthentication(new UserPrincipal(ME)); + } + + @AfterEach + void tearDown() { + SecurityContextHolder.clearContext(); + } + + private static ConversationResponse view(String id) { + return new ConversationResponse( + id, + "direct", + null, + null, + List.of(ME, AiConstants.AI_BOT_USER_ID), + null, + ME, + null, + null, + null, + 0L, + Instant.now(), + "accepted", + false, + List.of(), + null, + null, + null, + null, + null, + List.of(), + null, + null); + } + + @Test + void create_publishesToCreatorsOtherDevices() { + ConversationResponse v = view("c1"); + when(aiThreadService.create(ME)).thenReturn(v); + + assertThat(controller.create()).isSameAs(v); + verify(events).publishToUser(ME, v); + } + + @Test + void rename_broadcastsSharedUpdate() { + ConversationResponse v = view("c1"); + when(aiThreadService.rename(ME, "c1", "Plan")).thenReturn(v); + + assertThat(controller.rename("c1", new RenameAiThreadRequest("Plan"))).isSameAs(v); + verify(events).publishShared(v); + } + + /** GET /api/conversations?excludeAi=... against the real query service (mocked Mongo). */ + private String listQueryJson(boolean excludeAi) { + ConversationQueryService queries = + new ConversationQueryService( + conversationRepository, + cache, + mongoTemplate, + new ConversationMapper(messageRepository)); + ArgumentCaptor q = ArgumentCaptor.forClass(Query.class); + when(mongoTemplate.find(q.capture(), eq(Conversation.class))).thenReturn(List.of()); + when(mongoTemplate.count(any(Query.class), eq(Conversation.class))).thenReturn(0L); + PageResponse r = + queries.listConversations(ME, PageRequest.of(0, 20), false, excludeAi); + assertThat(r.content()).isEmpty(); + return q.getValue().getQueryObject().toJson(); + } + + @Test + void listConversations_excludeAi_addsNorOnDirectBotChats() { + assertThat(listQueryJson(true)) + .contains("$nor") + .contains(AiConstants.AI_BOT_USER_ID) + .contains("\"hiddenFor\""); + } + + @Test + void listConversations_withoutExcludeAi_hasNoBotFilter() { + assertThat(listQueryJson(false)) + .doesNotContain("$nor") + .doesNotContain(AiConstants.AI_BOT_USER_ID); + } +} diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java new file mode 100644 index 00000000..df580fe3 --- /dev/null +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/AiThreadServiceTest.java @@ -0,0 +1,282 @@ +package com.platform.chatservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.platform.chatservice.dto.ConversationResponse; +import com.platform.chatservice.exception.BadRequestException; +import com.platform.chatservice.exception.ConversationNotFoundException; +import com.platform.chatservice.exception.ErrorCodes; +import com.platform.chatservice.model.AiPersona; +import com.platform.chatservice.model.Conversation; +import com.platform.chatservice.repository.AiPersonaRepository; +import com.platform.chatservice.repository.ConversationRepository; +import com.platform.chatservice.repository.MessageRepository; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.springframework.data.mongodb.core.FindAndModifyOptions; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.UpdateDefinition; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class AiThreadServiceTest { + + private static final String ME = "user-001"; + private static final String BOT = AiConstants.AI_BOT_USER_ID; + + @Mock private ConversationRepository conversationRepository; + @Mock private ConversationCacheService cache; + @Mock private AiPersonaRepository personaRepository; + @Mock private MongoTemplate mongoTemplate; + @Mock private MessageRepository messageRepository; + @Mock private ConversationEventPublisher events; + + private AiThreadService service; + private final AtomicInteger seq = new AtomicInteger(); + + @BeforeEach + void setUp() { + ConversationWriteSupport support = + new ConversationWriteSupport( + cache, mongoTemplate, messageRepository, new ConversationMapper(messageRepository)); + service = + new AiThreadService(conversationRepository, cache, personaRepository, support, events); + when(cache.save(any(Conversation.class))) + .thenAnswer( + inv -> { + Conversation c = inv.getArgument(0); + c.setId("new-" + seq.incrementAndGet()); + return c; + }); + when(conversationRepository.findOneOnOneConversations(any())).thenReturn(List.of()); + } + + private static Conversation thread(String id, Instant lastAt, Instant createdAt) { + return Conversation.builder() + .id(id) + .type("direct") + .participants(List.of(ME, BOT)) + .lastMessageAt(lastAt) + .createdAt(createdAt) + .hiddenFor(new ArrayList<>()) + .build(); + } + + @Test + void create_makesNewConversationEvenWhenOneExists() { + when(conversationRepository.findOneOnOneConversations(List.of(ME, BOT))) + .thenReturn(List.of(thread("old", null, Instant.now()))); + + ConversationResponse a = service.create(ME); + ConversationResponse b = service.create(ME); + + assertThat(a.id()).isNotEqualTo(b.id()); + for (ConversationResponse r : List.of(a, b)) { + assertThat(r.participants()).containsExactly(ME, BOT); + assertThat(r.status()).isEqualTo("accepted"); + assertThat(r.type()).isEqualTo("direct"); + assertThat(r.name()).isNull(); + } + } + + @Test + void create_copiesPersonaFromMostRecentThread() { + Instant now = Instant.now(); + when(conversationRepository.findOneOnOneConversations(List.of(ME, BOT))) + .thenReturn( + List.of( + thread("stale", now.minusSeconds(500), now.minusSeconds(900)), + thread("fresh", now.minusSeconds(5), now.minusSeconds(800)), + thread("empty", null, now.minusSeconds(700)))); + AiPersona persona = + AiPersona.builder() + .id("p1") + .conversationId("fresh") + .name("Jarvis") + .tone("formal") + .avatarUrl("/a.png") + .systemPromptPrefix("Be brief") + .build(); + when(personaRepository.findByConversationId("fresh")).thenReturn(Optional.of(persona)); + + ConversationResponse created = service.create(ME); + + ArgumentCaptor saved = ArgumentCaptor.forClass(AiPersona.class); + verify(personaRepository).save(saved.capture()); + AiPersona copy = saved.getValue(); + assertThat(copy.getId()).isNull(); + assertThat(copy.getConversationId()).isEqualTo(created.id()); + assertThat(copy.getName()).isEqualTo("Jarvis"); + assertThat(copy.getTone()).isEqualTo("formal"); + assertThat(copy.getSystemPromptPrefix()).isEqualTo("Be brief"); + assertThat(copy.getAvatarUrl()).isEqualTo("/a.png"); + } + + @Test + void create_withoutAnyThreadOrPersona_savesNoPersona() { + service.create(ME); + when(conversationRepository.findOneOnOneConversations(List.of(ME, BOT))) + .thenReturn(List.of(thread("t", null, Instant.now()))); + service.create(ME); // latest thread has no persona + verify(personaRepository, never()).save(any(AiPersona.class)); + } + + @Test + void list_returnsOnlyCallersAiThreads_newestFirst_skipsDeleted() { + Instant now = Instant.now(); + Conversation older = thread("older", now.minusSeconds(100), now.minusSeconds(900)); + Conversation newest = thread("newest", now.minusSeconds(1), now.minusSeconds(800)); + Conversation noMessages = thread("fresh", null, now.minusSeconds(50)); + Conversation deleted = thread("deleted", now, now); + deleted.setHiddenFor(new ArrayList<>(List.of(ME))); + Conversation blocked = thread("blocked", now, now); + blocked.setBlockedBy(new ArrayList<>(List.of(ME))); + // The repository query is already scoped to [me, bot] direct chats, so another user's thread + // and human DMs never come back; assert the exact query used. + when(conversationRepository.findOneOnOneConversations(List.of(ME, BOT))) + .thenReturn(List.of(older, deleted, noMessages, newest, blocked)); + + List result = service.list(ME); + + assertThat(result) + .extracting(ConversationResponse::id) + .containsExactly("newest", "fresh", "older"); + verify(conversationRepository).findOneOnOneConversations(List.of(ME, BOT)); + } + + private void updateReturns(Conversation c) { + when(mongoTemplate.findAndModify( + any(), + any(UpdateDefinition.class), + any(FindAndModifyOptions.class), + eq(Conversation.class))) + .thenReturn(c); + } + + @Test + void rename_rejectsBlankAndTooLong_andForeignThread() { + when(cache.findByIdOptional("mine")) + .thenReturn(Optional.of(thread("mine", null, Instant.now()))); + Conversation foreign = + Conversation.builder() + .id("foreign") + .type("direct") + .participants(List.of("other", BOT)) + .build(); + when(cache.findByIdOptional("foreign")).thenReturn(Optional.of(foreign)); + Conversation humanDm = + Conversation.builder() + .id("dm") + .type("direct") + .participants(List.of(ME, "user-002")) + .build(); + when(cache.findByIdOptional("dm")).thenReturn(Optional.of(humanDm)); + + assertThatThrownBy(() -> service.rename(ME, "mine", " ")) + .isInstanceOfSatisfying( + BadRequestException.class, + e -> assertThat(e.getCode()).isEqualTo(ErrorCodes.AI_THREAD_NAME_INVALID)); + assertThatThrownBy(() -> service.rename(ME, "mine", null)) + .isInstanceOf(BadRequestException.class); + assertThatThrownBy(() -> service.rename(ME, "mine", "x".repeat(81))) + .isInstanceOfSatisfying( + BadRequestException.class, + e -> assertThat(e.getCode()).isEqualTo(ErrorCodes.AI_THREAD_NAME_INVALID)); + assertThatThrownBy(() -> service.rename(ME, "foreign", "ok")) + .isInstanceOf(ConversationNotFoundException.class); + assertThatThrownBy(() -> service.rename(ME, "dm", "ok")) + .isInstanceOf(ConversationNotFoundException.class); + } + + @Test + void rename_trimsAndPersists() { + Conversation t = thread("mine", null, Instant.now()); + when(cache.findByIdOptional("mine")).thenReturn(Optional.of(t)); + Conversation renamed = thread("mine", null, Instant.now()); + renamed.setName("Plan"); + updateReturns(renamed); + + ConversationResponse r = service.rename(ME, "mine", " Plan "); + + assertThat(r.name()).isEqualTo("Plan"); + ArgumentCaptor u = ArgumentCaptor.forClass(UpdateDefinition.class); + verify(mongoTemplate) + .findAndModify(any(), u.capture(), any(FindAndModifyOptions.class), eq(Conversation.class)); + assertThat(u.getValue().getUpdateObject().toJson()).contains("\"name\": \"Plan\""); + } + + private String autoTitleWrites(Conversation c, String text) { + Conversation after = thread(c.getId(), null, Instant.now()); + updateReturns(after); + service.maybeAutoTitle(c, text); + ArgumentCaptor u = ArgumentCaptor.forClass(UpdateDefinition.class); + verify(mongoTemplate) + .findAndModify(any(), u.capture(), any(FindAndModifyOptions.class), eq(Conversation.class)); + return u.getValue().getUpdateObject().toJson(); + } + + @Test + void autoTitle_setsFirst60Chars_once() { + assertThat(autoTitleWrites(thread("t1", null, Instant.now()), " Xin chào\n bạn ")) + .contains("\"name\": \"Xin chào bạn\""); + } + + @Test + void autoTitle_cutsLongTextTo59CharsPlusEllipsis() { + String json = autoTitleWrites(thread("t2", null, Instant.now()), "a".repeat(70)); + assertThat(json).contains("\"name\": \"" + "a".repeat(59) + "…\""); + } + + @Test + void autoTitle_neverOverwrites_andIgnoresNonAiConversations() { + Conversation named = thread("t3", null, Instant.now()); + named.setName("My title"); + service.maybeAutoTitle(named, "second message"); + + Conversation group = + Conversation.builder().id("g").type("group").participants(List.of(ME, BOT)).build(); + service.maybeAutoTitle(group, "hello"); + + Conversation threeWay = + Conversation.builder().id("x").type("direct").participants(List.of(ME, "u2", BOT)).build(); + service.maybeAutoTitle(threeWay, "hello"); + + service.maybeAutoTitle(thread("t4", null, Instant.now()), " "); + + verify(mongoTemplate, never()) + .findAndModify( + any(), + any(UpdateDefinition.class), + any(FindAndModifyOptions.class), + eq(Conversation.class)); + } + + @Test + void autoTitle_publishesSharedEventOnlyWhenTitled() { + Conversation c = thread("t5", null, Instant.now()); + updateReturns(null); // a concurrent rename already won the guarded write + service.maybeAutoTitle(c, "hi"); + verify(events, never()).publishShared(any(ConversationResponse.class)); + + updateReturns(thread("t5", null, Instant.now())); + service.maybeAutoTitle(c, "hi"); + verify(events).publishShared(any(ConversationResponse.class)); + } +} diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java index 945856d2..0c7b721a 100644 --- a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessagePinTest.java @@ -70,7 +70,8 @@ void setUp() { messageMapper, aiMessageService, conversationCacheService, - uploadRefs); + uploadRefs, + org.mockito.Mockito.mock(AiThreadService.class)); interactionService = new MessageInteractionService( messageRepository, diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java index a2529a16..bac0a757 100644 --- a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/MessageSendTest.java @@ -75,7 +75,8 @@ void setUp() { messageMapper, aiMessageService, conversationCacheService, - uploadRefs); + uploadRefs, + org.mockito.Mockito.mock(AiThreadService.class)); conversation = Conversation.builder().id(CONV_ID).participants(List.of(SENDER_ID, OTHER_ID)).build(); diff --git a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java index 940eb120..4276017b 100644 --- a/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java +++ b/apps/server/chat-service/src/test/java/com/platform/chatservice/service/UploadRefsActorTest.java @@ -101,7 +101,8 @@ void setUp() { mapper, aiMessageService, cache, - refs); + refs, + org.mockito.Mockito.mock(AiThreadService.class)); ConversationWriteSupport support = new ConversationWriteSupport( cache, mongoTemplate, messageRepository, new ConversationMapper(messageRepository)); diff --git a/docs/api-spec.md b/docs/api-spec.md index f9e8e59e..2c2d515d 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -25,7 +25,8 @@ Response 200: { "title": "string", "description": "string", "imageUrl": "string" ### List conversations (paginated) ```http -GET /api/conversations +GET /api/conversations?page=0&size=20&archived=false&blocked=false&excludeAi=false +# excludeAi=true: drops direct chats with the AI bot (they are listed by /api/ai-threads) Response 200: { "content": [ @@ -188,6 +189,31 @@ Response 200: List of Message objects matching attachment category --- +## 🤖 AI Threads (`/api/ai-threads`) + +Each "new chat" with the assistant is its own `direct` conversation `[me, ai-bot-000000000000000000000001]` +(`POST /api/conversations` still answers 409 for a second DM with the bot — old clients rely on it). +Delete a thread with `DELETE /api/conversations/{id}` (per-user hide). Untitled threads are auto-named +from the user's first text message (first 60 chars, whitespace collapsed, `…` when cut) for both STOMP +and REST sends; an existing name is never overwritten. + +```http +POST /api/ai-threads +Response 201: Conversation object (name = null, status = accepted, persona copied from the + caller's most recently active AI thread if any) +# also pushes CONVERSATION_UPDATED to the caller's /user/queue/notifications + +GET /api/ai-threads +Response 200: [Conversation] # caller's AI threads, lastMessageAt desc (fallback createdAt), max 100, + # excludes threads the caller deleted/blocked + +PATCH /api/ai-threads/{id} +Body: { "name": "string" } # trimmed, 1-80 chars +Response 200: Conversation object (+ shared CONVERSATION_UPDATED on /topic/conversation/{id}) +Response 400: { "code": "AI_THREAD_NAME_INVALID" } +Response 404: not one of the caller's AI threads +``` + ## ✉️ Messages (`/api/messages`) ### Send Message (REST fallback) From ae009b02c929b0ac90ac64cc71dfccee7ee23eb2 Mon Sep 17 00:00:00 2001 From: MITOM06 Date: Thu, 5 Nov 2026 18:40:12 +0700 Subject: [PATCH 03/12] fix(ai): no daily digest for 1-1 AI threads Co-Authored-By: Claude Opus 5.5 --- .../src/scheduler/daily-digest.cron.spec.ts | 34 +++++++++++++++++-- .../src/scheduler/daily-digest.cron.ts | 17 +++++++++- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts b/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts index d2b8a566..23336944 100644 --- a/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts +++ b/apps/server/ai-service/src/scheduler/daily-digest.cron.spec.ts @@ -1,3 +1,4 @@ +import { Types } from 'mongoose'; import { DailyDigestCron } from './daily-digest.cron'; import { ResolvedAiSettings } from '../settings/resolved-ai-settings'; @@ -22,17 +23,24 @@ interface Mocks { create: jest.Mock; deleteOne: jest.Mock; distinct: jest.Mock; + find: jest.Mock; generate: jest.Mock; } function makeCron(opts: { resolved: ResolvedAiSettings; activeIds?: string[]; + aiThreadIds?: string[]; createImpl?: jest.Mock; generateImpl?: jest.Mock; }): Mocks { const distinct = jest.fn().mockResolvedValue(opts.activeIds ?? ['conv-1']); - const connection = { collection: () => ({ distinct }) } as any; + const find = jest.fn().mockReturnValue({ + toArray: jest + .fn() + .mockResolvedValue((opts.aiThreadIds ?? []).map((id) => ({ _id: new Types.ObjectId(id) }))), + }); + const connection = { collection: () => ({ distinct, find }) } as any; const create = opts.createImpl ?? jest.fn().mockResolvedValue({}); const deleteOne = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({}) }); @@ -47,7 +55,7 @@ function makeCron(opts: { ({ 'config.ai.timeZone': 'Asia/Ho_Chi_Minh', 'config.bot.userId': 'ai-bot-1' })[k], } as any; const cron = new DailyDigestCron(connection, digestLogModel, settingsService, generator, config); - return { cron, create, deleteOne, distinct, generate }; + return { cron, create, deleteOne, distinct, find, generate }; } // 08:00 in the workspace zone (Asia/Ho_Chi_Minh, +07:00) — 01:00 UTC. Absolute @@ -101,6 +109,28 @@ describe('DailyDigestCron (TASK-11)', () => { expect(deleteOne).not.toHaveBeenCalled(); }); + it('skips conversations whose participants include the AI bot (1-1 AI threads)', async () => { + const aiThread = new Types.ObjectId().toHexString(); + const group = new Types.ObjectId().toHexString(); + const { cron, find, create, generate } = makeCron({ + resolved: settings(), + activeIds: [aiThread, group], + aiThreadIds: [aiThread], + }); + await cron.run(AT_8); + expect(find).toHaveBeenCalledWith( + { + _id: { $in: [new Types.ObjectId(aiThread), new Types.ObjectId(group)] }, + participants: 'ai-bot-1', + type: { $ne: 'group' }, + }, + { projection: { _id: 1 } }, + ); + expect(create).toHaveBeenCalledTimes(1); + expect(create).toHaveBeenCalledWith({ conversationId: group, digestDate: '2026-06-22' }); + expect(generate).toHaveBeenCalledTimes(1); + }); + it('SKIPS generation on a duplicate-key (already digested ⇒ idempotent)', async () => { const dupErr = Object.assign(new Error('E11000 duplicate key'), { code: 11000 }); const create = jest.fn().mockRejectedValue(dupErr); diff --git a/apps/server/ai-service/src/scheduler/daily-digest.cron.ts b/apps/server/ai-service/src/scheduler/daily-digest.cron.ts index 37266dea..15d21206 100644 --- a/apps/server/ai-service/src/scheduler/daily-digest.cron.ts +++ b/apps/server/ai-service/src/scheduler/daily-digest.cron.ts @@ -8,6 +8,7 @@ import { DigestGeneratorService } from './digest-generator.service'; import { DigestLog, DigestLogDocument } from './digest-log.schema'; import { localHour, yesterdayWindow } from './digest-date.util'; import { safeTimeZone } from '../common/time-zone'; +import { toObjectIds } from '../common/object-id'; /** Mongo duplicate-key error code (unique-index idempotency guard). */ const DUP_KEY = 11000; @@ -122,6 +123,20 @@ export class DailyDigestCron { senderId: { $ne: this.botUserId }, recalled: { $ne: true }, }); - return (ids as unknown[]).map((id) => String(id)).filter(Boolean); + const activeIds = (ids as unknown[]).map((id) => String(id)).filter(Boolean); + + // 1-1 AI threads (direct/untyped conversation with the bot as participant) + // must never get a digest. Groups containing the bot are still digested. + const objectIds = toObjectIds(activeIds); + if (objectIds.length === 0) return activeIds; + const aiThreads = await this.connection + .collection('conversations') + .find( + { _id: { $in: objectIds }, participants: this.botUserId, type: { $ne: 'group' } }, + { projection: { _id: 1 } }, + ) + .toArray(); + const skip = new Set(aiThreads.map((c) => String(c._id))); + return activeIds.filter((id) => !skip.has(id)); } } From c2da58380b253c42b73560dc298f1b3ae16c7787 Mon Sep 17 00:00:00 2001 From: MITOM06 Date: Thu, 5 Nov 2026 18:42:55 +0700 Subject: [PATCH 04/12] feat(web): AI threads data layer (api, hooks, realtime cache, excludeAi) Co-Authored-By: Claude Opus 5.5 --- apps/web/lib/api/ai-threads.test.ts | 55 ++++++++++++++ apps/web/lib/api/ai-threads.ts | 16 +++++ apps/web/lib/api/chat.ts | 4 +- apps/web/lib/hooks/use-ai-threads.test.tsx | 40 +++++++++++ apps/web/lib/hooks/use-ai-threads.ts | 27 +++++++ apps/web/lib/hooks/use-open-ai-chat.test.tsx | 53 ++++++++++++++ apps/web/lib/hooks/use-open-ai-chat.ts | 39 +++++----- .../__tests__/conversation-cache.test.ts | 61 ++++++++++++++++ apps/web/lib/realtime/conversation-cache.ts | 72 +++++++++++++++++-- apps/web/lib/realtime/user-queue.ts | 2 + 10 files changed, 344 insertions(+), 25 deletions(-) create mode 100644 apps/web/lib/api/ai-threads.test.ts create mode 100644 apps/web/lib/api/ai-threads.ts create mode 100644 apps/web/lib/hooks/use-ai-threads.test.tsx create mode 100644 apps/web/lib/hooks/use-ai-threads.ts create mode 100644 apps/web/lib/hooks/use-open-ai-chat.test.tsx diff --git a/apps/web/lib/api/ai-threads.test.ts b/apps/web/lib/api/ai-threads.test.ts new file mode 100644 index 00000000..929a6571 --- /dev/null +++ b/apps/web/lib/api/ai-threads.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest' +import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios' +import { chatApi } from '@/lib/api/axios' +import { aiThreadsApi } from '@/lib/api/ai-threads' +import { chatService } from '@/lib/api/chat' +import type { Conversation } from '@/lib/api/types' + +interface Call { method?: string; url?: string; data?: unknown; params?: Record } +let calls: Call[] = [] +let saved: unknown +const thread = { id: 't1' } as Conversation + +beforeEach(() => { + calls = [] + saved = chatApi.defaults.adapter + chatApi.defaults.adapter = (config: InternalAxiosRequestConfig) => { + calls.push({ + method: config.method, + url: config.url, + data: typeof config.data === 'string' ? JSON.parse(config.data) : config.data, + params: config.params, + }) + const data = config.url === '/api/ai-threads' && config.method === 'get' + ? [thread] + : config.url === '/api/conversations' + ? { content: [], page: 0, size: 100, totalElements: 0, hasNext: false } + : thread + return Promise.resolve({ data, status: 200, statusText: 'OK', headers: {}, config } as AxiosResponse) + } +}) +afterEach(() => { + chatApi.defaults.adapter = saved as typeof chatApi.defaults.adapter +}) + +describe('aiThreadsApi', () => { + it('list GETs /api/ai-threads', async () => { + expect(await aiThreadsApi.list()).toEqual([thread]) + expect(calls[0]).toMatchObject({ method: 'get', url: '/api/ai-threads' }) + }) + it('create POSTs /api/ai-threads', async () => { + expect(await aiThreadsApi.create()).toEqual(thread) + expect(calls[0]).toMatchObject({ method: 'post', url: '/api/ai-threads' }) + }) + it('rename PATCHes /api/ai-threads/{id} with name', async () => { + await aiThreadsApi.rename('t1', 'Hello') + expect(calls[0]).toMatchObject({ method: 'patch', url: '/api/ai-threads/t1', data: { name: 'Hello' } }) + }) +}) + +describe('main conversations list', () => { + it('sends excludeAi=true', async () => { + await chatService.getConversations() + expect(calls[0].params).toMatchObject({ excludeAi: true }) + }) +}) diff --git a/apps/web/lib/api/ai-threads.ts b/apps/web/lib/api/ai-threads.ts new file mode 100644 index 00000000..c0c70edb --- /dev/null +++ b/apps/web/lib/api/ai-threads.ts @@ -0,0 +1,16 @@ +import { chatApi } from './axios' +import type { Conversation } from './types' + +/** ChatGPT-style AI threads: each "new chat" with the AI is its own chat-service conversation. */ +export const aiThreadsApi = { + /** Caller's threads, newest activity first (max 100, hidden ones excluded). */ + list: () => chatApi.get('/api/ai-threads').then((r) => r.data), + + create: () => chatApi.post('/api/ai-threads').then((r) => r.data), + + /** 400 `AI_THREAD_NAME_INVALID` unless 1–80 chars after trim. */ + rename: (id: string, name: string) => + chatApi + .patch(`/api/ai-threads/${encodeURIComponent(id)}`, { name }) + .then((r) => r.data), +} diff --git a/apps/web/lib/api/chat.ts b/apps/web/lib/api/chat.ts index 2a5317c5..2c5e13c7 100644 --- a/apps/web/lib/api/chat.ts +++ b/apps/web/lib/api/chat.ts @@ -112,7 +112,9 @@ export const chatService = { // ── Conversations ────────────────────────────────────────────────────────── /** All of the caller's conversations; `archived=true` → only the archived ones. */ - getConversations: (archived = false) => listAllConversations({ archived }), + getConversations: (archived = false) => + // AI threads live in their own list (`['ai-threads']`), never in the main one. + listAllConversations(archived ? { archived } : { archived, excludeAi: true }), getConversation: (id: string) => chatApi.get(`/api/conversations/${id}`).then((r) => r.data), diff --git a/apps/web/lib/hooks/use-ai-threads.test.tsx b/apps/web/lib/hooks/use-ai-threads.test.tsx new file mode 100644 index 00000000..ba555656 --- /dev/null +++ b/apps/web/lib/hooks/use-ai-threads.test.tsx @@ -0,0 +1,40 @@ +import { describe, it, expect, vi } from 'vitest' +import { renderHook, act, waitFor } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { ReactNode } from 'react' +import type { Conversation } from '@/lib/api/types' + +const rename = vi.fn() +const create = vi.fn() +vi.mock('@/lib/api/ai-threads', () => ({ + aiThreadsApi: { list: vi.fn().mockResolvedValue([]), create: () => create(), rename: (...a: unknown[]) => rename(...a) }, +})) +import { useCreateAiThread, useRenameAiThread } from '@/lib/hooks/use-ai-threads' + +function setup(initial: Conversation[]) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + qc.setQueryData(['ai-threads'], initial) + const Wrap = ({ children }: { children: ReactNode }) => ( + {children} + ) + return { qc, Wrap } +} + +describe('ai thread mutations', () => { + it('create inserts at top and returns conversation', async () => { + create.mockResolvedValue({ id: 'n' }) + const { qc, Wrap } = setup([{ id: 'a' } as Conversation]) + const { result } = renderHook(() => useCreateAiThread(), { wrapper: Wrap }) + let out: Conversation | undefined + await act(async () => { out = await result.current.mutateAsync() }) + expect(out?.id).toBe('n') + expect(qc.getQueryData(['ai-threads'])?.map((c) => c.id)).toEqual(['n', 'a']) + }) + it('rename updates the cached thread name', async () => { + rename.mockResolvedValue({ id: 'a', name: 'X' }) + const { qc, Wrap } = setup([{ id: 'a', name: null } as Conversation]) + const { result } = renderHook(() => useRenameAiThread(), { wrapper: Wrap }) + await act(async () => { await result.current.mutateAsync({ id: 'a', name: 'X' }) }) + await waitFor(() => expect(qc.getQueryData(['ai-threads'])?.[0].name).toBe('X')) + }) +}) diff --git a/apps/web/lib/hooks/use-ai-threads.ts b/apps/web/lib/hooks/use-ai-threads.ts new file mode 100644 index 00000000..de4abd03 --- /dev/null +++ b/apps/web/lib/hooks/use-ai-threads.ts @@ -0,0 +1,27 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { aiThreadsApi } from '@/lib/api/ai-threads' +import { AI_THREADS_KEY, upsertAiThread } from '@/lib/realtime/conversation-cache' + +export function useAiThreads() { + return useQuery({ + queryKey: AI_THREADS_KEY, + queryFn: () => aiThreadsApi.list(), + staleTime: 60 * 1000, + }) +} + +export function useCreateAiThread() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: () => aiThreadsApi.create(), + onSuccess: (conv) => upsertAiThread(queryClient, conv), + }) +} + +export function useRenameAiThread() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ id, name }: { id: string; name: string }) => aiThreadsApi.rename(id, name), + onSuccess: (conv) => upsertAiThread(queryClient, conv, { keepPosition: true }), + }) +} diff --git a/apps/web/lib/hooks/use-open-ai-chat.test.tsx b/apps/web/lib/hooks/use-open-ai-chat.test.tsx new file mode 100644 index 00000000..f68e0c5a --- /dev/null +++ b/apps/web/lib/hooks/use-open-ai-chat.test.tsx @@ -0,0 +1,53 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { renderHook, act } from '@testing-library/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { ReactNode } from 'react' +import type { Conversation } from '@/lib/api/types' + +const push = vi.fn() +const list = vi.fn() +const create = vi.fn() +vi.mock('next/navigation', () => ({ useRouter: () => ({ push }) })) +vi.mock('next-intl', () => ({ useTranslations: () => (k: string) => k })) +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) +vi.mock('@/lib/api/ai-threads', () => ({ + aiThreadsApi: { list: () => list(), create: () => create(), rename: vi.fn() }, +})) + +import { useOpenAiChat } from '@/lib/hooks/use-open-ai-chat' + +function wrapper() { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return { + qc, + Wrap: ({ children }: { children: ReactNode }) => ( + {children} + ), + } +} + +beforeEach(() => { + push.mockReset() + list.mockReset() + create.mockReset() +}) + +describe('useOpenAiChat', () => { + it('opens the newest thread', async () => { + list.mockResolvedValue([{ id: 'new' }, { id: 'old' }] as Conversation[]) + const { Wrap } = wrapper() + const { result } = renderHook(() => useOpenAiChat(), { wrapper: Wrap }) + await act(() => result.current.openAiChat()) + expect(push).toHaveBeenCalledWith('/conversations/new') + expect(create).not.toHaveBeenCalled() + }) + it('creates a thread when none exist', async () => { + list.mockResolvedValue([]) + create.mockResolvedValue({ id: 'fresh' } as Conversation) + const { Wrap, qc } = wrapper() + const { result } = renderHook(() => useOpenAiChat(), { wrapper: Wrap }) + await act(() => result.current.openAiChat()) + expect(push).toHaveBeenCalledWith('/conversations/fresh') + expect(qc.getQueryData(['ai-threads'])?.[0].id).toBe('fresh') + }) +}) diff --git a/apps/web/lib/hooks/use-open-ai-chat.ts b/apps/web/lib/hooks/use-open-ai-chat.ts index 4dcc7ae8..093871ab 100644 --- a/apps/web/lib/hooks/use-open-ai-chat.ts +++ b/apps/web/lib/hooks/use-open-ai-chat.ts @@ -2,42 +2,45 @@ import { useState, useCallback } from 'react' import { useRouter } from 'next/navigation' +import { useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { useTranslations } from 'next-intl' -import { chatService } from '@/lib/api/chat' +import { aiThreadsApi } from '@/lib/api/ai-threads' +import { AI_BOT_ID } from '@/lib/constants' +import { AI_THREADS_KEY, upsertAiThread } from '@/lib/realtime/conversation-cache' +import type { Conversation } from '@/lib/api/types' -export const AI_BOT_ID = 'ai-bot-000000000000000000000001' +export { AI_BOT_ID } -// Shared "Start chat with PON AI" logic used by both the AI Hub hero CTA and -// (historically) the conversation-list Bot button. Creates the AI conversation -// and navigates to it, with the 409 (already-exists) fallback that navigates to -// the existing conversation. Mirrors Flutter `getOrCreateConversation(kAiBotUserId)`. +// Shared "Start chat with PON AI" logic (AI Hub hero CTA). Opens the most recent +// AI thread, or creates the first one when the user has none. export function useOpenAiChat() { const t = useTranslations('chat') const router = useRouter() + const queryClient = useQueryClient() const [loading, setLoading] = useState(false) const openAiChat = useCallback(async () => { if (loading) return setLoading(true) try { - const conv = await chatService.createConversation(AI_BOT_ID) - router.push(`/conversations/${conv.id}`) - } catch (err) { - // 409 = conversation already exists — find and navigate to it. - const isConflict = (err as { response?: { status?: number } })?.response?.status === 409 - if (isConflict) { - const body = (err as { response?: { data?: { conversationId?: string } } })?.response?.data - if (body?.conversationId) { - router.push(`/conversations/${body.conversationId}`) - return - } + const threads = await queryClient.fetchQuery({ + queryKey: AI_THREADS_KEY, + queryFn: () => aiThreadsApi.list(), + staleTime: 0, + }) + let target = threads[0] + if (!target) { + target = await aiThreadsApi.create() + upsertAiThread(queryClient, target) } + router.push(`/conversations/${target.id}`) + } catch { toast.error(t('aiOpenError')) } finally { setLoading(false) } - }, [loading, router, t]) + }, [loading, queryClient, router, t]) return { openAiChat, loading } } diff --git a/apps/web/lib/realtime/__tests__/conversation-cache.test.ts b/apps/web/lib/realtime/__tests__/conversation-cache.test.ts index ee55718d..fba31fea 100644 --- a/apps/web/lib/realtime/__tests__/conversation-cache.test.ts +++ b/apps/web/lib/realtime/__tests__/conversation-cache.test.ts @@ -9,6 +9,7 @@ import { QueryClient } from '@tanstack/react-query' import { ARCHIVED_CONVERSATIONS_KEY, CONVERSATIONS_KEY, + applyIncomingPreview, applyOwnConversationUpdate, applySharedConversationUpdate, isConversationMuted, @@ -154,3 +155,63 @@ describe('conversation cache merge rules', () => { expect(isConversationMuted(undefined, now)).toBe(false) }) }) + +describe('AI threads cache', () => { + const AI = 'ai-bot-000000000000000000000001' + const aiConv = (over: Partial = {}) => + conv({ id: 'ai1', type: 'direct', participants: [ME, AI], name: null, ...over }) + const mk = () => { + const qc = new QueryClient() + qc.setQueryData(CONVERSATIONS_KEY, { + content: [conv()], page: 0, size: 1, totalElements: 1, hasNext: false, + }) + return qc + } + + it('user-queue update inserts an unknown AI thread at top of ai-threads, not the main list', () => { + const qc = mk() + qc.setQueryData(['ai-threads'], [aiConv({ id: 'old' })]) + applyOwnConversationUpdate(qc, aiConv(), ME) + expect(qc.getQueryData(['ai-threads'])?.map((c) => c.id)).toEqual(['ai1', 'old']) + expect(qc.getQueryData(CONVERSATIONS_KEY)?.content.map((c) => c.id)).toEqual(['c1']) + expect(qc.getQueryState(CONVERSATIONS_KEY)?.isInvalidated).toBe(false) + }) + + it('user-queue update replaces a known AI thread in place', () => { + const qc = mk() + qc.setQueryData(['ai-threads'], [aiConv({ id: 'x' }), aiConv({ name: 'a' })]) + applyOwnConversationUpdate(qc, aiConv({ name: 'b' }), ME) + expect(qc.getQueryData(['ai-threads'])?.map((c) => c.name)).toEqual([null, 'b']) + }) + + it('shared update (auto-title) merges into the matching thread', () => { + const qc = mk() + qc.setQueryData(['ai-threads'], [aiConv({ name: null, unreadCount: 3 })]) + applySharedConversationUpdate(qc, shared({ id: 'ai1', type: 'direct', participants: [ME, AI], name: 'Title' }), ME) + const t = qc.getQueryData(['ai-threads'])?.[0] + expect(t?.name).toBe('Title') + expect(t?.unreadCount).toBe(3) + expect(qc.getQueryState(CONVERSATIONS_KEY)?.isInvalidated).toBe(false) + }) + + it('removed participant drops thread from ai-threads', () => { + const qc = mk() + qc.setQueryData(['ai-threads'], [aiConv()]) + applySharedConversationUpdate(qc, shared({ id: 'ai1', participants: [AI] }), ME) + expect(qc.getQueryData(['ai-threads'])).toEqual([]) + }) + + it('incoming message moves the AI thread to top', () => { + const qc = mk() + qc.setQueryData(['ai-threads'], [aiConv({ id: 'other' }), aiConv({ lastMessageAt: '2026-10-05T10:00:00Z' })]) + const ok = applyIncomingPreview( + qc, + { conversationId: 'ai1', messageId: 'm9', createdAt: '2026-10-06T10:00:00Z', senderId: AI, content: 'yo' }, + false, + ) + expect(ok).toBe(true) + const list = qc.getQueryData(['ai-threads']) + expect(list?.map((c) => c.id)).toEqual(['ai1', 'other']) + expect(list?.[0].lastMessage?.content).toBe('yo') + }) +}) diff --git a/apps/web/lib/realtime/conversation-cache.ts b/apps/web/lib/realtime/conversation-cache.ts index 680dd408..bd502164 100644 --- a/apps/web/lib/realtime/conversation-cache.ts +++ b/apps/web/lib/realtime/conversation-cache.ts @@ -1,4 +1,5 @@ import type { QueryClient } from '@tanstack/react-query' +import { AI_BOT_ID } from '@/lib/constants' import { SHARED_CONVERSATION_FIELDS, type Conversation, @@ -25,6 +26,14 @@ export const ARCHIVED_CONVERSATIONS_KEY = ['conversations', 'archived'] as const const BLOCKED_CONVERSATIONS_KEY = ['conversations', 'blocked'] as const const LEGACY_BLOCKED_KEY = ['blocked-conversations'] as const +/** The caller's AI threads (a plain `Conversation[]`, newest activity first). */ +export const AI_THREADS_KEY = ['ai-threads'] as const + +/** An AI conversation (thread): the AI bot is a participant. */ +export function isAiConversation(c: Pick | undefined): boolean { + return Array.isArray(c?.participants) && c.participants.includes(AI_BOT_ID) +} + const LIST_KEYS = [CONVERSATIONS_KEY, ARCHIVED_CONVERSATIONS_KEY, BLOCKED_CONVERSATIONS_KEY] as const const conversationKey = (id: string) => ['conversation', id] as const @@ -89,6 +98,32 @@ function listContains(queryClient: QueryClient, key: readonly unknown[], id: str return data?.content.some((c) => c.id === id) ?? false } +function patchAiThreads( + queryClient: QueryClient, + fn: (list: Conversation[]) => Conversation[], +): void { + queryClient.setQueryData(AI_THREADS_KEY, (old) => (old ? fn(old) : old)) +} + +function aiThreadsContain(queryClient: QueryClient, id: string): boolean { + return queryClient.getQueryData(AI_THREADS_KEY)?.some((c) => c.id === id) ?? false +} + +/** Insert (top) or replace a thread in `['ai-threads']`; no-op while that query is not loaded. */ +export function upsertAiThread( + queryClient: QueryClient, + conv: Conversation, + opts: { keepPosition?: boolean } = {}, +): void { + patchAiThreads(queryClient, (list) => + list.some((c) => c.id === conv.id) + ? opts.keepPosition + ? list.map((c) => (c.id === conv.id ? conv : c)) + : [conv, ...list.filter((c) => c.id !== conv.id)] + : [conv, ...list], + ) +} + /** The cached copy of a conversation (detail query first, then any list). */ export function findCachedConversation( queryClient: QueryClient, @@ -100,12 +135,13 @@ export function findCachedConversation( const hit = queryClient.getQueryData(key)?.content.find((c) => c.id === id) if (hit) return hit } - return undefined + return queryClient.getQueryData(AI_THREADS_KEY)?.find((c) => c.id === id) } /** Remove a conversation (and its thread) from every cache. */ export function dropConversation(queryClient: QueryClient, id: string): void { for (const key of LIST_KEYS) patchList(queryClient, key, (list) => list.filter((c) => c.id !== id)) + patchAiThreads(queryClient, (list) => list.filter((c) => c.id !== id)) queryClient.removeQueries({ queryKey: conversationKey(id), exact: true }) queryClient.removeQueries({ queryKey: ['messages', id], exact: true }) } @@ -133,6 +169,14 @@ export function applySharedConversationUpdate( queryClient.setQueryData(conversationKey(shared.id), mergeSharedConversation(one, shared)) found = true } + if (aiThreadsContain(queryClient, shared.id)) { + found = true + patchAiThreads(queryClient, (list) => + list + .map((c) => (c.id === shared.id ? mergeSharedConversation(c, shared) : c)) + .sort(byNewestActivity), + ) + } for (const key of LIST_KEYS) { if (!listContains(queryClient, key, shared.id)) continue found = true @@ -143,7 +187,11 @@ export function applySharedConversationUpdate( ) } if (!found) { - queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY, exact: true }) + // AI threads never belong in the main list (fetched with excludeAi=true). + queryClient.invalidateQueries({ + queryKey: isAiConversation(shared) ? AI_THREADS_KEY : CONVERSATIONS_KEY, + exact: true, + }) return 'unknown' } return 'merged' @@ -168,6 +216,12 @@ export function applyOwnConversationUpdate( queryClient.setQueryData(conversationKey(full.id), full) } + if (isAiConversation(full)) { + // AI threads live only in `['ai-threads']`: insert a new one at the top. + upsertAiThread(queryClient, full, { keepPosition: aiThreadsContain(queryClient, full.id) }) + return previous ? 'merged' : 'unknown' + } + const replace = (list: Conversation[]) => list.map((c) => (c.id === full.id ? full : c)) if (listContains(queryClient, CONVERSATIONS_KEY, full.id)) { patchList(queryClient, CONVERSATIONS_KEY, replace) @@ -245,8 +299,10 @@ export function applyIncomingPreview( const { conversationId, messageId, createdAt } = event if (!messageId || !createdAt || !Number.isFinite(Date.parse(createdAt))) return false const list = queryClient.getQueryData(CONVERSATIONS_KEY) - const conv = list?.content.find((c) => c.id === conversationId) - if (!list || !conv) return false + const aiThreads = queryClient.getQueryData(AI_THREADS_KEY) + const aiConv = aiThreads?.find((c) => c.id === conversationId) + const conv = aiConv ?? list?.content.find((c) => c.id === conversationId) + if (!conv || (!aiConv && !list)) return false // Already applied (the open thread or a duplicate frame), or older than the row. if (conv.lastMessage?.messageId === messageId) return true if (conv.lastMessageAt && Date.parse(conv.lastMessageAt) > Date.parse(createdAt)) return true @@ -263,9 +319,13 @@ export function applyIncomingPreview( lastMessageAt: createdAt, unreadCount: viewing ? conv.unreadCount : (conv.unreadCount ?? 0) + 1, } + if (aiConv) { + upsertAiThread(queryClient, updated) + return true + } queryClient.setQueryData(CONVERSATIONS_KEY, { - ...list, - content: [updated, ...list.content.filter((c) => c.id !== conversationId)], + ...list!, + content: [updated, ...list!.content.filter((c) => c.id !== conversationId)], }) return true } diff --git a/apps/web/lib/realtime/user-queue.ts b/apps/web/lib/realtime/user-queue.ts index 2312ae62..3d18b28f 100644 --- a/apps/web/lib/realtime/user-queue.ts +++ b/apps/web/lib/realtime/user-queue.ts @@ -6,6 +6,7 @@ import { safeDisplayName } from '@/lib/chat/names' import { getNickname } from '@/lib/nicknames' import { CONVERSATIONS_KEY, + AI_THREADS_KEY, applyIncomingPreview, applyOwnConversationUpdate, findCachedConversation, @@ -148,6 +149,7 @@ export function handleUserQueueEvent(event: UserQueueEvent, ctx: UserQueueContex ) ) { ctx.queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY }) + ctx.queryClient.invalidateQueries({ queryKey: AI_THREADS_KEY }) } if (!ctx.notificationsEnabled()) return if (ctx.isViewingConversation(event.conversationId)) return From 0a890b6999b846cb3fc110811135090af869b5da Mon Sep 17 00:00:00 2001 From: MITOM06 Date: Thu, 5 Nov 2026 18:45:43 +0700 Subject: [PATCH 05/12] fix(web): route AI thread cache invalidation, keep ai-threads loaded, excludeAi on archived Co-Authored-By: Claude Opus 5.5 --- .../lib/api/__tests__/chat-pagination.test.ts | 4 +-- apps/web/lib/api/chat.ts | 2 +- .../__tests__/use-message-cache.test.tsx | 19 +++++++++++++- apps/web/lib/hooks/use-message-cache.ts | 25 ++++++++++++++++++- .../lib/hooks/use-realtime-notifications.ts | 6 ++++- .../lib/realtime/__tests__/user-queue.test.ts | 25 +++++++++++++++++++ apps/web/lib/realtime/user-queue.ts | 12 +++++++-- 7 files changed, 85 insertions(+), 8 deletions(-) diff --git a/apps/web/lib/api/__tests__/chat-pagination.test.ts b/apps/web/lib/api/__tests__/chat-pagination.test.ts index 93e41dbb..a3a65876 100644 --- a/apps/web/lib/api/__tests__/chat-pagination.test.ts +++ b/apps/web/lib/api/__tests__/chat-pagination.test.ts @@ -49,8 +49,8 @@ describe('chatService pagination', () => { const res = await chatService.getConversations(true) expect(res.content.map((c) => c.id)).toEqual(['a', 'b', 'c']) expect(calls).toEqual([ - { archived: true, page: 0, size: 100 }, - { archived: true, page: 1, size: 100 }, + { archived: true, excludeAi: true, page: 0, size: 100 }, + { archived: true, excludeAi: true, page: 1, size: 100 }, ]) }) diff --git a/apps/web/lib/api/chat.ts b/apps/web/lib/api/chat.ts index 2c5e13c7..99fcd000 100644 --- a/apps/web/lib/api/chat.ts +++ b/apps/web/lib/api/chat.ts @@ -114,7 +114,7 @@ export const chatService = { /** All of the caller's conversations; `archived=true` → only the archived ones. */ getConversations: (archived = false) => // AI threads live in their own list (`['ai-threads']`), never in the main one. - listAllConversations(archived ? { archived } : { archived, excludeAi: true }), + listAllConversations({ archived, excludeAi: true }), getConversation: (id: string) => chatApi.get(`/api/conversations/${id}`).then((r) => r.data), diff --git a/apps/web/lib/hooks/__tests__/use-message-cache.test.tsx b/apps/web/lib/hooks/__tests__/use-message-cache.test.tsx index a85db931..9676b602 100644 --- a/apps/web/lib/hooks/__tests__/use-message-cache.test.tsx +++ b/apps/web/lib/hooks/__tests__/use-message-cache.test.tsx @@ -17,7 +17,7 @@ import { type InfiniteData, } from '@tanstack/react-query' import { reconcileThread, useMessageCache } from '@/lib/hooks/use-message-cache' -import type { ConversationsResponse, Message, MessagesResponse } from '@/lib/api/types' +import type { Conversation, ConversationsResponse, Message, MessagesResponse } from '@/lib/api/types' const CONV = 'conv-1' const KEY = ['messages', CONV] as const @@ -228,4 +228,21 @@ describe('useMessageCache', () => { const next = reconcileThread(old, [msg('a1', { type: 'ai', content: 'final' })]) expect(next?.pages[0].content[0]).toMatchObject({ content: 'final', sources }) }) + + it('AI thread message bumps ai-threads preview without invalidating the main list', () => { + const AI = 'ai-bot-000000000000000000000001' + env.qc.setQueryData(['conversations'], { + content: [{ id: 'other' } as Conversation], page: 0, size: 1, totalElements: 1, hasNext: false, + }) + env.qc.setQueryData(['ai-threads'], [ + { id: 'x', participants: ['u', AI] } as Conversation, + { id: CONV, participants: ['u', AI], lastMessageAt: '2026-06-19T09:00:00.000Z' } as Conversation, + ]) + seed(env.qc, []) + act(() => env.result.current.appendMessage(msg('m9', { content: 'yo' }))) + const list = env.qc.getQueryData(['ai-threads']) + expect(list?.map((c) => c.id)).toEqual([CONV, 'x']) + expect(list?.[0]?.lastMessage?.content).toBe('yo') + expect(env.qc.getQueryState(['conversations'])?.isInvalidated).toBe(false) + }) }) diff --git a/apps/web/lib/hooks/use-message-cache.ts b/apps/web/lib/hooks/use-message-cache.ts index 9228a3b8..52374cc3 100644 --- a/apps/web/lib/hooks/use-message-cache.ts +++ b/apps/web/lib/hooks/use-message-cache.ts @@ -9,7 +9,14 @@ import type { Message, MessagesResponse, } from '@/lib/api/types' -import { CONVERSATIONS_KEY, lastMessageOf, markPreviewRecalled } from '@/lib/realtime/conversation-cache' +import { + CONVERSATIONS_KEY, + findCachedConversation, + isAiConversation, + lastMessageOf, + markPreviewRecalled, + upsertAiThread, +} from '@/lib/realtime/conversation-cache' import { withActionStatus, type ActionStatus } from '@/lib/ai/pending-actions' type Pages = InfiniteData @@ -60,6 +67,22 @@ export function reconcileThread(old: Pages | undefined, incoming: Message[]): Pa /** Refresh the conversation-list preview for a message without refetching the list. */ function bumpListPreview(queryClient: QueryClient, incoming: Message): void { + // AI threads live in ['ai-threads'], never in the main list: bump them there + // and never refetch the main list because of them. + const cached = findCachedConversation(queryClient, incoming.conversationId) + if (isAiConversation(cached)) { + if ( + cached && + !(cached.lastMessageAt && Date.parse(cached.lastMessageAt) > Date.parse(incoming.createdAt)) + ) { + upsertAiThread(queryClient, { + ...cached, + lastMessage: lastMessageOf(incoming), + lastMessageAt: incoming.createdAt, + }) + } + return + } // On busy threads this fires per message, so invalidating (refetching the // whole list) every time was a refetch storm. Fall back to invalidate only // when the list cache is empty or doesn't yet contain this conversation diff --git a/apps/web/lib/hooks/use-realtime-notifications.ts b/apps/web/lib/hooks/use-realtime-notifications.ts index a77013e8..748b32bc 100644 --- a/apps/web/lib/hooks/use-realtime-notifications.ts +++ b/apps/web/lib/hooks/use-realtime-notifications.ts @@ -7,9 +7,10 @@ import { toast } from 'sonner' import { useLocale, useTranslations } from 'next-intl' import { useAuthStore } from '@/lib/store/auth.store' import { useNotificationPrefs } from '@/lib/store/notification-prefs' +import { useAiThreads } from '@/lib/hooks/use-ai-threads' import { stompService } from '@/lib/stomp/client' import { refreshClaims } from '@/lib/realtime/claims' -import { CONVERSATIONS_KEY } from '@/lib/realtime/conversation-cache' +import { AI_THREADS_KEY, CONVERSATIONS_KEY } from '@/lib/realtime/conversation-cache' import { createPresenceHandler, handleWebRtcFrame } from '@/lib/realtime/session-handlers' import { presentNotice } from '@/lib/realtime/present-notice' import { handleMeetingQueueEvent, type MeetingQueueContext } from '@/lib/realtime/meeting-queue' @@ -30,6 +31,8 @@ const conversationPath = (id: string) => `/conversations/${id}` export function useRealtimeNotifications(): void { const router = useRouter() const queryClient = useQueryClient() + // Keep ['ai-threads'] loaded app-wide so realtime AI updates always have a cache to land in. + useAiThreads() // Depend on a STABLE boolean, not the token value: the token is rotated on // every ~15-min refresh (and on every 401-refresh), and a value dependency // here would tear down + rebuild the STOMP singleton on each rotation — a @@ -137,6 +140,7 @@ export function useRealtimeNotifications(): void { if (connected) refreshTransport() if (connected && !wasConnected && connectedBefore) { queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY }) + queryClient.invalidateQueries({ queryKey: AI_THREADS_KEY }) queryClient.invalidateQueries({ queryKey: ['notifications'] }) } if (connected) connectedBefore = true diff --git a/apps/web/lib/realtime/__tests__/user-queue.test.ts b/apps/web/lib/realtime/__tests__/user-queue.test.ts index ad16ded0..7f8ba7fe 100644 --- a/apps/web/lib/realtime/__tests__/user-queue.test.ts +++ b/apps/web/lib/realtime/__tests__/user-queue.test.ts @@ -249,3 +249,28 @@ describe('system-notice NEW_MESSAGE payload', () => { expect(humanizeLastMessage(row().lastMessage, t, { currentUserId: 'me' })).toBe('systemGroupCreated') }) }) + +describe('invalidation routing on a preview miss', () => { + const AI = 'ai-bot-000000000000000000000001' + const aiConv = { id: 'ai1', participants: ['me', AI], type: 'direct' } as Conversation + const aiEvent = { ...newMessage, conversationId: 'ai1', senderId: AI } + + it('AI message with ai-threads loaded: no main-list invalidation', () => { + const qc = new QueryClient() + seedConversation(qc, {}) + qc.setQueryData(['ai-threads'], [aiConv]) + // no messageId/createdAt -> applyIncomingPreview misses + handleUserQueueEvent(aiEvent, ctx(qc)) + expect(qc.getQueryState(CONVERSATIONS_KEY)?.isInvalidated).toBe(false) + expect(qc.getQueryState(['ai-threads'])?.isInvalidated).toBe(true) + }) + + it('known non-AI message miss: no ai-threads invalidation', () => { + const qc = new QueryClient() + seedConversation(qc, {}) + qc.setQueryData(['ai-threads'], [aiConv]) + handleUserQueueEvent(newMessage, ctx(qc)) + expect(qc.getQueryState(['ai-threads'])?.isInvalidated).toBe(false) + expect(qc.getQueryState(CONVERSATIONS_KEY)?.isInvalidated).toBe(true) + }) +}) diff --git a/apps/web/lib/realtime/user-queue.ts b/apps/web/lib/realtime/user-queue.ts index 3d18b28f..ecc486a5 100644 --- a/apps/web/lib/realtime/user-queue.ts +++ b/apps/web/lib/realtime/user-queue.ts @@ -10,6 +10,7 @@ import { applyIncomingPreview, applyOwnConversationUpdate, findCachedConversation, + isAiConversation, isConversationMuted, } from './conversation-cache' @@ -148,8 +149,15 @@ export function handleUserQueueEvent(event: UserQueueEvent, ctx: UserQueueContex ctx.isViewingConversation(event.conversationId), ) ) { - ctx.queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY }) - ctx.queryClient.invalidateQueries({ queryKey: AI_THREADS_KEY }) + // Route the refetch to the list the chat belongs to; only a chat + // unknown everywhere (rare) may invalidate both. + const known = findCachedConversation(ctx.queryClient, event.conversationId) + if (!known || !isAiConversation(known)) { + ctx.queryClient.invalidateQueries({ queryKey: CONVERSATIONS_KEY }) + } + if (!known || isAiConversation(known)) { + ctx.queryClient.invalidateQueries({ queryKey: AI_THREADS_KEY }) + } } if (!ctx.notificationsEnabled()) return if (ctx.isViewingConversation(event.conversationId)) return From 4f1159f90211f5f92b4cd1c84e63a5c7b8b63cf4 Mon Sep 17 00:00:00 2001 From: MITOM06 Date: Thu, 5 Nov 2026 18:49:26 +0700 Subject: [PATCH 06/12] feat(web): ChatGPT-style AI threads sidebar Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(main)/ai-hub/page.tsx | 7 + apps/web/app/(main)/layout.tsx | 34 ++-- apps/web/components/ai/AiThreadItem.tsx | 90 +++++++++++ apps/web/components/ai/AiThreadList.tsx | 121 ++++++++++++++ .../ai/__tests__/AiThreadList.test.tsx | 148 ++++++++++++++++++ apps/web/components/chat/AiSessionPanel.tsx | 98 ------------ .../components/chat/ConversationHeader.tsx | 30 +++- .../chat/ConversationSettingsDrawer.tsx | 6 - apps/web/lib/api/ai-session.ts | 36 ----- apps/web/messages/en.json | 18 +++ apps/web/messages/es.json | 18 +++ apps/web/messages/fr.json | 18 +++ apps/web/messages/ja.json | 18 +++ apps/web/messages/ko.json | 18 +++ apps/web/messages/vi.json | 18 +++ apps/web/messages/zh.json | 18 +++ 16 files changed, 542 insertions(+), 154 deletions(-) create mode 100644 apps/web/components/ai/AiThreadItem.tsx create mode 100644 apps/web/components/ai/AiThreadList.tsx create mode 100644 apps/web/components/ai/__tests__/AiThreadList.test.tsx delete mode 100644 apps/web/components/chat/AiSessionPanel.tsx delete mode 100644 apps/web/lib/api/ai-session.ts diff --git a/apps/web/app/(main)/ai-hub/page.tsx b/apps/web/app/(main)/ai-hub/page.tsx index c4f32954..0319d046 100644 --- a/apps/web/app/(main)/ai-hub/page.tsx +++ b/apps/web/app/(main)/ai-hub/page.tsx @@ -14,6 +14,7 @@ import { } from 'lucide-react' import { Button } from '@/components/ui/button' import { AiHubCard } from '@/components/ai/AiHubCard' +import { AiThreadList } from '@/components/ai/AiThreadList' import { useOpenAiChat } from '@/lib/hooks/use-open-ai-chat' export default function AiHubPage() { @@ -62,6 +63,12 @@ export default function AiHubPage() { + {/* Mobile: the aside is hidden, so the thread list (new chat, switch, + back to messages) lives here. Desktop shows it in the sidebar. */} +
+ +
+ {/* Destination cards */}
- {/* Horizontal presence row doesn't fit the compact rail — hide it. */} -
- -
- - + {showAiThreads ? ( + + ) : ( + <> + {/* Horizontal presence row doesn't fit the compact rail — hide it. */} +
+ +
+ + + + )}
{/* Bottom cluster — AI Hub launcher sits directly above the account anchor (desktop). */} @@ -219,7 +235,7 @@ function MainShell({ children }: { children: React.ReactNode }) { as="main" className={cn( 'flex-1 overflow-hidden flex-col', - showSidebar && !isConversationOpen ? 'hidden md:flex' : 'flex', + showSidebar && !isConversationOpen && !isAiHub ? 'hidden md:flex' : 'flex', )} > {children} diff --git a/apps/web/components/ai/AiThreadItem.tsx b/apps/web/components/ai/AiThreadItem.tsx new file mode 100644 index 00000000..dcb801c2 --- /dev/null +++ b/apps/web/components/ai/AiThreadItem.tsx @@ -0,0 +1,90 @@ +'use client' + +import { useState } from 'react' +import Link from 'next/link' +import { useTranslations } from 'next-intl' +import { Check, Pencil, Trash2, X } from 'lucide-react' +import { cn } from '@/lib/utils' +import type { Conversation } from '@/lib/api/types' + +interface Props { + thread: Conversation + active: boolean + /** Resolves when the rename succeeded (editor closes), rejects/returns false to stay open. */ + onRename: (id: string, name: string) => Promise + onDelete: (thread: Conversation) => void +} + +export function AiThreadItem({ thread, active, onRename, onDelete }: Props) { + const t = useTranslations('aiThreads') + const [editing, setEditing] = useState(false) + const [draft, setDraft] = useState('') + const title = thread.name?.trim() || t('untitled') + + const startEdit = () => { + setDraft(thread.name ?? '') + setEditing(true) + } + const save = async () => { + const name = draft.trim() + if (name === (thread.name ?? '')) return setEditing(false) + if (await onRename(thread.id, name)) setEditing(false) + } + + if (editing) { + return ( +
+ setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') void save() + else if (e.key === 'Escape') setEditing(false) + }} + className="min-w-0 flex-1 rounded-md border border-border bg-background px-2 py-1 text-sm outline-none focus-visible:ring-2 focus-visible:ring-primary/50" + /> + + +
+ ) + } + + return ( +
+ + {title} + + {/* Touch has no hover: always visible below md, hover/focus-revealed on desktop. */} +
+ + +
+
+ ) +} diff --git a/apps/web/components/ai/AiThreadList.tsx b/apps/web/components/ai/AiThreadList.tsx new file mode 100644 index 00000000..795c7659 --- /dev/null +++ b/apps/web/components/ai/AiThreadList.tsx @@ -0,0 +1,121 @@ +'use client' + +import { useState } from 'react' +import Link from 'next/link' +import { useRouter, usePathname } from 'next/navigation' +import { useQueryClient } from '@tanstack/react-query' +import { useTranslations } from 'next-intl' +import { toast } from 'sonner' +import { ArrowLeft, Loader2, Plus } from 'lucide-react' +import { ConfirmDialog } from '@/components/common/ConfirmDialog' +import { AiThreadItem } from '@/components/ai/AiThreadItem' +import { chatService } from '@/lib/api/chat' +import { parseChatError } from '@/lib/api/chat-errors' +import { useAiThreads, useCreateAiThread, useRenameAiThread } from '@/lib/hooks/use-ai-threads' +import { dropConversation } from '@/lib/realtime/conversation-cache' +import type { Conversation } from '@/lib/api/types' + +/** + * ChatGPT-style sidebar: every AI "new chat" is its own conversation. Replaces the + * normal conversation list while an AI thread (or the AI hub) is open. + */ +export function AiThreadList() { + const t = useTranslations('aiThreads') + const router = useRouter() + const pathname = usePathname() + const queryClient = useQueryClient() + const { data: threads, isLoading, isError } = useAiThreads() + const create = useCreateAiThread() + const rename = useRenameAiThread() + const [pendingDelete, setPendingDelete] = useState(null) + + const openId = /^\/conversations\/([^/]+)/.exec(pathname)?.[1] + + const handleCreate = async () => { + try { + const conv = await create.mutateAsync() + router.push(`/conversations/${conv.id}`) + } catch { + toast.error(t('createFailed')) + } + } + + const handleRename = async (id: string, name: string): Promise => { + try { + await rename.mutateAsync({ id, name }) + return true + } catch (err) { + toast.error(parseChatError(err).code === 'AI_THREAD_NAME_INVALID' ? t('nameInvalid') : t('renameFailed')) + return false + } + } + + const handleConfirmDelete = async () => { + const target = pendingDelete + if (!target) return + setPendingDelete(null) + const list = threads ?? [] + const idx = list.findIndex((c) => c.id === target.id) + const next = list[idx + 1] ?? list[idx - 1] + try { + await chatService.deleteConversation(target.id) + dropConversation(queryClient, target.id) + if (openId === target.id) router.push(next ? `/conversations/${next.id}` : '/ai-hub') + } catch { + toast.error(t('deleteFailed')) + } + } + + return ( +
+
+ + + {t('backToMessages')} + + +
+ + + + !o && setPendingDelete(null)} + title={t('deleteTitle')} + description={t('deleteDesc')} + confirmLabel={t('delete')} + onConfirm={() => void handleConfirmDelete()} + /> +
+ ) +} diff --git a/apps/web/components/ai/__tests__/AiThreadList.test.tsx b/apps/web/components/ai/__tests__/AiThreadList.test.tsx new file mode 100644 index 00000000..2ea25cab --- /dev/null +++ b/apps/web/components/ai/__tests__/AiThreadList.test.tsx @@ -0,0 +1,148 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import React from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import axios from 'axios' +import { AiThreadList } from '@/components/ai/AiThreadList' +import type { Conversation } from '@/lib/api/types' + +const push = vi.fn() +let pathname = '/conversations/t1' +vi.mock('next/navigation', () => ({ + useRouter: () => ({ push }), + usePathname: () => pathname, +})) +vi.mock('next/link', () => ({ + default: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => ( + {children} + ), +})) +vi.mock('next-intl', () => ({ + useTranslations: () => (key: string) => key, +})) +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })) +vi.mock('@/components/common/ConfirmDialog', () => ({ + ConfirmDialog: ({ open, onConfirm, confirmLabel }: { open: boolean; onConfirm: () => void; confirmLabel: string }) => + open ? : null, +})) + +const threadsState: { data: Conversation[] | undefined } = { data: [] } +const createMutateAsync = vi.fn() +const renameMutateAsync = vi.fn() +vi.mock('@/lib/hooks/use-ai-threads', () => ({ + useAiThreads: () => ({ data: threadsState.data, isLoading: false, isError: false }), + useCreateAiThread: () => ({ mutateAsync: createMutateAsync, isPending: false }), + useRenameAiThread: () => ({ mutateAsync: renameMutateAsync, isPending: false }), +})) +const deleteConversation = vi.fn() +vi.mock('@/lib/api/chat', () => ({ + chatService: { deleteConversation: (id: string) => deleteConversation(id) }, +})) + +function thread(id: string, name: string | null): Conversation { + return { + id, participants: ['u1', 'ai-bot-000000000000000000000001'], type: 'direct', name, + avatarUrl: null, wallpaper: null, admins: [], createdBy: 'u1', isPublic: false, + status: 'accepted', isMuted: false, isArchived: false, pinnedMessages: [], + autoDeleteSeconds: null, lastMessage: null, lastMessageAt: null, unreadCount: 0, + } +} + +function renderList() { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + + , + ) +} + +describe('AiThreadList', () => { + beforeEach(() => { + vi.clearAllMocks() + pathname = '/conversations/t1' + threadsState.data = [thread('t1', 'Báo cáo Q3'), thread('t2', null)] + }) + + it('renders titles in order, falling back to the untitled label, and highlights the active one', () => { + renderList() + const rows = screen.getAllByTestId('ai-thread-row') + expect(rows).toHaveLength(2) + expect(rows[0].textContent).toContain('Báo cáo Q3') + expect(rows[1].textContent).toContain('untitled') + expect(rows[0].getAttribute('aria-current')).toBe('page') + expect(rows[1].getAttribute('aria-current')).toBeNull() + }) + + it('links back to the normal conversation list', () => { + renderList() + expect(screen.getByText('backToMessages').closest('a')?.getAttribute('href')).toBe('/conversations') + }) + + it('creates a new thread and navigates to it', async () => { + createMutateAsync.mockResolvedValue(thread('t9', null)) + renderList() + fireEvent.click(screen.getByText('newThread')) + await waitFor(() => expect(push).toHaveBeenCalledWith('/conversations/t9')) + }) + + it('renames inline: Enter saves, Escape cancels', async () => { + renameMutateAsync.mockResolvedValue(thread('t1', 'Mới')) + renderList() + fireEvent.click(screen.getAllByLabelText('rename')[0]) + const input = screen.getByRole('textbox') as HTMLInputElement + fireEvent.change(input, { target: { value: ' Mới ' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(renameMutateAsync).toHaveBeenCalledWith({ id: 't1', name: 'Mới' })) + await waitFor(() => expect(screen.queryByRole('textbox')).toBeNull()) + + fireEvent.click(screen.getAllByLabelText('rename')[0]) + const input2 = screen.getByRole('textbox') + fireEvent.change(input2, { target: { value: 'Khác' } }) + fireEvent.keyDown(input2, { key: 'Escape' }) + expect(screen.queryByRole('textbox')).toBeNull() + expect(renameMutateAsync).toHaveBeenCalledTimes(1) + }) + + it('shows a localized message (never raw error text) on AI_THREAD_NAME_INVALID', async () => { + const err = new axios.AxiosError('raw english', '400', undefined, undefined, { + status: 400, data: { code: 'AI_THREAD_NAME_INVALID', message: 'raw english' }, + } as never) + renameMutateAsync.mockRejectedValue(err) + const { toast } = await import('sonner') + renderList() + fireEvent.click(screen.getAllByLabelText('rename')[0]) + const input = screen.getByRole('textbox') + fireEvent.change(input, { target: { value: 'x' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(toast.error).toHaveBeenCalledWith('nameInvalid')) + }) + + it('delete asks for confirmation, then navigates to the next thread when the open one is removed', async () => { + deleteConversation.mockResolvedValue({}) + renderList() + fireEvent.click(screen.getAllByLabelText('delete')[0]) + expect(deleteConversation).not.toHaveBeenCalled() + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(deleteConversation).toHaveBeenCalledWith('t1')) + await waitFor(() => expect(push).toHaveBeenCalledWith('/conversations/t2')) + }) + + it('goes to /ai-hub when the last open thread is deleted', async () => { + threadsState.data = [thread('t1', 'A')] + deleteConversation.mockResolvedValue({}) + renderList() + fireEvent.click(screen.getByLabelText('delete')) + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(push).toHaveBeenCalledWith('/ai-hub')) + }) + + it('does not navigate when a non-open thread is deleted', async () => { + deleteConversation.mockResolvedValue({}) + renderList() + fireEvent.click(screen.getAllByLabelText('delete')[1]) + fireEvent.click(screen.getByText(/^confirm:/)) + await waitFor(() => expect(deleteConversation).toHaveBeenCalledWith('t2')) + expect(push).not.toHaveBeenCalled() + }) +}) diff --git a/apps/web/components/chat/AiSessionPanel.tsx b/apps/web/components/chat/AiSessionPanel.tsx deleted file mode 100644 index be638b87..00000000 --- a/apps/web/components/chat/AiSessionPanel.tsx +++ /dev/null @@ -1,98 +0,0 @@ -'use client' - -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { Plus, RotateCcw } from 'lucide-react' -import { formatDistanceToNow } from 'date-fns' -import { useTranslations } from 'next-intl' -import { aiSessionApi, type AiSession } from '@/lib/api/ai-session' -import { Button } from '@/components/ui/button' -import { - AccordionContent, AccordionItem, AccordionTrigger, -} from '@/components/ui/accordion' - -/** - * Per-conversation AI session history. Lets the user see past sessions, resume - * an older one, or start a fresh session (equivalent to sending `/new`). - * Mirrors Flutter `ai_session_panel.dart`. AI conversations only. - */ -export function AiSessionPanel({ conversationId }: { conversationId: string }) { - const t = useTranslations('chat') - const qc = useQueryClient() - - const { data: sessions = [] } = useQuery({ - queryKey: ['ai-sessions', conversationId], - queryFn: () => aiSessionApi.listSessions(conversationId), - }) - - const invalidate = () => - qc.invalidateQueries({ queryKey: ['ai-sessions', conversationId] }) - - const newSession = useMutation({ - mutationFn: () => aiSessionApi.createNew(conversationId), - onSuccess: invalidate, - }) - - const resumeSession = useMutation({ - mutationFn: (sessionId: string) => aiSessionApi.resume(conversationId, sessionId), - onSuccess: invalidate, - }) - - const busy = newSession.isPending || resumeSession.isPending - - return ( - - - {t('aiSessionHistory')} - - - - -
- {sessions.map((s) => ( -
!s.isActive && !busy && resumeSession.mutate(s._id)} - onKeyDown={(e) => { - if (!s.isActive && !busy && (e.key === 'Enter' || e.key === ' ')) { - e.preventDefault() - resumeSession.mutate(s._id) - } - }} - > -
-

{s.name}

-

- {formatDistanceToNow(new Date(s.updatedAt), { addSuffix: true })} - {s.summary && ` · ${t('aiContextCompacted')}`} -

-
- {s.isActive ? ( - - {t('aiSessionActive')} - - ) : ( - - )} -
- ))} -
-
-
- ) -} diff --git a/apps/web/components/chat/ConversationHeader.tsx b/apps/web/components/chat/ConversationHeader.tsx index 07bc59de..237167eb 100644 --- a/apps/web/components/chat/ConversationHeader.tsx +++ b/apps/web/components/chat/ConversationHeader.tsx @@ -4,7 +4,7 @@ import { useState } from 'react' import { useRouter } from 'next/navigation' import { useTranslations } from 'next-intl' import { toast } from 'sonner' -import { ArrowLeft, Bot, Settings, Phone, Video, Users } from 'lucide-react' +import { ArrowLeft, Bot, Settings, Phone, Video, Users, SquarePen } from 'lucide-react' import { useQueryClient } from '@tanstack/react-query' import { useConversation } from '@/lib/hooks/use-conversation' import { useUserStatus } from '@/lib/hooks/use-user-status' @@ -12,10 +12,10 @@ import { useRelationship } from '@/lib/hooks/use-relationship' import { useAuthStore } from '@/lib/store/auth.store' import { useUser } from '@/lib/hooks/use-user' import { useAssistant } from '@/lib/hooks/use-assistant' -import { useAssistantName } from '@/lib/hooks/use-capabilities' import type { Conversation } from '@/lib/api/types' import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' import { Button } from '@/components/ui/button' +import { useCreateAiThread } from '@/lib/hooks/use-ai-threads' import { PinnedMessagesBar } from './PinnedMessagesBar' import { ConversationSettingsDrawer } from './ConversationSettingsDrawer' import { GroupSettingsDrawer } from './GroupSettingsDrawer' @@ -78,6 +78,8 @@ export function ConversationHeader({ }: Props) { const t = useTranslations('chat') const tCall = useTranslations('call') + const tThreads = useTranslations('aiThreads') + const createThread = useCreateAiThread() const router = useRouter() const { data: conversation } = useConversation(conversationId) const queryClient = useQueryClient() @@ -105,14 +107,13 @@ export function ConversationHeader({ const blockedMe = relationship?.blockedMe ?? false const { data: otherUser } = useUser(otherUserId) const nickname = useNickname(conversationId, otherUserId) - const assistantName = useAssistantName() const { data: extBotAssistant } = useAssistant() const displayName = nickname ?? conversation?.name ?? (isAI - ? (assistantName ?? t('aiAssistant')) + ? tThreads('untitled') : isExtBot ? (extBotAssistant?.name ?? t('aiAssistant')) : (otherUser?.displayName ?? t('conversationDefault'))) @@ -152,7 +153,7 @@ export function ConversationHeader({ variant="ghost" size="icon" className="md:hidden h-8 w-8 shrink-0 -ml-1" - onClick={() => router.push('/conversations')} + onClick={() => router.push(isAI ? '/ai-hub' : '/conversations')} title={t('backToList')} > @@ -221,6 +222,25 @@ export function ConversationHeader({ {/* Header action buttons */}
+ {/* New AI chat — starts a fresh thread (reachable on mobile, where the sidebar is hidden) */} + {isAI && ( + + )} {/* Group call — always visible for group conversations */} {isGroup && !isAI && (