This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-11 23:47:58 -05:00
1 parent eb2570b405
commit 9d9f5786cb
8 files changed
+143 -18

No files matched your search

+7 -2
View File
@@ -17,8 +17,13 @@ export const savePreferences = (data: Record<string, unknown>) =>
// ── 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<WorkspaceListItem[]>('/api/state/workspaces');
// ── Single workspace CRUD ───────────────────────────────────────
@@ -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}
<Icon name="folder" size={14} />
{/if}
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
>{ws.name}</span
>
<span class="min-w-0 truncate text-left">{ws.name}</span>
{#if ws.unread_count > 0}
<span
class="inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-md bg-sky-500/10 px-1 text-[0.625rem] font-semibold text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
>
{new Intl.NumberFormat(undefined, {
notation: 'compact',
compactDisplay: 'short'
}).format(ws.unread_count)}
</span>
{/if}
</a>
<span
class="flex items-center justify-center w-4 h-4 shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:text-gray-600 dark:hover:text-gray-300 transition-all duration-75"
+2 -2
View File
@@ -281,7 +281,7 @@ export const homeState = writable<HomeState>({
});
/** 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
+38 -1
View File
@@ -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."""
+29 -1
View File
@@ -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}
+14 -4
View File
@@ -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
]
+16 -1
View File
@@ -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):
+13 -3
View File
@@ -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: