From 9d9f5786cb6a990d92d2ddfa4ea5b6f8350c12c8 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 11 Jul 2026 23:47:58 -0500 Subject: [PATCH] refac --- cptr/frontend/src/lib/apis/state.ts | 9 ++++- .../components/SidebarWorkspaceList.svelte | 28 +++++++++++-- cptr/frontend/src/lib/stores.ts | 4 +- cptr/models/chats.py | 39 ++++++++++++++++++- cptr/routers/chat.py | 30 +++++++++++++- cptr/routers/state.py | 18 +++++++-- cptr/socket/main.py | 17 +++++++- cptr/utils/chat_task.py | 16 ++++++-- 8 files changed, 143 insertions(+), 18 deletions(-) diff --git a/cptr/frontend/src/lib/apis/state.ts b/cptr/frontend/src/lib/apis/state.ts index ee49b37..10d64b8 100644 --- a/cptr/frontend/src/lib/apis/state.ts +++ b/cptr/frontend/src/lib/apis/state.ts @@ -17,8 +17,13 @@ export const savePreferences = (data: Record) => // ── Workspace list (sidebar) ──────────────────────────────────── -export const getWorkspaceList = () => - fetchJSON<{ path: string; name: string }[]>('/api/state/workspaces'); +export interface WorkspaceListItem { + path: string; + name: string; + unread_count: number; +} + +export const getWorkspaceList = () => fetchJSON('/api/state/workspaces'); // ── Single workspace CRUD ─────────────────────────────────────── diff --git a/cptr/frontend/src/lib/components/SidebarWorkspaceList.svelte b/cptr/frontend/src/lib/components/SidebarWorkspaceList.svelte index ee50bc0..fcaf790 100644 --- a/cptr/frontend/src/lib/components/SidebarWorkspaceList.svelte +++ b/cptr/frontend/src/lib/components/SidebarWorkspaceList.svelte @@ -173,15 +173,27 @@ active?: boolean; updated_at?: number; last_read_at?: number; + workspace_unread_count?: number; }) { if ( !data.title && typeof data.active !== 'boolean' && typeof data.updated_at !== 'number' && - typeof data.last_read_at !== 'number' + typeof data.last_read_at !== 'number' && + typeof data.workspace_unread_count !== 'number' ) { return; } + const unreadCount = data.workspace_unread_count; + if (data.workspace && typeof unreadCount === 'number') { + workspaceList.update((workspaces) => + workspaces.map((workspace) => + workspace.path === data.workspace + ? { ...workspace, unread_count: unreadCount } + : workspace + ) + ); + } let known = false; wsChatsCache = new Map( @@ -310,9 +322,17 @@ {:else} {/if} - {ws.name} + {ws.name} + {#if ws.unread_count > 0} + + {new Intl.NumberFormat(undefined, { + notation: 'compact', + compactDisplay: 'short' + }).format(ws.unread_count)} + + {/if} ({ }); /** List of all workspace summaries for the sidebar. */ -export const workspaceList = writable<{ path: string; name: string }[]>([]); +export const workspaceList = writable<{ path: string; name: string; unread_count: number }[]>([]); /** Global user preferences. */ export const sidebarOpen = writable( @@ -825,7 +825,7 @@ export function addWorkspace(path: string): void { // Update workspace list for sidebar workspaceList.update((list) => { if (list.some((w) => w.path === path)) return list; - return [...list, { path, name }]; + return [...list, { path, name, unread_count: 0 }]; }); // Append to order diff --git a/cptr/models/chats.py b/cptr/models/chats.py index 56805fc..a59266a 100644 --- a/cptr/models/chats.py +++ b/cptr/models/chats.py @@ -5,7 +5,18 @@ from __future__ import annotations import re import uuid -from sqlalchemy import BigInteger, Boolean, Column, ForeignKey, Text, delete, or_, select, update +from sqlalchemy import ( + BigInteger, + Boolean, + Column, + ForeignKey, + Text, + delete, + func, + or_, + select, + update, +) from sqlalchemy.dialects.sqlite import JSON from cptr.models.base import Base @@ -121,6 +132,32 @@ class Chat(Base): await db.commit() return result.rowcount > 0 + @staticmethod + async def unread_counts_by_workspace( + user_id: str, workspace_paths: list[str], active_chat_ids: set[str] + ) -> dict[str, int]: + """Derive unread counts from chats; do not persist a second read-state.""" + paths = list(dict.fromkeys(path for path in workspace_paths if path)) + if not paths: + return {} + + workspace = Chat.meta["workspace"].as_string() + statement = ( + select(workspace, func.count(Chat.id)) + .where( + Chat.user_id == user_id, + workspace.in_(paths), + Chat.updated_at > func.coalesce(Chat.last_read_at, 0), + ) + .group_by(workspace) + ) + if active_chat_ids: + statement = statement.where(Chat.id.not_in(active_chat_ids)) + + async with await get_db() as db: + result = await db.execute(statement) + return {workspace: count for workspace, count in result.all() if workspace} + @staticmethod async def update_last_read_at(chat_id: str, user_id: str, last_read_at: int) -> bool: """Mark a chat read without changing its activity timestamp.""" diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index 4455252..f671210 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -538,9 +538,23 @@ async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request): updated_at = now_ms() await Chat.update_title(chat_id, title, updated_at) + workspace = (chat.meta or {}).get("workspace", "") + from cptr.utils.chat_task import get_active_chat_ids from cptr.socket.main import emit_to_user - await emit_to_user(user_id, {"chat_id": chat_id, "title": title, "updated_at": updated_at}) + unread_counts = await Chat.unread_counts_by_workspace( + user_id, [workspace], get_active_chat_ids() + ) + await emit_to_user( + user_id, + { + "chat_id": chat_id, + "title": title, + "workspace": workspace, + "updated_at": updated_at, + "workspace_unread_count": unread_counts.get(workspace, 0), + }, + ) return {"ok": True, "title": title} @@ -573,6 +587,20 @@ async def delete_chat(chat_id: str, request: Request): await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True await Chat.delete(chat_id) + from cptr.socket.main import emit_to_user + from cptr.utils.chat_task import get_active_chat_ids + + unread_counts = await Chat.unread_counts_by_workspace( + user_id, [workspace or ""], get_active_chat_ids() + ) + await emit_to_user( + user_id, + { + "chat_id": chat_id, + "workspace": workspace or "", + "workspace_unread_count": unread_counts.get(workspace or "", 0), + }, + ) return {"ok": True} diff --git a/cptr/routers/state.py b/cptr/routers/state.py index 8acb714..e944a64 100644 --- a/cptr/routers/state.py +++ b/cptr/routers/state.py @@ -13,7 +13,7 @@ from pathlib import Path, PureWindowsPath from fastapi import APIRouter, HTTPException, Request, Query from cptr.env import DATA_DIR -from cptr.models import UserStates, Workspace +from cptr.models import Chat, UserStates, Workspace from cptr.utils.config import get_or_create_user router = APIRouter(prefix="/api/state", tags=["state"]) @@ -84,11 +84,21 @@ def _workspace_display_name(path: str) -> str: return name or path -async def _workspace_summaries(user_id: str) -> list[dict[str, str]]: +async def _workspace_summaries(user_id: str) -> list[dict[str, str | int]]: workspaces = await Workspace.get_by_user(user_id) + summaries = _dedupe_workspaces(workspaces) + from cptr.utils.chat_task import get_active_chat_ids + + unread_counts = await Chat.unread_counts_by_workspace( + user_id, [path for path, _ in summaries], get_active_chat_ids() + ) return [ - {"path": path, "name": workspace.name or _workspace_display_name(path)} - for path, workspace in _dedupe_workspaces(workspaces) + { + "path": path, + "name": workspace.name or _workspace_display_name(path), + "unread_count": unread_counts.get(path, 0), + } + for path, workspace in summaries ] diff --git a/cptr/socket/main.py b/cptr/socket/main.py index 10c4d52..d0c2787 100644 --- a/cptr/socket/main.py +++ b/cptr/socket/main.py @@ -89,7 +89,22 @@ async def on_chat_read(sid, data): last_read_at = now_ms() if await Chat.update_last_read_at(chat_id, user_id, last_read_at): - await emit_to_user(user_id, {"chat_id": chat_id, "last_read_at": last_read_at}) + chat = await Chat.get_by_id(chat_id) + workspace = (chat.meta or {}).get("workspace", "") if chat else "" + from cptr.utils.chat_task import get_active_chat_ids + + unread_counts = await Chat.unread_counts_by_workspace( + user_id, [workspace], get_active_chat_ids() + ) + await emit_to_user( + user_id, + { + "chat_id": chat_id, + "workspace": workspace, + "last_read_at": last_read_at, + "workspace_unread_count": unread_counts.get(workspace, 0), + }, + ) async def emit_to_user(user_id: str, data: dict): diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 88c2846..738722c 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -381,17 +381,23 @@ def start_task( ) _tasks[message_id] = task _task_chat[message_id] = chat_id - asyncio.create_task( - emit_to_user( + + async def emit_active(): + unread_counts = await Chat.unread_counts_by_workspace( + user_id, [workspace], get_active_chat_ids() + ) + await emit_to_user( user_id, { "type": "chat:active", "chat_id": chat_id, "workspace": workspace, "active": True, + "workspace_unread_count": unread_counts.get(workspace, 0), }, ) - ) + + asyncio.create_task(emit_active()) async def cancel_task(message_id: str) -> bool: @@ -2640,6 +2646,9 @@ async def run_chat_task( try: await Chat.touch(chat_id, now_ms()) chat = await Chat.get_by_id(chat_id) + unread_counts = await Chat.unread_counts_by_workspace( + user_id, [workspace], get_active_chat_ids() + ) await emit_to_user( user_id, { @@ -2648,6 +2657,7 @@ async def run_chat_task( "workspace": workspace, "active": False, "updated_at": chat.updated_at if chat else None, + "workspace_unread_count": unread_counts.get(workspace, 0), }, ) except Exception: