This commit is contained in:
Timothy Jaeryang Baek
2026-07-11 20:01:33 -05:00
Unverified
parent 1e14d49de2
commit c8f530cbbc
8 changed files with 146 additions and 59 deletions
@@ -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 };
}
@@ -15,12 +15,12 @@
let { item, pairedOutput, chatId, messageId, onanswer }: Props = $props();
let selections = $state<Record<string, string>>({});
let otherAnswers = $state<Record<string, string>>({});
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<string, string> = {};
@@ -72,7 +61,7 @@
<div class="text-xs font-medium text-gray-800 dark:text-gray-100">Planning question</div>
{#if pending}
<div class="text-[0.6875rem] text-gray-500 dark:text-gray-400">
Continuing with recommendations in {timeLabel(secondsRemaining)}
{questionIndex + 1} / {questions.length} · paused while this chat is visible
</div>
{:else if item.timed_out || resolved.timed_out}
<div class="text-[0.6875rem] text-gray-500 dark:text-gray-400">Used recommendations</div>
@@ -80,7 +69,7 @@
</div>
<div class="space-y-4 px-3 py-3">
{#each questions as question}
{#if question}
<div class="space-y-2">
<div>
<div class="text-xs font-medium text-gray-800 dark:text-gray-100">{question.header}</div>
@@ -136,17 +125,35 @@
</div>
{/if}
</div>
{/each}
{/if}
{#if pending}
<div class="flex items-center justify-between gap-2">
<button
type="button"
class="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white disabled:cursor-not-allowed disabled:opacity-40 dark:bg-white dark:text-black"
disabled={!canSubmit || submitting}
onclick={() => submit()}
class="rounded-lg px-2.5 py-1.5 text-xs text-gray-600 hover:bg-gray-100 disabled:opacity-30 dark:text-gray-300 dark:hover:bg-white/10"
disabled={questionIndex === 0}
onclick={() => (questionIndex -= 1)}
>
Submit answers
Previous
</button>
{/if}
{#if questionIndex < questions.length - 1}
<button
type="button"
class="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white dark:bg-white dark:text-black"
onclick={() => (questionIndex += 1)}
>
Next
</button>
{:else if pending}
<button
type="button"
class="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white disabled:cursor-not-allowed disabled:opacity-40 dark:bg-white dark:text-black"
disabled={!canSubmit || submitting}
onclick={() => submit()}
>
Submit answers
</button>
{/if}
</div>
</div>
</section>
@@ -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<string, string>,
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 @@
<ChatFilePreview {file} {filePath} />
{/if}
</div>
{:else if displayItem.type === 'ask_user_item'}
<AskUserCard
item={displayItem.item}
pairedOutput={displayItem.output}
{chatId}
{messageId}
{onanswer}
/>
{:else if displayItem.type === 'activity_group'}
{#if displayItem.entries.length === 1}
{@const item = displayItem.entries[0]}
@@ -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<string, string>,
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}
<div class="mx-1">
<AskUserCard
item={askUser.item}
pairedOutput={askUser.output}
chatId={askUser.chatId}
messageId={askUser.messageId}
onanswer={onaskuseranswer}
/>
</div>
{/if}
{#if tasks.length > 0}
<div class="mx-1">
<Tasks {tasks} />
@@ -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<string | null>(initialChatId ?? null);
let selectedModel = $state('');
let allMessages = $state<ChatMessageRow[]>([]);
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<string | null>(null);
let contextUsage = $state<ContextUsage | null>(null);
let chatTasks = $state<ChatTask[]>([]);
@@ -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}
+2
View File
@@ -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}
/>
</div>
{/each}
+32
View File
@@ -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))
+7 -1
View File
@@ -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