From c8f530cbbc8eddd2b3ee017a5f2d8baa9d2180f7 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sat, 11 Jul 2026 20:01:33 -0500 Subject: [PATCH] refac --- .../src/lib/components/GroupTabBar.svelte | 2 +- .../lib/components/chat/AskUserCard.svelte | 51 ++++++++++-------- .../components/chat/AssistantMessage.svelte | 35 +----------- .../src/lib/components/chat/ChatInput.svelte | 22 ++++++++ .../src/lib/components/chat/ChatPanel.svelte | 53 ++++++++++++++++++- cptr/frontend/src/routes/+page.svelte | 2 + cptr/socket/main.py | 32 +++++++++++ cptr/utils/chat_task.py | 8 ++- 8 files changed, 146 insertions(+), 59 deletions(-) diff --git a/cptr/frontend/src/lib/components/GroupTabBar.svelte b/cptr/frontend/src/lib/components/GroupTabBar.svelte index fc231be..3a8933e 100644 --- a/cptr/frontend/src/lib/components/GroupTabBar.svelte +++ b/cptr/frontend/src/lib/components/GroupTabBar.svelte @@ -138,7 +138,7 @@ } function handleContextMenu(e: MouseEvent, tab: Tab) { - if (!isWideScreen) return; + if (!isWideScreen || tab.permanent) return; e.preventDefault(); contextMenu = { tab, x: e.clientX, y: e.clientY }; } diff --git a/cptr/frontend/src/lib/components/chat/AskUserCard.svelte b/cptr/frontend/src/lib/components/chat/AskUserCard.svelte index 30ec79a..ee2cb0e 100644 --- a/cptr/frontend/src/lib/components/chat/AskUserCard.svelte +++ b/cptr/frontend/src/lib/components/chat/AskUserCard.svelte @@ -15,12 +15,12 @@ let { item, pairedOutput, chatId, messageId, onanswer }: Props = $props(); let selections = $state>({}); let otherAnswers = $state>({}); - let now = $state(Date.now()); let submitting = $state(false); + let questionIndex = $state(0); const request = $derived(item.arguments || {}); const questions = $derived(Array.isArray(request.questions) ? request.questions : []); + const question = $derived(questions[questionIndex]); const pending = $derived(item.status === 'pending'); - const secondsRemaining = $derived(Math.max(0, Math.ceil((Number(item.expires_at) - now) / 1000))); const canSubmit = $derived( questions.length > 0 && questions.every((question: any) => { @@ -36,17 +36,6 @@ } }); - $effect(() => { - if (!pending) return; - now = Date.now(); - const timer = window.setInterval(() => (now = Date.now()), 1000); - return () => window.clearInterval(timer); - }); - - function timeLabel(seconds: number) { - return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; - } - function submit(timedOut = false) { if (!chatId || (!canSubmit && !timedOut)) return; const answers: Record = {}; @@ -72,7 +61,7 @@
Planning question
{#if pending}
- Continuing with recommendations in {timeLabel(secondsRemaining)} + {questionIndex + 1} / {questions.length} · paused while this chat is visible
{:else if item.timed_out || resolved.timed_out}
Used recommendations
@@ -80,7 +69,7 @@
- {#each questions as question} + {#if question}
{question.header}
@@ -136,17 +125,35 @@
{/if}
- {/each} + {/if} - {#if pending} +
- {/if} + {#if questionIndex < questions.length - 1} + + {:else if pending} + + {/if} +
diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index 8a791b6..df8ae88 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -8,7 +8,6 @@ import MessageTimestamp from './MessageTimestamp.svelte'; import ReasoningCollapsible from './ReasoningCollapsible.svelte'; import ToolCallCollapsible from './ToolCallCollapsible.svelte'; - import AskUserCard from './AskUserCard.svelte'; import { currentWorkspace, openFileTab } from '$lib/stores'; import { ttsConfigured, ttsEnabled } from '$lib/stores/audio'; import { tooltip } from '$lib/tooltip'; @@ -28,12 +27,6 @@ siblingTotal?: number; speaking?: boolean; onapprove: (messageId: string, callId: string, approved: boolean) => void; - onanswer: ( - messageId: string, - callId: string, - answers: Record, - timedOut: boolean - ) => void; onnavigate?: (direction: -1 | 1) => void; onfork?: () => void; onregenerate?: () => void; @@ -52,7 +45,6 @@ siblingTotal = 1, speaking = false, onapprove, - onanswer, onnavigate, onfork, onregenerate, @@ -270,19 +262,7 @@ index: number; } - interface AskUserItem { - type: 'ask_user_item'; - item: any; - output: any; - } - - type DisplayItem = - | ActivityGroup - | MessageItem - | ArtifactItem - | ImageItem - | FileItem - | AskUserItem; + type DisplayItem = ActivityGroup | MessageItem | ArtifactItem | ImageItem | FileItem; const outputText = $derived.by((): string => { return (output || []) @@ -363,10 +343,7 @@ for (const [index, item] of output.entries()) { if (item.type === 'function_call') { - if (item.name === 'ask_user') { - flushGroup(); - items.push({ type: 'ask_user_item', item, output: outputMap.get(item.call_id) }); - } else { + if (item.name !== 'ask_user') { ensureGroup(); currentGroup!.entries.push(item); currentGroup!.calls.push(item); @@ -572,14 +549,6 @@ {/if} - {:else if displayItem.type === 'ask_user_item'} - {:else if displayItem.type === 'activity_group'} {#if displayItem.entries.length === 1} {@const item = displayItem.entries[0]} diff --git a/cptr/frontend/src/lib/components/chat/ChatInput.svelte b/cptr/frontend/src/lib/components/chat/ChatInput.svelte index b46c675..ae56f27 100644 --- a/cptr/frontend/src/lib/components/chat/ChatInput.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatInput.svelte @@ -27,6 +27,7 @@ import DictateButton from './DictateButton.svelte'; import QueuedMessageItem from './QueuedMessageItem.svelte'; import Tasks from './Tasks.svelte'; + import AskUserCard from './AskUserCard.svelte'; import Icon from '../Icon.svelte'; import { planMode } from '$lib/stores'; import { @@ -71,6 +72,7 @@ placeholder?: string; contextUsage?: ContextUsage | null; tasks?: ChatTask[]; + askUser?: any; queuedMessages?: { id: string; content: string }[]; hasChatContent?: boolean; onsend: () => void; @@ -80,6 +82,12 @@ onstatus?: () => void; onskillslist?: () => void; oncancel?: () => void; + onaskuseranswer?: ( + messageId: string, + callId: string, + answers: Record, + timedOut: boolean + ) => void; onqueuesendnow?: (id: string) => void; onqueueedit?: (id: string) => void; onqueuedelete?: (id: string) => void; @@ -93,6 +101,7 @@ placeholder = 'Message...', contextUsage = null, tasks = [], + askUser = null, queuedMessages = [], hasChatContent = false, onsend, @@ -102,6 +111,7 @@ onstatus, onskillslist, oncancel, + onaskuseranswer, onqueuesendnow, onqueueedit, onqueuedelete @@ -1108,6 +1118,18 @@ }} role="presentation" > + {#if askUser && onaskuseranswer} +
+ +
+ {/if} + {#if tasks.length > 0}
diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index b9a8365..90edf70 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -77,15 +77,45 @@ workspace?: string; chatId?: string; tabId?: string; + active?: boolean; ontabupdate?: (tabId: string, chatId: string, label: string) => void; onopenchat?: (chatId?: string) => void; } - let { workspace = '', chatId: initialChatId, tabId, ontabupdate, onopenchat }: Props = $props(); + let { + workspace = '', + chatId: initialChatId, + tabId, + active = true, + ontabupdate, + onopenchat + }: Props = $props(); let inputText = $state(''); let chatId = $state(initialChatId ?? null); let selectedModel = $state(''); let allMessages = $state([]); + const pendingAskUser = $derived.by(() => { + for (const message of [...allMessages].reverse()) { + const item = message.output?.find( + (output: any) => + output.type === 'function_call' && + output.name === 'ask_user' && + output.status === 'pending' + ); + if (item) { + return { + item, + output: message.output?.find( + (output: any) => + output.type === 'function_call_output' && output.call_id === item.call_id + ), + chatId, + messageId: message.id + }; + } + } + return null; + }); let currentMessageId = $state(null); let contextUsage = $state(null); let chatTasks = $state([]); @@ -699,6 +729,22 @@ return () => unregisterStreamingChat(chatId!); }); + $effect(() => { + if (!chatId || !tabId) return; + const send = () => + socketStore + .getSocket() + ?.emit('chat:view', { chat_id: chatId, view_id: tabId, visible: active }); + send(); + const off = socketStore.on('connect', send); + return () => { + off(); + socketStore + .getSocket() + ?.emit('chat:view', { chat_id: chatId, view_id: tabId, visible: false }); + }; + }); + // ── Auto-scroll ───────────────────────────────────────────── function scrollToBottom() { @@ -1595,6 +1641,8 @@ {workspace} placeholder={$t('chat.placeholder', { name: workspaceDisplayName })} tasks={chatTasks} + askUser={pendingAskUser} + onaskuseranswer={handleAskUserAnswer} onsend={send} onplan={handlePlanCommand} {queuedMessages} @@ -1668,7 +1716,6 @@ onedit={(c, o, submit) => handleEditMessage(msg.id, c, o, submit)} onspeak={() => speakMessage(msg.id)} onapprove={handleApprove} - onanswer={handleAskUserAnswer} /> {/if} {/each} @@ -1716,6 +1763,8 @@ {contextUsage} {hasChatContent} tasks={chatTasks} + askUser={pendingAskUser} + onaskuseranswer={handleAskUserAnswer} onsend={send} oncompact={handleManualCompact} onfork={handleForkChat} diff --git a/cptr/frontend/src/routes/+page.svelte b/cptr/frontend/src/routes/+page.svelte index 597e7ba..22580fd 100644 --- a/cptr/frontend/src/routes/+page.svelte +++ b/cptr/frontend/src/routes/+page.svelte @@ -1042,6 +1042,7 @@ ? undefined : tab.path} tabId={tab.id} + active={tab.id === homePane.activeTabId} ontabupdate={(tabId, chatId, label) => updateHomeChatTab(tabId, chatId, label, homePane.id)} onopenchat={(chatId) => openHomeChat(chatId, homePane.id)} @@ -1373,6 +1374,7 @@ ? undefined : tab.path} tabId={tab.id} + active={tab.id === group.activeTabId} />
{/each} diff --git a/cptr/socket/main.py b/cptr/socket/main.py index 0108d74..c22bd63 100644 --- a/cptr/socket/main.py +++ b/cptr/socket/main.py @@ -16,6 +16,8 @@ sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=CORS_ALLOWED_ # user_id → set of connected sids _user_sids: dict[str, set[str]] = {} +# (user_id, chat_id) → visible panel instances +_chat_view_sids: dict[tuple[str, str], set[tuple[str, str]]] = {} @sio.on("connect") @@ -47,6 +49,32 @@ async def on_disconnect(sid): _user_sids[uid].discard(sid) if not _user_sids[uid]: del _user_sids[uid] + for key, views in list(_chat_view_sids.items()): + views_copy = {view for view in views if view[0] != sid} + if views_copy: + _chat_view_sids[key] = views_copy + else: + del _chat_view_sids[key] + + +@sio.on("chat:view") +async def on_chat_view(sid, data): + """Track which chat panels are currently visible for timeout pausing.""" + session = await sio.get_session(sid) + user_id = session.get("user_id") + chat_id = data.get("chat_id") if isinstance(data, dict) else None + view_id = data.get("view_id") if isinstance(data, dict) else None + if not user_id or not isinstance(chat_id, str) or not isinstance(view_id, str): + return + + views = _chat_view_sids.setdefault((user_id, chat_id), set()) + view = (sid, view_id) + if data.get("visible"): + views.add(view) + else: + views.discard(view) + if not views: + del _chat_view_sids[(user_id, chat_id)] async def emit_to_user(user_id: str, data: dict): @@ -55,6 +83,10 @@ async def emit_to_user(user_id: str, data: dict): await sio.emit("events:chat", data, to=sid) +def is_chat_visible(user_id: str, chat_id: str) -> bool: + return bool(_chat_view_sids.get((user_id, chat_id))) + + def is_user_active(user_id: str) -> bool: """Return True when the user has at least one connected app session.""" return bool(_user_sids.get(user_id)) diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 737c9c7..35e90fd 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -2279,7 +2279,13 @@ async def run_chat_task( _task_state.pop(message_id, None) async def auto_answer(): - await asyncio.sleep(arguments["autoResolutionMs"] / 1000) + from cptr.socket.main import is_chat_visible + + remaining = arguments["autoResolutionMs"] / 1000 + while remaining > 0: + await asyncio.sleep(1) + if not is_chat_visible(user_id, chat_id): + remaining -= 1 from cptr.app import app from cptr.routers.chat import AskUserNotPendingError, resolve_ask_user