This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-06 23:39:35 +01:00
1 parent 513498244e
commit af35848d21
4 files changed
+79 -18

No files matched your search

@@ -196,6 +196,20 @@
type DisplayItem = ToolGroup | MessageItem | ArtifactItem;
const outputText = $derived.by((): string => {
return (output || [])
.filter((i: any) => i.type === 'message')
.flatMap((i: any) => i.content || [])
.map((c: any) => c.text || '')
.join('');
});
const unrenderedContent = $derived.by((): string => {
if (!content) return '';
if (!outputText) return content;
return content.startsWith(outputText) ? content.slice(outputText.length) : '';
});
const displayItems = $derived.by((): DisplayItem[] => {
if (!output?.length) return [];
@@ -317,6 +331,9 @@
class="inline-block w-[2px] h-3.5 bg-gray-400 dark:bg-gray-500 ml-0.5 animate-pulse align-text-bottom"
></span>
{:else}
{#if done && displayItems.length === 0 && content}
<MarkdownRenderer {content} />
{/if}
{#each displayItems as displayItem, groupIdx}
{#if displayItem.type === 'message_item'}
<MarkdownRenderer
@@ -805,15 +822,11 @@
</div>
{/if}
{/each}
{#if !done}
{@const flushedText = (output || [])
.filter((i: any) => i.type === 'message')
.flatMap((i: any) => i.content || [])
.map((c: any) => c.text)
.join('')}
{@const pendingText = content.slice(flushedText.length)}
{#if pendingText}
<MarkdownRenderer content={pendingText} />
{#if done && unrenderedContent && displayItems.length > 0}
<MarkdownRenderer content={unrenderedContent} />
{:else if !done}
{#if unrenderedContent}
<MarkdownRenderer content={unrenderedContent} />
{/if}
<span
class="inline-block w-[2px] h-3.5 bg-gray-400 dark:bg-gray-500 ml-0.5 animate-pulse align-text-bottom"
@@ -24,7 +24,12 @@
import { socketStore } from '$lib/stores/socket.svelte';
import { onMount, onDestroy, tick } from 'svelte';
import { get } from 'svelte/store';
import { currentWorkspace, toolApprovalMode, streamingBehavior, selectedModelId } from '$lib/stores';
import {
currentWorkspace,
toolApprovalMode,
streamingBehavior,
selectedModelId
} from '$lib/stores';
import ChatInput from './ChatInput.svelte';
import UserMessage from './UserMessage.svelte';
@@ -107,8 +112,8 @@
const effectiveId =
currentMessageId && msgMap.has(currentMessageId)
? currentMessageId
: allMessages.length > 0
? allMessages[allMessages.length - 1].id
: displayMessages.length > 0
? displayMessages[displayMessages.length - 1].id
: null;
if (!effectiveId) return [];
@@ -203,8 +208,11 @@
// ── Load chat from DB ───────────────────────────────────────
let loadGeneration = 0;
async function loadChat(id: string) {
chatId = id;
const gen = ++loadGeneration;
// Only show loading spinner on initial load (no messages yet).
// On reloads (e.g. after cancel/done), keep the DOM intact to preserve scroll position.
const isInitialLoad = allMessages.length === 0;
@@ -215,10 +223,12 @@
try {
const data = await getChat(id);
// Discard stale response if a newer loadChat was called while we waited
if (gen !== loadGeneration) return;
allMessages = data.messages;
currentMessageId = data.chat.current_message_id;
} finally {
if (isInitialLoad) loading = false;
if (isInitialLoad && gen === loadGeneration) loading = false;
}
// On reloads, restore scroll position after the DOM re-renders.
@@ -347,6 +357,12 @@
cancelledMessageId = null;
return;
}
// Mark done optimistically, but keep the streamed content visible until
// the DB reload returns. This avoids a transient blank message if the
// final `done` socket event beats the commit/read path.
msg.done = true;
allMessages = [...allMessages];
loadChat(data.chat_id);
}
}
+16 -1
View File
@@ -547,6 +547,7 @@ async def run_chat_task(
}
output_items.append(item)
text_buffer = ""
_sync_state()
return item
def _sync_state():
@@ -660,6 +661,11 @@ async def run_chat_task(
await emit(output=artifact_item)
_sync_state()
# Persist intermediate state so content survives crashes/errors
await ChatMessage.update(
message_id, content=content, output=output_items
)
# Append to messages for next iteration
_append_tool_to_messages(messages, event, result, provider)
restart = True
@@ -678,6 +684,7 @@ async def run_chat_task(
if flushed_item:
await emit(output=flushed_item)
await emit(output=item)
_task_state.pop(message_id, None)
await emit(done=True)
return
@@ -698,6 +705,7 @@ async def run_chat_task(
usage=usage,
done=True,
)
_task_state.pop(message_id, None)
await emit(done=True)
return
@@ -706,7 +714,9 @@ async def run_chat_task(
pass
if not restart:
_flush_text()
flushed_item = _flush_text()
if flushed_item:
await emit(output=flushed_item)
logger.info(
"[task %s] save (end): content=%d chars, output=%d items, types=%s",
message_id[:8],
@@ -720,6 +730,7 @@ async def run_chat_task(
output=output_items,
done=True,
)
_task_state.pop(message_id, None)
await emit(done=True)
return
@@ -731,14 +742,17 @@ async def run_chat_task(
done=True,
meta={"error": "max iterations reached"},
)
_task_state.pop(message_id, None)
await emit(done=True)
except asyncio.CancelledError:
_flush_text()
await ChatMessage.update(message_id, content=content, output=output_items, done=True)
_task_state.pop(message_id, None)
await emit(done=True)
except Exception as e:
logger.exception(f"Chat task error for message {message_id}")
_flush_text()
await ChatMessage.update(
message_id,
content=content,
@@ -746,6 +760,7 @@ async def run_chat_task(
done=True,
meta={"error": str(e)},
)
_task_state.pop(message_id, None)
await emit(done=True)
finally:
_tasks.pop(message_id, None)
+21 -4
View File
@@ -8,12 +8,14 @@ type hints + docstrings via inspect. The LLM never sees the
from __future__ import annotations
import asyncio
import fnmatch
import inspect
import json
import os
import re
import uuid
from pathlib import Path
from typing import get_type_hints
from typing import Callable, Optional, Pattern, get_type_hints
from cptr.env import CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
@@ -250,6 +252,22 @@ async def _search_rg(
async def _search_python(query: str, full: Path, case_insensitive: bool) -> str:
"""Fallback search using pure Python (when ripgrep not installed)."""
def _read_text_for_search(fpath: Path) -> str | None:
"""Read a file for searching, skipping binary-looking files.
Match ripgrep's default binary handling closely enough for the fallback:
files containing NUL bytes are treated as binary and are not decoded or
returned as replacement-character text.
"""
try:
data = fpath.read_bytes()
except (OSError, PermissionError):
return None
if b"\0" in data:
return None
return data.decode(errors="replace")
def _walk_and_search():
results = []
ignore = {".git", "node_modules", "__pycache__", ".venv", "venv"}
@@ -259,9 +277,8 @@ async def _search_python(query: str, full: Path, case_insensitive: bool) -> str:
dirs[:] = [d for d in dirs if d not in ignore]
for fname in files:
fpath = Path(root) / fname
try:
text = fpath.read_text(errors="replace")
except (OSError, PermissionError):
text = _read_text_for_search(fpath)
if text is None:
continue
for i, line in enumerate(text.splitlines(), 1):
target = line.lower() if case_insensitive else line