mirror of
https://github.com/open-webui/computer.git
synced 2026-12-01 01:12:44 -05:00
refac
This commit is contained in:
1 parent
cdbd446813
commit
d21a3bcf86
13 files changed
+628
-26
No files matched your search
+42
-1
@@ -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():
|
||||
|
||||
@@ -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")
|
||||
@@ -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' }
|
||||
);
|
||||
@@ -626,9 +626,7 @@
|
||||
<DropdownMenu
|
||||
anchor={contextMenu.anchor}
|
||||
items={[
|
||||
...(contextMenu.file.status !== 'untracked'
|
||||
? [{ label: $t('git.discard'), icon: 'xmark', onclick: () => 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) },
|
||||
]}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { theme } from '$lib/stores';
|
||||
import type { Theme } from '$lib/stores';
|
||||
import { theme, streamingBehavior } from '$lib/stores';
|
||||
import type { Theme, StreamingBehavior } from '$lib/stores';
|
||||
import { t, locale, changeLocale, supportedLocales } from '$lib/i18n';
|
||||
|
||||
function setTheme(v: Theme) { theme.set(v); }
|
||||
@@ -40,6 +40,27 @@
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">Message queue</h3>
|
||||
<div class="flex gap-1">
|
||||
{#each [
|
||||
{ value: 'queue' as StreamingBehavior, label: 'Queue' },
|
||||
{ value: 'interrupt' as StreamingBehavior, label: 'Interrupt' },
|
||||
] as opt}
|
||||
<button
|
||||
class="flex items-center gap-1.5 h-7 px-2.5 rounded-lg text-xs transition-colors duration-100
|
||||
{$streamingBehavior === opt.value ? 'bg-gray-100 dark:bg-white/8 text-gray-900 dark:text-white font-medium' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'}"
|
||||
onclick={() => streamingBehavior.set(opt.value)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-1">
|
||||
{$streamingBehavior === 'queue'
|
||||
? 'Messages sent during generation are queued and sent after completion.'
|
||||
: 'Sending a message cancels the current generation.'}
|
||||
</p>
|
||||
|
||||
|
||||
<div class="mt-auto pt-6 flex justify-end">
|
||||
<button
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import SendButton from './SendButton.svelte';
|
||||
import PlusMenu from './PlusMenu.svelte';
|
||||
import DictateButton from './DictateButton.svelte';
|
||||
import QueuedMessageItem from './QueuedMessageItem.svelte';
|
||||
|
||||
interface Props {
|
||||
inputText: string;
|
||||
@@ -18,8 +19,12 @@
|
||||
sending: boolean;
|
||||
streaming?: boolean;
|
||||
placeholder?: string;
|
||||
queuedMessages?: { id: string; content: string }[];
|
||||
onsend: () => void;
|
||||
oncancel?: () => void;
|
||||
onqueuesendnow?: (id: string) => void;
|
||||
onqueueedit?: (id: string) => void;
|
||||
onqueuedelete?: (id: string) => void;
|
||||
}
|
||||
let {
|
||||
inputText = $bindable(),
|
||||
@@ -27,8 +32,12 @@
|
||||
sending,
|
||||
streaming = false,
|
||||
placeholder = 'Message...',
|
||||
queuedMessages = [],
|
||||
onsend,
|
||||
oncancel,
|
||||
onqueuesendnow,
|
||||
onqueueedit,
|
||||
onqueuedelete,
|
||||
}: Props = $props();
|
||||
|
||||
let editorEl: HTMLDivElement | undefined = $state();
|
||||
@@ -119,11 +128,30 @@
|
||||
// TipTap auto-sizes; no-op kept for API compat
|
||||
}
|
||||
|
||||
// Allow sending during streaming (message will be enqueued server-side)
|
||||
const canSend = $derived(inputText.trim() && selectedModel && !sending);
|
||||
</script>
|
||||
|
||||
<div class="relative">
|
||||
<!-- Queued messages (above input, matching open-webui layout) -->
|
||||
{#if queuedMessages.length > 0}
|
||||
<div
|
||||
class="mb-1 mx-2 py-0.5 px-1.5 rounded-2xl border border-gray-100 dark:border-white/5 overflow-x-hidden overflow-y-auto max-h-[25vh]"
|
||||
>
|
||||
{#each queuedMessages as qm (qm.id)}
|
||||
<QueuedMessageItem
|
||||
id={qm.id}
|
||||
content={qm.content}
|
||||
onsendnow={onqueuesendnow ?? (() => {})}
|
||||
onedit={onqueueedit ?? (() => {})}
|
||||
ondelete={onqueuedelete ?? (() => {})}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="rounded-3xl shadow-lg border border-gray-100/40 dark:border-white/4 focus-within:border-gray-200/50 focus-within:dark:border-white/8 transition px-1 bg-white dark:bg-gray-500/5">
|
||||
|
||||
<!-- Editor area -->
|
||||
<div class="px-2.5">
|
||||
<div
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<script lang="ts">
|
||||
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}
|
||||
/>
|
||||
<ChatHistory chats={previousChats} onopen={openChat} ondelete={deleteChat} />
|
||||
</div>
|
||||
@@ -556,14 +687,7 @@
|
||||
<div bind:this={messagesEl} class="flex-1 overflow-y-auto" onscroll={handleMessagesScroll}>
|
||||
<div class="max-w-2xl mx-auto px-4 pt-4 pb-16 flex flex-col gap-4">
|
||||
{#if hasHiddenMessages}
|
||||
<div class="flex justify-center py-2">
|
||||
<button
|
||||
class="text-xs text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors px-3 py-1.5 rounded-full border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 bg-gray-50 dark:bg-gray-800/50"
|
||||
onclick={loadMoreMessages}
|
||||
>
|
||||
Load earlier messages ({activePath.length - visibleCount} hidden)
|
||||
</button>
|
||||
</div>
|
||||
<div bind:this={loadSentinelEl} class="h-1 w-full" aria-hidden="true"></div>
|
||||
{/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}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<script lang="ts">
|
||||
interface Props {
|
||||
id: string;
|
||||
content: string;
|
||||
onsendnow: (id: string) => void;
|
||||
onedit: (id: string) => void;
|
||||
ondelete: (id: string) => void;
|
||||
}
|
||||
let { id, content, onsendnow, onedit, ondelete }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div class="flex items-center gap-2 px-2 py-1">
|
||||
<!-- Queue indicator: reply/forward arrow -->
|
||||
<div class="shrink-0 text-gray-400 dark:text-gray-600">
|
||||
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M13.25 19.25L16.75 15.75L13.25 12.25" />
|
||||
<path d="M16.75 15.75H10.75C8.54086 15.75 6.75 13.9591 6.75 11.75V7.5" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<p class="flex-1 min-w-0 text-xs text-gray-600 dark:text-gray-400 truncate">{content || ''}</p>
|
||||
|
||||
<!-- Actions -->
|
||||
<div class="flex items-center shrink-0">
|
||||
<!-- Send now -->
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 rounded-md text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
title="Send now"
|
||||
onclick={() => onsendnow(id)}
|
||||
>
|
||||
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M4.5 10.5 12 3m0 0 7.5 7.5M12 3v18" />
|
||||
</svg>
|
||||
</button>
|
||||
<!-- Edit -->
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 rounded-md text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
title="Edit"
|
||||
onclick={() => onedit(id)}
|
||||
>
|
||||
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L6.832 19.82a4.5 4.5 0 01-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 011.13-1.897L16.863 4.487zm0 0L19.5 7.125" />
|
||||
</svg>
|
||||
</button>
|
||||
<!-- Remove -->
|
||||
<button
|
||||
type="button"
|
||||
class="p-1 rounded-md text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
title="Remove"
|
||||
onclick={() => ondelete(id)}
|
||||
>
|
||||
<svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -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);
|
||||
</script>
|
||||
|
||||
{#if streaming && oncancel}
|
||||
{#if showStop}
|
||||
<button
|
||||
class="bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-600 transition rounded-full p-1"
|
||||
onclick={oncancel}
|
||||
|
||||
@@ -125,6 +125,8 @@ export const autoApproveTools = {
|
||||
export const stateLoaded = writable(false);
|
||||
export const gitReviewOpen = writable(false);
|
||||
export const isGitRepo = writable(false);
|
||||
export type StreamingBehavior = 'queue' | 'interrupt';
|
||||
export const streamingBehavior = writable<StreamingBehavior>('queue');
|
||||
|
||||
/** Saved workspace path order for sidebar drag-reorder. */
|
||||
export const workspaceOrder = writable<string[]>([]);
|
||||
|
||||
+125
-1
@@ -294,7 +294,7 @@ class SendMessageRequest(BaseModel):
|
||||
@router.post("")
|
||||
async def send_message(body: SendMessageRequest, request: Request):
|
||||
"""Send a message. Omit chat_id to create a new chat.
|
||||
Returns: { chat_id, message_id }
|
||||
Returns: { chat_id, message_id, queued? }
|
||||
"""
|
||||
user_id = _get_user(request)
|
||||
|
||||
@@ -324,6 +324,25 @@ async def send_message(body: SendMessageRequest, request: Request):
|
||||
# Auto-add .cptr to .gitignore if this is a git repo
|
||||
_ensure_gitignore(body.workspace)
|
||||
|
||||
# Check if the chat has an in-progress assistant message.
|
||||
# If so, queue this message instead of starting a new task.
|
||||
if body.chat_id and await _chat_has_active_generation(chat.id):
|
||||
user_msg = await ChatMessage.create(
|
||||
chat_id=chat.id,
|
||||
role="user",
|
||||
content=body.content,
|
||||
parent_id=body.parent_id,
|
||||
meta={"queued": True},
|
||||
created_at=now_ms(),
|
||||
)
|
||||
# Double-check: if generation finished during our create,
|
||||
# process queue now to close the race window.
|
||||
if not await _chat_has_active_generation(chat.id):
|
||||
from cptr.utils.chat_task import _process_queue
|
||||
workspace = (chat.meta or {}).get("workspace", body.workspace)
|
||||
await _process_queue(chat.id, user_id, workspace)
|
||||
return {"chat_id": chat.id, "message_id": user_msg.id, "queued": True}
|
||||
|
||||
# Resolve connection for model
|
||||
connection, bare_model = await _resolve_connection(body.model_id, request.app.state)
|
||||
|
||||
@@ -441,6 +460,10 @@ async def approve_tool(
|
||||
else:
|
||||
call["status"] = "rejected"
|
||||
await ChatMessage.update(message_id, output=output, done=True)
|
||||
# Process queued messages since this chat is now idle
|
||||
from cptr.utils.chat_task import _process_queue
|
||||
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
||||
await _process_queue(chat_id, user_id, workspace)
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
@@ -471,6 +494,11 @@ async def cancel_task_endpoint(
|
||||
item["status"] = "rejected"
|
||||
await ChatMessage.update(message_id, output=output, done=True)
|
||||
|
||||
# Process queued messages since this chat may now be idle
|
||||
from cptr.utils.chat_task import _process_queue
|
||||
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
||||
await _process_queue(chat_id, user_id, workspace)
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@@ -551,6 +579,102 @@ async def create_message_endpoint(
|
||||
await Chat.update_current_message(chat_id, msg.id, now_ms())
|
||||
return {"ok": True, "message_id": msg.id}
|
||||
|
||||
async def _chat_has_active_generation(chat_id: str) -> bool:
|
||||
"""Check if any assistant message in this chat has done=False."""
|
||||
messages = await ChatMessage.get_all_by_chat(chat_id)
|
||||
return any(m.role == "assistant" and not m.done for m in messages)
|
||||
|
||||
|
||||
# ── Queue management ───────────────────────────────────────
|
||||
|
||||
@router.post("/{chat_id}/queue/{message_id}/send")
|
||||
async def queue_send_now(
|
||||
chat_id: str, message_id: str, request: Request
|
||||
):
|
||||
"""Cancel current generation, dequeue this message, send it immediately."""
|
||||
user_id = _get_user(request)
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat or chat.user_id != user_id:
|
||||
raise HTTPException(404, "chat not found")
|
||||
|
||||
msg = await ChatMessage.get_by_id(message_id)
|
||||
if not msg or msg.chat_id != chat_id:
|
||||
raise HTTPException(404, "message not found")
|
||||
if not (msg.meta and msg.meta.get("queued")):
|
||||
raise HTTPException(400, "message is not queued")
|
||||
|
||||
# Cancel any active task
|
||||
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
|
||||
for m in all_msgs:
|
||||
if m.role == "assistant" and not m.done:
|
||||
from cptr.utils.chat_task import cancel_task
|
||||
await cancel_task(m.id)
|
||||
await ChatMessage.update(m.id, done=True)
|
||||
|
||||
# Delete all OTHER queued messages, keep this one
|
||||
for m in all_msgs:
|
||||
if m.role == "user" and m.meta and m.meta.get("queued") and m.id != message_id:
|
||||
await ChatMessage.delete(m.id)
|
||||
|
||||
# Clear queued flag on this message
|
||||
meta = dict(msg.meta or {})
|
||||
meta.pop("queued", None)
|
||||
await ChatMessage.update(message_id, meta=meta or None)
|
||||
|
||||
# Find parent: latest done assistant message, or the queued message's parent
|
||||
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
|
||||
parent_id = done_assistants[-1].id if done_assistants else msg.parent_id
|
||||
|
||||
# Re-parent the user message to the correct leaf
|
||||
if msg.parent_id != parent_id:
|
||||
await ChatMessage.update(message_id, parent_id=parent_id)
|
||||
|
||||
# Resolve connection and start task
|
||||
model_id = msg.model or (all_msgs[-1].model if all_msgs else "")
|
||||
if not model_id:
|
||||
# Fall back to last used model from chat meta
|
||||
model_id = (chat.meta or {}).get("last_model", "")
|
||||
connection, bare_model = await _resolve_connection(model_id, request.app.state)
|
||||
workspace = (chat.meta or {}).get("workspace", "")
|
||||
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=chat_id, role="assistant", content="",
|
||||
parent_id=message_id, model=model_id,
|
||||
done=False, created_at=now_ms(),
|
||||
)
|
||||
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
|
||||
|
||||
from cptr.utils.chat_task import start_task
|
||||
start_task(
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
)
|
||||
return {"ok": True, "chat_id": chat_id, "message_id": assistant_msg.id}
|
||||
|
||||
|
||||
@router.delete("/{chat_id}/queue/{message_id}")
|
||||
async def queue_delete(
|
||||
chat_id: str, message_id: str, request: Request
|
||||
):
|
||||
"""Remove a queued message."""
|
||||
user_id = _get_user(request)
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat or chat.user_id != user_id:
|
||||
raise HTTPException(404, "chat not found")
|
||||
|
||||
msg = await ChatMessage.get_by_id(message_id)
|
||||
if not msg or msg.chat_id != chat_id:
|
||||
raise HTTPException(404, "message not found")
|
||||
if not (msg.meta and msg.meta.get("queued")):
|
||||
raise HTTPException(400, "message is not queued")
|
||||
|
||||
await ChatMessage.delete(message_id)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
async def _resolve_connection(model_id: str, app_state=None) -> tuple[dict, str]:
|
||||
"""Find connection for model.
|
||||
|
||||
@@ -31,6 +31,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_tasks: dict[str, asyncio.Task] = {} # message_id → asyncio.Task
|
||||
_task_state: dict[str, dict] = {} # message_id → {content, output}
|
||||
_task_chat: dict[str, str] = {} # message_id → chat_id
|
||||
_queue_locks: dict[str, asyncio.Lock] = {} # chat_id → Lock
|
||||
|
||||
|
||||
def start_task(
|
||||
@@ -47,6 +49,7 @@ def start_task(
|
||||
run_chat_task(message_id, chat_id, user_id, connection, workspace, model, regeneration_prompt)
|
||||
)
|
||||
_tasks[message_id] = task
|
||||
_task_chat[message_id] = chat_id
|
||||
|
||||
|
||||
async def cancel_task(message_id: str) -> bool:
|
||||
@@ -69,6 +72,153 @@ def get_live_state(message_id: str) -> dict | None:
|
||||
return _task_state.get(message_id)
|
||||
|
||||
|
||||
# ── Queue processing ────────────────────────────────────────
|
||||
|
||||
|
||||
async def _process_queue(chat_id: str, user_id: str, workspace: str):
|
||||
"""Check for queued user messages and start the next task.
|
||||
|
||||
Uses a per-chat lock to prevent concurrent processing from
|
||||
both the task's finally block and the API double-check.
|
||||
"""
|
||||
lock = _queue_locks.setdefault(chat_id, asyncio.Lock())
|
||||
async with lock:
|
||||
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
|
||||
|
||||
# Don't process queue if there's still an active generation
|
||||
if any(m.role == "assistant" and not m.done for m in all_msgs):
|
||||
return
|
||||
|
||||
# Find queued messages (ordered by created_at)
|
||||
queued = [
|
||||
m for m in all_msgs
|
||||
if m.role == "user" and m.meta and m.meta.get("queued")
|
||||
]
|
||||
if not queued:
|
||||
return
|
||||
|
||||
# Combine all queued prompts into one user message
|
||||
combined_content = "\n\n".join(m.content for m in queued if m.content)
|
||||
|
||||
# Find the current leaf (latest done assistant message)
|
||||
done_assistants = [
|
||||
m for m in all_msgs if m.role == "assistant" and m.done
|
||||
]
|
||||
parent_id = (
|
||||
done_assistants[-1].id if done_assistants else queued[0].parent_id
|
||||
)
|
||||
|
||||
# Delete individual queued messages, create one combined message
|
||||
for m in queued:
|
||||
await ChatMessage.delete(m.id)
|
||||
|
||||
combined_msg = await ChatMessage.create(
|
||||
chat_id=chat_id,
|
||||
role="user",
|
||||
content=combined_content,
|
||||
parent_id=parent_id,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
|
||||
# Resolve model from the chat's last used model
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return
|
||||
model_id = (chat.meta or {}).get("last_model", "")
|
||||
if not model_id:
|
||||
# Fall back to the model from the last assistant message
|
||||
last_asst = done_assistants[-1] if done_assistants else None
|
||||
model_id = (last_asst.model if last_asst else "") or ""
|
||||
if not model_id:
|
||||
logger.error("[queue] No model found for chat %s, cannot process queue", chat_id)
|
||||
return
|
||||
|
||||
# Resolve connection
|
||||
try:
|
||||
from cptr.routers.chat import _resolve_connection
|
||||
connection, bare_model = await _resolve_connection(model_id)
|
||||
except Exception:
|
||||
logger.exception("[queue] Failed to resolve connection for model %s", model_id)
|
||||
return
|
||||
|
||||
# Create assistant placeholder
|
||||
assistant_msg = await ChatMessage.create(
|
||||
chat_id=chat_id,
|
||||
role="assistant",
|
||||
content="",
|
||||
parent_id=combined_msg.id,
|
||||
model=model_id,
|
||||
done=False,
|
||||
created_at=now_ms(),
|
||||
)
|
||||
await Chat.update_current_message(chat_id, assistant_msg.id, now_ms())
|
||||
|
||||
# Notify frontend that queue was processed (new messages appeared)
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{"chat_id": chat_id, "message_id": assistant_msg.id, "queue_processed": True},
|
||||
)
|
||||
|
||||
# Start new task
|
||||
start_task(
|
||||
message_id=assistant_msg.id,
|
||||
chat_id=chat_id,
|
||||
user_id=user_id,
|
||||
connection=connection,
|
||||
workspace=workspace,
|
||||
model=bare_model,
|
||||
)
|
||||
logger.info(
|
||||
"[queue] Processed %d queued message(s) for chat %s",
|
||||
len(queued), chat_id[:8],
|
||||
)
|
||||
|
||||
|
||||
async def reconcile_chat_state():
|
||||
"""Recover from server crash: fix stuck messages, process orphaned queues.
|
||||
|
||||
Called once on startup when ENABLE_CHAT_RECONCILE_ON_STARTUP=true (default).
|
||||
Finds:
|
||||
1. Assistant messages with done=False that have no running task → mark done
|
||||
2. Chats with queued user messages → process them
|
||||
"""
|
||||
from sqlalchemy import select, and_
|
||||
from cptr.utils.db import get_db
|
||||
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(
|
||||
select(ChatMessage).where(
|
||||
and_(
|
||||
ChatMessage.role == "assistant",
|
||||
ChatMessage.done == False, # noqa: E712
|
||||
)
|
||||
)
|
||||
)
|
||||
stuck = list(result.scalars().all())
|
||||
|
||||
healed_chats: set[str] = set()
|
||||
for msg in stuck:
|
||||
if not is_running(msg.id):
|
||||
logger.warning("[reconcile] Marking stuck message %s as done", msg.id)
|
||||
meta = dict(msg.meta or {})
|
||||
meta["error"] = "interrupted by server restart"
|
||||
await ChatMessage.update(msg.id, done=True, meta=meta)
|
||||
healed_chats.add(msg.chat_id)
|
||||
|
||||
# Process orphaned queues for healed chats
|
||||
for cid in healed_chats:
|
||||
chat = await Chat.get_by_id(cid)
|
||||
if chat:
|
||||
workspace = (chat.meta or {}).get("workspace", "")
|
||||
try:
|
||||
await _process_queue(cid, chat.user_id, workspace)
|
||||
except Exception:
|
||||
logger.exception("[reconcile] Failed to process queue for chat %s", cid)
|
||||
|
||||
if healed_chats:
|
||||
logger.info("[reconcile] Recovered %d chat(s) on startup", len(healed_chats))
|
||||
|
||||
|
||||
# ── System prompt ───────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -438,6 +588,7 @@ async def run_chat_task(
|
||||
await emit(done=True)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
_flush_text()
|
||||
await ChatMessage.update(
|
||||
message_id, content=content, output=output_items, done=True
|
||||
)
|
||||
@@ -455,7 +606,13 @@ async def run_chat_task(
|
||||
finally:
|
||||
_tasks.pop(message_id, None)
|
||||
_task_state.pop(message_id, None)
|
||||
_task_chat.pop(message_id, None)
|
||||
try:
|
||||
await export_chat_to_file(chat_id)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to export chat {chat_id}")
|
||||
# Process any queued follow-up messages
|
||||
try:
|
||||
await _process_queue(chat_id, user_id, workspace)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to process queue for chat {chat_id}")
|
||||
+23
-2
@@ -204,10 +204,31 @@ async def unstage(root: str, files: list[str]) -> None:
|
||||
|
||||
|
||||
async def discard(root: str, files: list[str]) -> None:
|
||||
"""Discard unstaged changes in files."""
|
||||
"""Discard changes in files. Tracked files are restored via git checkout;
|
||||
untracked files are deleted from disk."""
|
||||
if not files:
|
||||
return
|
||||
await _run("checkout", "--", *files, cwd=root)
|
||||
|
||||
# Determine which files are untracked
|
||||
_, st_out, _ = await _run(
|
||||
"status", "--porcelain=v2", "--untracked-files=all",
|
||||
cwd=root, check=False,
|
||||
)
|
||||
untracked = set()
|
||||
for line in st_out.splitlines():
|
||||
if line.startswith("? "):
|
||||
untracked.add(line[2:])
|
||||
|
||||
tracked = [f for f in files if f not in untracked]
|
||||
to_delete = [f for f in files if f in untracked]
|
||||
|
||||
if tracked:
|
||||
await _run("checkout", "--", *tracked, cwd=root)
|
||||
|
||||
for f in to_delete:
|
||||
full = os.path.join(root, f)
|
||||
if os.path.isfile(full):
|
||||
os.remove(full)
|
||||
|
||||
|
||||
async def commit(root: str, message: str) -> dict[str, str]:
|
||||
|
||||
Reference in new issue
Block a user