From d21a3bcf86afab27102abbccd928669ed27b4a6f Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 6 Jun 2026 01:12:39 -0400 Subject: [PATCH] refac --- cptr/app.py | 43 ++++- cptr/env.py | 3 + cptr/frontend/src/lib/apis/chat.ts | 15 ++ .../frontend/src/lib/components/GitBar.svelte | 4 +- .../lib/components/Settings/General.svelte | 25 ++- .../src/lib/components/chat/ChatInput.svelte | 28 +++ .../src/lib/components/chat/ChatPanel.svelte | 160 ++++++++++++++++-- .../components/chat/QueuedMessageItem.svelte | 60 +++++++ .../src/lib/components/chat/SendButton.svelte | 6 +- cptr/frontend/src/lib/stores.ts | 2 + cptr/routers/chat.py | 126 +++++++++++++- cptr/utils/chat_task.py | 157 +++++++++++++++++ cptr/utils/git.py | 25 ++- 13 files changed, 628 insertions(+), 26 deletions(-) create mode 100644 cptr/frontend/src/lib/components/chat/QueuedMessageItem.svelte diff --git a/cptr/app.py b/cptr/app.py index b17855d..727fc19 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -29,6 +29,11 @@ async def startup(): await init_db() from cptr.env import STARTUP_TOKEN app.state.startup_token = STARTUP_TOKEN + # Reconcile stuck chat state from prior crash/restart + from cptr.env import ENABLE_CHAT_RECONCILE_ON_STARTUP + if ENABLE_CHAT_RECONCILE_ON_STARTUP: + from cptr.utils.chat_task import reconcile_chat_state + await reconcile_chat_state() # Auth middleware @@ -36,7 +41,7 @@ async def startup(): async def auth_middleware(request: Request, call_next): path = request.url.path # Skip auth for: auth endpoints, health, static assets, HTML pages - if path.startswith("/api/auth") or path == "/api/health" or path == "/api/config": + if path.startswith("/api/auth") or path == "/api/health" or path == "/api/config" or path == "/manifest.json": return await call_next(request) if path.startswith("/_app/") or not path.startswith("/api/"): return await call_next(request) @@ -170,6 +175,42 @@ async def health(): return {"status": "ok", "uptime_seconds": int(time.time() - START_TIME), "pid": os.getpid()} +# PWA manifest (backend-driven so each instance has its own identity) +@app.get("/manifest.json") +async def pwa_manifest(): + import socket + from importlib.metadata import version as pkg_version + + try: + hostname = socket.gethostname() + except Exception: + hostname = "" + + try: + version = pkg_version("cptr") + except Exception: + version = "dev" + + name = f"cptr @ {hostname}" if hostname else "cptr" + + return { + "name": name, + "short_name": "cptr", + "description": f"Your computer, from anywhere. v{version}", + "start_url": "/", + "display": "standalone", + "orientation": "any", + "background_color": "#000000", + "theme_color": "#000000", + "icons": [ + {"src": "/icon-192.png", "sizes": "192x192", "type": "image/png"}, + {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png"}, + {"src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}, + ], + "categories": ["developer", "productivity", "utilities"], + } + + # Frontend (unchanged) FRONTEND_BUILD_DIR = Path(__file__).parent / "frontend" / "build" if FRONTEND_BUILD_DIR.exists(): diff --git a/cptr/env.py b/cptr/env.py index 4c9b24e..75a8d9e 100644 --- a/cptr/env.py +++ b/cptr/env.py @@ -22,3 +22,6 @@ STARTUP_TOKEN: str | None = os.environ.pop("CPTR_STARTUP_TOKEN", None) # ── Chat settings ─────────────────────────────────────────── CHAT_MAX_ITERATIONS = int(os.environ.get("CHAT_MAX_ITERATIONS", "2048")) +ENABLE_CHAT_RECONCILE_ON_STARTUP: bool = os.environ.get( + "ENABLE_CHAT_RECONCILE_ON_STARTUP", "true" +).lower() in ("true", "1", "yes") diff --git a/cptr/frontend/src/lib/apis/chat.ts b/cptr/frontend/src/lib/apis/chat.ts index 892ee50..e6ac7c1 100644 --- a/cptr/frontend/src/lib/apis/chat.ts +++ b/cptr/frontend/src/lib/apis/chat.ts @@ -35,6 +35,7 @@ export interface ChatDetail { export interface SendMessageResult { chat_id: string; message_id: string; + queued?: boolean; } // ── Queries ───────────────────────────────────────────────── @@ -114,3 +115,17 @@ export const createMessage = ( `/api/chats/${chatId}/messages`, jsonBody({ parent_id: parentId, role, content, output }) ); + +// ── Queue management ──────────────────────────────────────── + +export const queueSendNow = (chatId: string, messageId: string) => + fetchJSON<{ ok: boolean; chat_id: string; message_id: string }>( + `/api/chats/${chatId}/queue/${messageId}/send`, + { method: 'POST' } + ); + +export const queueDelete = (chatId: string, messageId: string) => + fetchJSON<{ ok: boolean }>( + `/api/chats/${chatId}/queue/${messageId}`, + { method: 'DELETE' } + ); diff --git a/cptr/frontend/src/lib/components/GitBar.svelte b/cptr/frontend/src/lib/components/GitBar.svelte index 5be8b14..cc175be 100644 --- a/cptr/frontend/src/lib/components/GitBar.svelte +++ b/cptr/frontend/src/lib/components/GitBar.svelte @@ -626,9 +626,7 @@ discardFile(contextMenu!.file.path) }] - : []), + { label: $t('git.discard'), icon: 'xmark', onclick: () => discardFile(contextMenu!.file.path) }, { label: $t('git.copyFilePath'), icon: 'copy', onclick: () => copyFilePath(contextMenu!.file.path) }, { label: $t('git.copyRelativePath'), icon: 'copy', onclick: () => copyRelativePath(contextMenu!.file.path) }, ]} diff --git a/cptr/frontend/src/lib/components/Settings/General.svelte b/cptr/frontend/src/lib/components/Settings/General.svelte index d8b1052..f9cdee0 100644 --- a/cptr/frontend/src/lib/components/Settings/General.svelte +++ b/cptr/frontend/src/lib/components/Settings/General.svelte @@ -1,8 +1,8 @@
+ + {#if queuedMessages.length > 0} +
+ {#each queuedMessages as qm (qm.id)} + {})} + onedit={onqueueedit ?? (() => {})} + ondelete={onqueuedelete ?? (() => {})} + /> + {/each} +
+ {/if} +
+
- import { getChat, getChats, deleteChat as apiDeleteChat, sendMessage as apiSendMessage, approveToolCall, cancelTask, updateCurrentMessage, updateMessage, createMessage, type ChatMessageRow, type ChatInfo } from '$lib/apis/chat'; + import { getChat, getChats, deleteChat as apiDeleteChat, sendMessage as apiSendMessage, approveToolCall, cancelTask, updateCurrentMessage, updateMessage, createMessage, queueSendNow as apiQueueSendNow, queueDelete as apiQueueDelete, type ChatMessageRow, type ChatInfo } from '$lib/apis/chat'; import { chatModels, defaultModel, streamingChatTabs, registerStreamingChat, unregisterStreamingChat } from '$lib/stores/chat'; import { socketStore } from '$lib/stores/socket.svelte'; import { onMount, onDestroy, tick } from 'svelte'; import { get } from 'svelte/store'; - import { currentWorkspace, toolApprovalMode } from '$lib/stores'; + import { currentWorkspace, toolApprovalMode, streamingBehavior } from '$lib/stores'; import ChatInput from './ChatInput.svelte'; import UserMessage from './UserMessage.svelte'; @@ -75,8 +75,12 @@ const activePath = $derived.by((): PathEntry[] => { if (!allMessages.length) return []; - const msgMap = new Map(allMessages.map((m) => [m.id, m])); - const childrenMap = buildChildrenMap(allMessages); + // Exclude queued messages from the display path — they only appear in the queue UI + const displayMessages = allMessages.filter((m) => !(m.meta?.queued)); + if (!displayMessages.length) return []; + + const msgMap = new Map(displayMessages.map((m) => [m.id, m])); + const childrenMap = buildChildrenMap(displayMessages); // Determine effective currentId: fall back to last message if unset const effectiveId = currentMessageId && msgMap.has(currentMessageId) @@ -118,8 +122,13 @@ hasHiddenMessages ? activePath.slice(activePath.length - visibleCount) : activePath ); + let loadSentinelEl: HTMLDivElement; + let loadObserver: IntersectionObserver | null = null; + let loadingMore = false; + function loadMoreMessages() { - if (!messagesEl) return; + if (!messagesEl || loadingMore) return; + loadingMore = true; // Remember scroll height before loading more so we can maintain position const prevScrollHeight = messagesEl.scrollHeight; @@ -131,13 +140,43 @@ const newScrollHeight = messagesEl.scrollHeight; messagesEl.scrollTop += newScrollHeight - prevScrollHeight; } + loadingMore = false; }); } + // Set up IntersectionObserver to auto-load earlier messages when sentinel is visible + $effect(() => { + if (hasHiddenMessages && loadSentinelEl && messagesEl) { + loadObserver = new IntersectionObserver( + (entries) => { + if (entries[0]?.isIntersecting && hasHiddenMessages) { + loadMoreMessages(); + } + }, + { root: messagesEl, threshold: 0 } + ); + loadObserver.observe(loadSentinelEl); + } + + return () => { + if (loadObserver) { + loadObserver.disconnect(); + loadObserver = null; + } + }; + }); + const streaming = $derived(allMessages.some((m) => m.role === 'assistant' && !m.done)); const isLanding = $derived(allMessages.length === 0 && !chatId); const workspaceName = $derived(workspace.split('/').pop() || 'workspace'); + // Queued messages: user messages with meta.queued flag (server-side queue) + const queuedMessages = $derived( + allMessages + .filter((m) => m.role === 'user' && m.meta?.queued) + .map((m) => ({ id: m.id, content: m.content })) + ); + // ── Load chat from DB ─────────────────────────────────────── async function loadChat(id: string) { @@ -180,8 +219,16 @@ delta?: string; output?: any; done?: boolean; + queue_processed?: boolean; }) { if (data.chat_id !== chatId) return; + + // Queue was processed server-side: reload to see combined message + new generation + if (data.queue_processed) { + loadChat(data.chat_id); + return; + } + const msg = allMessages.find((m) => m.id === data.message_id); if (!msg) return; @@ -327,7 +374,8 @@ async function send() { const text = inputText.trim(); - if (!text || !selectedModel || sending) return; + if (!text || !selectedModel) return; + if (sending) return; sending = true; inputText = ''; autoScroll = true; @@ -339,7 +387,49 @@ const parentId = lastMsg?.id ?? null; const isNew = !chatId; - // ── Optimistic UI: add user message immediately ────────── + // When streaming and behavior is 'queue', backend will enqueue + // When streaming and behavior is 'interrupt', cancel first then send normally + if (streaming && chatId) { + const behavior = get(streamingBehavior); + if (behavior === 'interrupt') { + // Cancel active generation, then fall through to normal send + const active = allMessages.find((m) => m.role === 'assistant' && !m.done); + if (active) { + try { await cancelTask(chatId, active.id); } catch {} + await loadChat(chatId); + } + } else { + try { + const mode = get(toolApprovalMode); + const result = await apiSendMessage(text, selectedModel, workspace, chatId, parentId, { tool_approval_mode: mode }); + if (result.queued) { + // Add directly to allMessages so it appears in queue UI instantly + allMessages = [...allMessages, { + id: result.message_id, + parent_id: parentId, + role: 'user' as const, + content: text, + model: null, + done: true, + output: null, + usage: null, + meta: { queued: true }, + created_at: Date.now(), + }]; + } else { + await loadChat(result.chat_id); + } + } catch (e) { + console.error('[chat] send (queue) error', e); + } finally { + sending = false; + chatInputEl?.focus(); + } + return; + } // end queue behavior + } // end streaming check + + // ── Normal flow: optimistic UI ──────────────────────────── const tempId = `temp-${Date.now()}`; const optimisticMsg: ChatMessageRow = { id: tempId, @@ -370,7 +460,6 @@ } } catch (e) { console.error('[chat] send error', e); - // Remove the optimistic message on failure allMessages = allMessages.filter((m) => m.id !== tempId); currentMessageId = parentId; throw e; @@ -380,6 +469,44 @@ } } + // ── Queue actions ────────────────────────────────────────── + + async function handleQueueSendNow(messageId: string) { + if (!chatId) return; + try { + await apiQueueSendNow(chatId, messageId); + await loadChat(chatId); + } catch (e) { + console.error('[chat] queue send-now error', e); + } + } + + async function handleQueueEdit(messageId: string) { + if (!chatId) return; + // Move content back to input, delete from queue + const msg = allMessages.find((m) => m.id === messageId); + if (msg) { + inputText = msg.content; + chatInputEl?.focus(); + } + try { + await apiQueueDelete(chatId, messageId); + await loadChat(chatId); + } catch (e) { + console.error('[chat] queue edit error', e); + } + } + + async function handleQueueDelete(messageId: string) { + if (!chatId) return; + try { + await apiQueueDelete(chatId, messageId); + await loadChat(chatId); + } catch (e) { + console.error('[chat] queue delete error', e); + } + } + async function handleCancel() { const active = allMessages.find((m) => m.role === 'assistant' && !m.done); if (!active || !chatId) return; @@ -538,6 +665,10 @@ {sending} placeholder="Ask anything about {workspaceName}..." onsend={send} + {queuedMessages} + onqueuesendnow={handleQueueSendNow} + onqueueedit={handleQueueEdit} + onqueuedelete={handleQueueDelete} />
@@ -556,14 +687,7 @@
{#if hasHiddenMessages} -
- -
+ {/if} {#each visiblePath as { msg, siblingIds, siblingIndex } (msg.id)} {#if msg.role === 'user'} @@ -618,6 +742,10 @@ {streaming} onsend={send} oncancel={handleCancel} + {queuedMessages} + onqueuesendnow={handleQueueSendNow} + onqueueedit={handleQueueEdit} + onqueuedelete={handleQueueDelete} />
diff --git a/cptr/frontend/src/lib/components/chat/QueuedMessageItem.svelte b/cptr/frontend/src/lib/components/chat/QueuedMessageItem.svelte new file mode 100644 index 0000000..6e618bc --- /dev/null +++ b/cptr/frontend/src/lib/components/chat/QueuedMessageItem.svelte @@ -0,0 +1,60 @@ + + +
+ +
+ + + + +
+ + +

{content || ''}

+ + +
+ + + + + + +
+
diff --git a/cptr/frontend/src/lib/components/chat/SendButton.svelte b/cptr/frontend/src/lib/components/chat/SendButton.svelte index 779f6c4..3e604a4 100644 --- a/cptr/frontend/src/lib/components/chat/SendButton.svelte +++ b/cptr/frontend/src/lib/components/chat/SendButton.svelte @@ -6,9 +6,13 @@ oncancel?: () => void; } let { canSend, streaming, onsend, oncancel }: Props = $props(); + + // Show send when there's sendable text, even during streaming (enqueue). + // Show stop only when streaming with nothing to send. + const showStop = $derived(streaming && !canSend && !!oncancel); -{#if streaming && oncancel} +{#if showStop}