From fbc33282e44139c92804a86c450c0ae11d44e16b Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Wed, 15 Jul 2026 15:22:26 -0400 Subject: [PATCH] refac --- cptr/frontend/src/lib/apis/chat.ts | 7 +- .../components/chat/AssistantMessage.svelte | 16 ++-- .../src/lib/components/chat/ChatPanel.svelte | 8 +- cptr/routers/chat.py | 25 +++--- cptr/routers/workspace.py | 45 +++++++--- cptr/utils/chat_task.py | 23 +++-- cptr/utils/context.py | 39 +++++++++ cptr/utils/gitignore.py | 83 +++++++++++++++++++ cptr/utils/tools.py | 31 ++++--- 9 files changed, 225 insertions(+), 52 deletions(-) create mode 100644 cptr/utils/gitignore.py diff --git a/cptr/frontend/src/lib/apis/chat.ts b/cptr/frontend/src/lib/apis/chat.ts index a5c8339..eb1e171 100644 --- a/cptr/frontend/src/lib/apis/chat.ts +++ b/cptr/frontend/src/lib/apis/chat.ts @@ -171,8 +171,11 @@ export const answerAskUser = ( export const cancelTask = (chatId: string, messageId: string) => fetchJSON(`/api/chats/${chatId}/messages/${messageId}/cancel`, { method: 'POST' }); -export const compactChat = (chatId: string, modelId: string) => - fetchJSON(`/api/chats/${chatId}/compact`, jsonBody({ model_id: modelId })); +export const compactChat = (chatId: string, modelId?: string | null) => + fetchJSON( + `/api/chats/${chatId}/compact`, + jsonBody({ model_id: modelId || null }) + ); export const updateCurrentMessage = (chatId: string, messageId: string) => fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}/current`, jsonBody({ message_id: messageId })); diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index f4e8f86..991be66 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -754,7 +754,7 @@ onmouseenter={() => (showUsageTooltip = true)} onmouseleave={() => (showUsageTooltip = false)} aria-label={$t('chat.usageInfo')} - use:tooltip={$t('chat.usageInfo')} + use:tooltip={showUsageTooltip ? null : $t('chat.usageInfo')} >
{#each Object.entries(usage) as [key, value]}
- {formatUsageLabel(key)} - {formatUsageValue(key, value)} + {formatUsageLabel(key)} + {formatUsageValue(key, value)}
{/each}
@@ -794,7 +791,8 @@ class="absolute top-full left-1/2 -translate-x-1/2 w-0 h-0 border-l-[0.3125rem] border-l-transparent border-r-[0.3125rem] border-r-transparent - border-t-[0.3125rem] border-t-gray-900 dark:border-t-gray-800" + border-t-[0.3125rem]" + style="border-top-color: var(--app-bg);" > {/if} diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index 0b16f7e..1f64586 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -532,6 +532,7 @@ delta?: string; output?: any; tasks?: ChatTask[]; + context_usage?: ContextUsage | null; done?: boolean; error?: string; pending_inputs_processed?: boolean; @@ -574,6 +575,9 @@ chatTitle = data.title; updateTab(tabId, data.chat_id, data.title); } + if (data.context_usage) { + contextUsage = data.context_usage; + } // Follow-up state changed server-side: reload to see new transcript/generation state. if (data.pending_inputs_processed || data.async_subagent_pending) { @@ -1024,12 +1028,12 @@ toast.message($t('chat.compactNoChat')); return; } - if (!selectedModel || sending || streaming) return; + if (sending || streaming) return; sending = true; inputText = ''; const toastId = toast.loading($t('chat.compacting')); try { - const result = await apiCompactChat(chatId, selectedModel); + const result = await apiCompactChat(chatId, selectedModel || null); contextUsage = result.context_usage ?? contextUsage; if (result.compacted) { toast.success($t('chat.compactDone'), { id: toastId }); diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index aec71e8..9d98749 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -457,6 +457,7 @@ async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | N estimate_context_usage, estimate_messages_tokens, load_compact_token_threshold, + usage_context_tokens, ) messages, existing_summary = await _load_message_history(chat.id, message_id) @@ -470,9 +471,8 @@ async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | N usage_checkpoint = await _get_latest_usage_checkpoint(chat.id, message_id) if usage_checkpoint: trailing_messages, usage = usage_checkpoint - tokens = usage.get("input_tokens") - if isinstance(tokens, int) and tokens > 0: - tokens += usage.get("output_tokens", 0) + tokens = usage_context_tokens(usage) + if tokens > 0: if trailing_messages: tokens += estimate_messages_tokens( [{"role": m.role, "content": m.content or ""} for m in trailing_messages] @@ -495,6 +495,8 @@ async def _infer_chat_model(chat_id: str) -> str: async def _get_latest_usage_checkpoint( chat_id: str, message_id: str ) -> tuple[list[ChatMessage], dict] | None: + from cptr.utils.context import normalize_usage, usage_context_tokens + all_msgs = await ChatMessage.get_all_by_chat(chat_id) msg_map = {m.id: m for m in all_msgs} chain = [] @@ -508,8 +510,8 @@ async def _get_latest_usage_checkpoint( message = chain[index] if message.chat_summary: return None - usage = message.usage or {} - if message.role == "assistant" and usage.get("input_tokens"): + usage = normalize_usage(message.usage) + if message.role == "assistant" and usage_context_tokens(usage): return chain[index + 1 :], usage return None @@ -700,7 +702,7 @@ class SendMessageRequest(BaseModel): class CompactRequest(BaseModel): - model_id: str + model_id: Optional[str] = None @router.post("") @@ -864,13 +866,16 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): raise HTTPException(404, "chat not found") if await _chat_has_active_generation(chat_id): raise HTTPException(409, "wait for the current response to finish before compacting") + model_id = body.model_id or await _infer_chat_model(chat_id) + if not model_id: + raise HTTPException(400, "choose a model before compacting") message_id = await _get_context_leaf_message_id(chat) if not message_id: return {"ok": True, "compacted": False, "reason": "empty", "context_usage": None} current_msg = await ChatMessage.get_by_id(message_id) if not current_msg or not current_msg.parent_id: - usage = await _get_chat_context_usage(chat, body.model_id) + usage = await _get_chat_context_usage(chat, model_id) return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage} from cptr.utils.model_targets import ( @@ -879,7 +884,7 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): resolve_model_target, ) - target = await resolve_model_target(body.model_id, request.app.state) + target = await resolve_model_target(model_id, request.app.state) if not isinstance(target, ApiModelTarget): target = await first_api_model_target(request.app.state) @@ -888,7 +893,7 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): messages, existing_summary = await _load_message_history(chat_id, current_msg.parent_id) if not messages: - usage = await _get_chat_context_usage(chat, body.model_id) + usage = await _get_chat_context_usage(chat, model_id) return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage} connection = target.connection @@ -914,7 +919,7 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request): from cptr.utils.chat_export import export_chat_to_file await export_chat_to_file(chat_id) - usage = await _get_chat_context_usage(chat, body.model_id) + usage = await _get_chat_context_usage(chat, model_id) return { "ok": True, "compacted": True, diff --git a/cptr/routers/workspace.py b/cptr/routers/workspace.py index 0438de4..37da275 100644 --- a/cptr/routers/workspace.py +++ b/cptr/routers/workspace.py @@ -18,6 +18,8 @@ from typing import Optional from fastapi import APIRouter, HTTPException, Query from pydantic import BaseModel +from cptr.utils.gitignore import is_gitignored, load_gitignore + router = APIRouter(prefix="/api/workspace/files", tags=["workspace-files"]) @@ -355,22 +357,35 @@ def _is_search_ignored(name: str) -> bool: return name in SEARCH_IGNORE_DIRS or name.endswith(".egg-info") -def _walk_match_entries(root: Path, show_hidden: bool): +def _walk_match_entries( + root: Path, + show_hidden: bool, + gitignore: tuple[Path, tuple] | None = None, +): """Yield visible files and directories without following symlinks.""" + if gitignore is None: + gitignore = load_gitignore(root) + ignore_base, ignore_patterns = gitignore + try: entries = sorted(root.iterdir(), key=lambda item: item.name.lower()) except (OSError, PermissionError): return for item in entries: - if _is_search_ignored(item.name) or (not show_hidden and item.name.startswith(".")): - continue try: + item_is_dir = item.is_dir() + if ( + _is_search_ignored(item.name) + or (not show_hidden and item.name.startswith(".")) + or is_gitignored(item, ignore_base, ignore_patterns, is_dir=item_is_dir) + ): + continue if item.is_symlink(): yield item, "file" - elif item.is_dir(): + elif item_is_dir: yield item, "directory" - yield from _walk_match_entries(item, show_hidden) + yield from _walk_match_entries(item, show_hidden, gitignore) elif item.is_file(): yield item, "file" except (OSError, PermissionError): @@ -408,7 +423,6 @@ def _content_matches_with_rg( "--column", "--max-count", str(MAX_CONTENT_MATCHES_PER_FILE + 1), - "--no-ignore", ] if show_hidden: args.append("--hidden") @@ -489,7 +503,9 @@ def find_file_matches( files = {path.resolve() for path, kind in entries if kind == "file" and not path.is_symlink()} content_result = _content_matches_with_rg(root, query, query_lower, show_hidden, files) content_matches, _ = ( - content_result if content_result is not None else _content_matches_with_python(files, query_lower) + content_result + if content_result is not None + else _content_matches_with_python(files, query_lower) ) matches: list[tuple[int, int, FileMatch]] = [] @@ -593,13 +609,19 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR query_lower = query.strip().lower().replace("\\", "/") matches: list[tuple[int, int, SearchResult]] = [] max_collect = limit * 10 + ignore_base, ignore_patterns = load_gitignore(root) def walk(directory: Path, depth: int = 0): if depth > 8 or len(matches) >= max_collect: return try: for item in sorted(directory.iterdir(), key=lambda p: p.name.lower()): - if item.name in SEARCH_IGNORE_DIRS or item.name.startswith("."): + item_is_dir = item.is_dir() + if ( + item.name in SEARCH_IGNORE_DIRS + or item.name.startswith(".") + or is_gitignored(item, ignore_base, ignore_patterns, is_dir=item_is_dir) + ): continue if len(matches) >= max_collect: return @@ -619,7 +641,7 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR SearchResult( path=str(item), name=item.name, - type="directory" if item.is_dir() else "file", + type="directory" if item_is_dir else "file", ), ) ) @@ -631,12 +653,12 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR SearchResult( path=str(item), name=item.name, - type="directory" if item.is_dir() else "file", + type="directory" if item_is_dir else "file", ), ) ) - if item.is_dir(): + if item_is_dir: walk(item, depth + 1) except (PermissionError, OSError): pass @@ -646,7 +668,6 @@ def walk_and_rank_files(root: Path, query: str, limit: int = 20) -> list[SearchR return [m[2] for m in matches[:limit]] - # ── File management ────────────────────────────────────────────── diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 9eebd1d..f323cb5 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -14,7 +14,13 @@ from typing import Any from cptr.events import EVENTS, publish_event from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS -from cptr.utils.context import resolve_compact_token_threshold, should_compact +from cptr.utils.context import ( + build_context_usage, + normalize_usage, + resolve_compact_token_threshold, + should_compact, + usage_context_tokens, +) from cptr.utils.skills import ( bump_skill_view, discover_skills, @@ -754,7 +760,7 @@ async def generate_chat_title( # Do not overwrite a title manually set while this request was running. chat = await Chat.get_by_id(chat_id) - fallback = user_content[:50].strip() or "New Chat" + fallback = user_message[:50].strip() or "New Chat" if not chat or chat.title != fallback: return @@ -2192,13 +2198,16 @@ async def run_chat_task( await emit(output=item) elif event["type"] == "usage": - usage = {k: v for k, v in event.items() if k != "type"} - if "total_tokens" not in usage: - usage["total_tokens"] = usage.get("input_tokens", 0) + usage.get( - "output_tokens", 0 - ) + usage = normalize_usage({k: v for k, v in event.items() if k != "type"}) last_usage = usage new_messages_since = 0 + tokens = usage_context_tokens(usage) + if tokens > 0: + await emit( + context_usage=build_context_usage( + tokens, threshold=compact_token_threshold, source="estimated" + ) + ) elif event["type"] == "done": # Stream ended. Usage may have arrived earlier, multiple times, or never. diff --git a/cptr/utils/context.py b/cptr/utils/context.py index 1a4e12c..ad04667 100644 --- a/cptr/utils/context.py +++ b/cptr/utils/context.py @@ -46,6 +46,7 @@ def should_compact( """ resolved_threshold = threshold or _get_threshold() + last_usage = normalize_usage(last_usage) if last_usage and last_usage.get("input_tokens"): # Real base from last API call + estimate only new additions base = last_usage["input_tokens"] + last_usage.get("output_tokens", 0) @@ -72,6 +73,36 @@ def build_context_usage(tokens: int, *, threshold: int | None = None, source: st } +def normalize_usage(usage: dict | None) -> dict | None: + """Return provider usage with cptr's canonical token field names.""" + if not usage: + return None + normalized = dict(usage) + input_tokens = _parse_nonnegative_int( + normalized.get("input_tokens", normalized.get("prompt_tokens")) + ) + output_tokens = _parse_nonnegative_int( + normalized.get("output_tokens", normalized.get("completion_tokens")) + ) + total_tokens = _parse_nonnegative_int(normalized.get("total_tokens")) + if total_tokens == 0: + total_tokens = input_tokens + output_tokens + normalized["input_tokens"] = input_tokens + normalized["output_tokens"] = output_tokens + normalized["total_tokens"] = total_tokens + return normalized + + +def usage_context_tokens(usage: dict | None) -> int: + """Best available context token count from normalized or provider usage.""" + usage = normalize_usage(usage) + if not usage: + return 0 + if usage.get("input_tokens"): + return usage["input_tokens"] + usage.get("output_tokens", 0) + return usage.get("total_tokens", 0) + + def estimate_context_usage( messages: list[dict], system_prompt: str, *, threshold: int | None = None ) -> dict: @@ -89,6 +120,14 @@ def _parse_positive_int(value: object) -> int | None: return parsed if parsed > 0 else None +def _parse_nonnegative_int(value: object) -> int: + try: + parsed = int(value) + except (TypeError, ValueError): + return 0 + return max(0, parsed) + + def resolve_compact_token_threshold( model: str | None = None, *, diff --git a/cptr/utils/gitignore.py b/cptr/utils/gitignore.py new file mode 100644 index 0000000..033366d --- /dev/null +++ b/cptr/utils/gitignore.py @@ -0,0 +1,83 @@ +"""Small .gitignore matcher for fallback file walkers.""" + +from __future__ import annotations + +from fnmatch import fnmatch +from pathlib import Path + +GitignorePattern = tuple[str, bool, bool, bool] + + +def load_gitignore(root: Path) -> tuple[Path, tuple[GitignorePattern, ...]]: + """Load the nearest repo/root .gitignore patterns for a search root.""" + base = _ignore_base(root.resolve()) + gitignore = base / ".gitignore" + if not gitignore.is_file(): + return base, () + + patterns: list[GitignorePattern] = [] + for raw in gitignore.read_text(encoding="utf-8", errors="replace").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if line.startswith("\\#") or line.startswith("\\!"): + line = line[1:] + negated = line.startswith("!") + if negated: + line = line[1:].strip() + directory_only = line.endswith("/") + pattern = line.strip("/") + if pattern: + patterns.append((pattern, negated, directory_only, "/" in pattern)) + return base, tuple(patterns) + + +def is_gitignored( + path: Path, + base: Path, + patterns: tuple[GitignorePattern, ...], + *, + is_dir: bool, +) -> bool: + if not patterns: + return False + try: + rel = path.resolve().relative_to(base).as_posix() + except ValueError: + return False + + ignored = False + name = path.name + for pattern, negated, directory_only, anchored in patterns: + if directory_only and not is_dir: + continue + if _matches_gitignore_pattern(pattern, rel, name, directory_only, anchored): + ignored = not negated + return ignored + + +def _ignore_base(root: Path) -> Path: + current = root if root.is_dir() else root.parent + fallback = current + for parent in (current, *current.parents): + if (parent / ".git").exists(): + return parent + if (parent / ".gitignore").is_file(): + fallback = parent + return fallback + + +def _matches_gitignore_pattern( + pattern: str, + rel: str, + name: str, + directory_only: bool, + anchored: bool, +) -> bool: + if anchored: + return ( + rel == pattern + or (directory_only and rel.startswith(f"{pattern}/")) + or fnmatch(rel, pattern) + ) + return any(fnmatch(part, pattern) for part in rel.split("/")) or fnmatch(name, pattern) diff --git a/cptr/utils/tools.py b/cptr/utils/tools.py index 0e8ec0a..52f39a0 100644 --- a/cptr/utils/tools.py +++ b/cptr/utils/tools.py @@ -20,7 +20,9 @@ import time import uuid from pathlib import Path from typing import Any, Literal, Optional, get_args, get_origin, get_type_hints + from cptr.env import CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS, EXECUTE_TIMEOUT +from cptr.utils.gitignore import is_gitignored, load_gitignore try: import fcntl @@ -716,13 +718,22 @@ async def _search_python(query: str, full: Path, case_insensitive: bool) -> str: def _walk_and_search(): results = [] ignore = {".git", "node_modules", "__pycache__", ".venv", "venv"} + ignore_base, ignore_patterns = load_gitignore(full) q = query.lower() if case_insensitive else query for root, dirs, files in os.walk(full): - dirs[:] = [d for d in dirs if d not in ignore] + root_path = Path(root) + dirs[:] = [ + d + for d in dirs + if d not in ignore + and not is_gitignored(root_path / d, ignore_base, ignore_patterns, is_dir=True) + ] for fname in files: fpath = Path(root) / fname - if _is_dotenv(fpath): + if _is_dotenv(fpath) or is_gitignored( + fpath, ignore_base, ignore_patterns, is_dir=False + ): continue text = _read_text_for_search(fpath) if text is None: @@ -767,7 +778,7 @@ async def create_file( artifact_path = artifact_dir / f"{ts}_{artifact_type}.md" def _write_artifact(): - artifact_path.write_text(content) + artifact_path.write_text(content, encoding="utf-8") await asyncio.to_thread(_write_artifact) @@ -793,7 +804,7 @@ async def create_file( def _write(): full.parent.mkdir(parents=True, exist_ok=True) - full.write_text(content) + full.write_text(content, encoding="utf-8") await asyncio.to_thread(_write) return f"Created {path} ({len(content)} bytes, {len(content.splitlines())} lines)" @@ -820,7 +831,7 @@ async def create_artifact( artifact_path = artifact_dir / f"{ts}_{artifact_type}.md" def _write(): - artifact_path.write_text(content) + artifact_path.write_text(content, encoding="utf-8") await asyncio.to_thread(_write) @@ -972,7 +983,7 @@ async def write_file(path: str, content: str, *, workspace: str) -> str: def _write(): full.parent.mkdir(parents=True, exist_ok=True) - full.write_text(content) + full.write_text(content, encoding="utf-8") await asyncio.to_thread(_write) return f"Wrote {len(content)} bytes to {path}" @@ -1043,7 +1054,7 @@ async def edit_file( return f"Error: file not found: {path}" def _edit(): - content = full.read_text(errors="replace") + content = full.read_text(encoding="utf-8", errors="replace") if start_line > 0 or end_line > 0: lines = content.splitlines(keepends=True) @@ -1075,7 +1086,7 @@ async def edit_file( ) new_content = content.replace(target, replacement, 1) - full.write_text(new_content) + full.write_text(new_content, encoding="utf-8") return None # success sentinel result = await asyncio.to_thread(_edit) @@ -1115,7 +1126,7 @@ async def multi_edit_file( return "Error: edits must be a non-empty JSON array" def _apply(): - content = full.read_text(errors="replace") + content = full.read_text(encoding="utf-8", errors="replace") applied = 0 for i, edit in enumerate(edit_list): @@ -1138,7 +1149,7 @@ async def multi_edit_file( content = content.replace(target, replacement, 1) applied += 1 - full.write_text(content) + full.write_text(content, encoding="utf-8") return f"Applied {applied} edits to {path}" return await asyncio.to_thread(_apply)