mirror of
https://github.com/open-webui/computer.git
synced 2026-11-19 04:11:57 +03:00
refac
This commit is contained in:
@@ -36,9 +36,18 @@ export interface ContextUsage {
|
||||
source: 'estimated';
|
||||
}
|
||||
|
||||
export type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled';
|
||||
|
||||
export interface ChatTask {
|
||||
id: string;
|
||||
content: string;
|
||||
status: TaskStatus;
|
||||
}
|
||||
|
||||
export interface ChatDetail {
|
||||
chat: ChatInfo;
|
||||
messages: ChatMessageRow[];
|
||||
tasks?: ChatTask[];
|
||||
context_usage?: ContextUsage | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -86,6 +86,7 @@
|
||||
{ id: 'memory', label: 'models.builtinTools.memory', desc: 'models.builtinTools.memoryDesc' },
|
||||
{ id: 'chats', label: 'models.builtinTools.chats', desc: 'models.builtinTools.chatsDesc' },
|
||||
{ id: 'skills', label: 'models.builtinTools.skills', desc: 'models.builtinTools.skillsDesc' },
|
||||
{ id: 'tasks', label: 'models.builtinTools.tasks', desc: 'models.builtinTools.tasksDesc' },
|
||||
{
|
||||
id: 'automations',
|
||||
label: 'models.builtinTools.automations',
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
|
||||
let enabled = $state(false);
|
||||
let backgroundEnabled = $state(false);
|
||||
let maxConcurrent = $state(3);
|
||||
let maxAsync = $state(3);
|
||||
let maxConcurrent = $state(20);
|
||||
let maxAsync = $state(20);
|
||||
let maxIterations = $state(30);
|
||||
let maxOutput = $state(30000);
|
||||
let systemPrompt = $state('');
|
||||
@@ -24,8 +24,8 @@
|
||||
backgroundEnabled =
|
||||
config['subagents.background_enabled'] === true ||
|
||||
config['subagents.background_enabled'] === 'true';
|
||||
maxConcurrent = Number(config['subagents.max_concurrent']) || 3;
|
||||
maxAsync = Number(config['subagents.max_async']) || 3;
|
||||
maxConcurrent = Number(config['subagents.max_concurrent']) || 20;
|
||||
maxAsync = Number(config['subagents.max_async']) || 20;
|
||||
maxIterations = Number(config['subagents.max_iterations']) || 30;
|
||||
maxOutput = Number(config['subagents.max_output']) || 30000;
|
||||
systemPrompt = (config['subagents.system_prompt'] as string) || '';
|
||||
@@ -87,7 +87,7 @@
|
||||
type="number"
|
||||
bind:value={maxConcurrent}
|
||||
min="1"
|
||||
max="10"
|
||||
max="100"
|
||||
class="w-16 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
<span class="text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
@@ -124,7 +124,7 @@
|
||||
type="number"
|
||||
bind:value={maxAsync}
|
||||
min="1"
|
||||
max="10"
|
||||
max="100"
|
||||
class="w-16 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
<span class="text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import OutputEditView from './OutputEditView.svelte';
|
||||
import ChatFilePreview from './ChatFilePreview.svelte';
|
||||
import ConsecutiveActivityGroup from './ConsecutiveActivityGroup.svelte';
|
||||
import MessageTimestamp from './MessageTimestamp.svelte';
|
||||
import ReasoningCollapsible from './ReasoningCollapsible.svelte';
|
||||
import ToolCallCollapsible from './ToolCallCollapsible.svelte';
|
||||
import { currentWorkspace, openFileTab } from '$lib/stores';
|
||||
@@ -21,6 +22,7 @@
|
||||
usage: Record<string, number> | null;
|
||||
chatId: string | null;
|
||||
messageId: string;
|
||||
createdAt?: number | null;
|
||||
siblingIndex?: number;
|
||||
siblingTotal?: number;
|
||||
speaking?: boolean;
|
||||
@@ -37,6 +39,7 @@
|
||||
usage,
|
||||
chatId,
|
||||
messageId,
|
||||
createdAt = null,
|
||||
siblingIndex = 0,
|
||||
siblingTotal = 1,
|
||||
speaking = false,
|
||||
@@ -593,7 +596,7 @@
|
||||
|
||||
<!-- Controls toolbar -->
|
||||
{#if done || siblingTotal > 1}
|
||||
<div class="flex items-center gap-1 mt-1 -ml-0.5">
|
||||
<div class="group/timestamp-toolbar flex items-center gap-1 mt-1 -ml-0.5">
|
||||
{#if siblingTotal > 1}
|
||||
<button
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 disabled:opacity-30 disabled:cursor-default transition-colors duration-100"
|
||||
@@ -784,6 +787,7 @@
|
||||
>
|
||||
</button>
|
||||
{/if}
|
||||
<MessageTimestamp {createdAt} />
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
@@ -20,12 +20,13 @@
|
||||
import { searchFiles } from '$lib/apis/files';
|
||||
import { getSkills } from '$lib/apis/skills';
|
||||
import { uploadFile } from '$lib/apis/files';
|
||||
import type { ContextUsage } from '$lib/apis/chat';
|
||||
import type { ChatTask, ContextUsage } from '$lib/apis/chat';
|
||||
import ModelSelector from '../common/ModelSelector.svelte';
|
||||
import SendButton from './SendButton.svelte';
|
||||
import PlusMenu from './PlusMenu.svelte';
|
||||
import DictateButton from './DictateButton.svelte';
|
||||
import QueuedMessageItem from './QueuedMessageItem.svelte';
|
||||
import Tasks from './Tasks.svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { planMode } from '$lib/stores';
|
||||
import {
|
||||
@@ -69,6 +70,7 @@
|
||||
workspace?: string;
|
||||
placeholder?: string;
|
||||
contextUsage?: ContextUsage | null;
|
||||
tasks?: ChatTask[];
|
||||
queuedMessages?: { id: string; content: string }[];
|
||||
onsend: () => void;
|
||||
oncompact?: () => void;
|
||||
@@ -88,6 +90,7 @@
|
||||
workspace = '',
|
||||
placeholder = 'Message...',
|
||||
contextUsage = null,
|
||||
tasks = [],
|
||||
queuedMessages = [],
|
||||
onsend,
|
||||
oncompact,
|
||||
@@ -1003,6 +1006,12 @@
|
||||
}}
|
||||
role="presentation"
|
||||
>
|
||||
{#if tasks.length > 0}
|
||||
<div class="mx-1">
|
||||
<Tasks {tasks} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Queued messages (above input, matching open-webui layout) -->
|
||||
{#if queuedMessages.length > 0}
|
||||
<div
|
||||
@@ -1031,7 +1040,10 @@
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Compact: shorten older messages so this chat can keep going."
|
||||
use:tooltip={{ content: 'Shorten older messages so this chat can keep going.', placement: 'right' }}
|
||||
use:tooltip={{
|
||||
content: 'Shorten older messages so this chat can keep going.',
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'compact'
|
||||
? 'app-interactive-active'
|
||||
@@ -1164,9 +1176,7 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'skills:list'
|
||||
? 'app-interactive-active'
|
||||
: ''}"
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'skills:list' ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('skills:list');
|
||||
@@ -1191,14 +1201,13 @@
|
||||
placement: 'right'
|
||||
}}
|
||||
class="slash-command-row flex items-center gap-2 w-full h-6 px-2 rounded-xl text-xs text-left transition-colors duration-75
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'skills:create'
|
||||
? 'app-interactive-active'
|
||||
: ''}"
|
||||
{slashCommandIds[selectedSlashCommandIndex] === 'skills:create' ? 'app-interactive-active' : ''}"
|
||||
onmousedown={(e) => e.preventDefault()}
|
||||
onclick={() => {
|
||||
runSlashCommand('skills:create');
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('skills:create'))}
|
||||
onmouseenter={() =>
|
||||
(selectedSlashCommandIndex = slashCommandIds.indexOf('skills:create'))}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<Icon name="plus" size={14} />
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
type ChatMessageRow,
|
||||
type ChatSendParams,
|
||||
type ChatInfo,
|
||||
type ContextUsage
|
||||
type ContextUsage,
|
||||
type ChatTask
|
||||
} from '$lib/apis/chat';
|
||||
import {
|
||||
chatModels,
|
||||
@@ -80,6 +81,7 @@
|
||||
let allMessages = $state<ChatMessageRow[]>([]);
|
||||
let currentMessageId = $state<string | null>(null);
|
||||
let contextUsage = $state<ContextUsage | null>(null);
|
||||
let chatTasks = $state<ChatTask[]>([]);
|
||||
let showStatusModal = $state(false);
|
||||
let showSkillsModal = $state(false);
|
||||
let skillsModalList = $state<SkillInfo[]>([]);
|
||||
@@ -107,6 +109,7 @@
|
||||
let speakingMessageId = $state<string | null>(null);
|
||||
let ttsStopRequested = false;
|
||||
let commandSessionsChatId: string | null = null;
|
||||
let taskClearTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
// This browser memory cache only helps while the current page is open, such as when
|
||||
// someone taps the same speak button twice. The backend cache is the durable source
|
||||
// for cross-session reuse and the workspace data flywheel.
|
||||
@@ -315,6 +318,23 @@
|
||||
.map((m) => ({ id: m.id, content: m.content }))
|
||||
);
|
||||
|
||||
function setChatTasks(tasks: ChatTask[]) {
|
||||
if (taskClearTimer) {
|
||||
clearTimeout(taskClearTimer);
|
||||
taskClearTimer = null;
|
||||
}
|
||||
chatTasks = tasks;
|
||||
if (
|
||||
tasks.length > 0 &&
|
||||
!tasks.some((task) => task.status === 'pending' || task.status === 'in_progress')
|
||||
) {
|
||||
taskClearTimer = setTimeout(() => {
|
||||
taskClearTimer = null;
|
||||
chatTasks = [];
|
||||
}, 4000);
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (chatId === commandSessionsChatId) return;
|
||||
commandSessionsChatId = chatId;
|
||||
@@ -345,6 +365,13 @@
|
||||
allMessages = data.messages;
|
||||
currentMessageId = data.chat.current_message_id;
|
||||
contextUsage = data.context_usage ?? null;
|
||||
setChatTasks(
|
||||
(data.tasks ?? []).some(
|
||||
(task) => task.status === 'pending' || task.status === 'in_progress'
|
||||
)
|
||||
? (data.tasks ?? [])
|
||||
: []
|
||||
);
|
||||
// Update tab label with the real title from the DB
|
||||
if (tabId && data.chat.title) {
|
||||
chatTitle = data.chat.title;
|
||||
@@ -418,10 +445,12 @@
|
||||
let landingRefreshTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function handleSocketEvent(data: {
|
||||
type?: string;
|
||||
chat_id: string;
|
||||
message_id: string;
|
||||
message_id?: string;
|
||||
delta?: string;
|
||||
output?: any;
|
||||
tasks?: ChatTask[];
|
||||
done?: boolean;
|
||||
error?: string;
|
||||
pending_inputs_processed?: boolean;
|
||||
@@ -454,6 +483,11 @@
|
||||
|
||||
if (data.chat_id !== chatId) return;
|
||||
|
||||
if (data.type === 'chat:tasks') {
|
||||
setChatTasks(data.tasks ?? []);
|
||||
return;
|
||||
}
|
||||
|
||||
// Title generated by backend — update tab label
|
||||
if (data.title && tabId) {
|
||||
updateTab(tabId, data.chat_id, data.title);
|
||||
@@ -465,6 +499,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.message_id) return;
|
||||
const msg = allMessages.find((m) => m.id === data.message_id);
|
||||
if (!msg) return;
|
||||
|
||||
@@ -535,6 +570,9 @@
|
||||
// the DB reload returns. This avoids a transient blank message if the
|
||||
// final `done` socket event beats the commit/read path.
|
||||
msg.done = true;
|
||||
if (chatTasks.some((task) => task.status === 'pending' || task.status === 'in_progress')) {
|
||||
setChatTasks([]);
|
||||
}
|
||||
allMessages = [...allMessages];
|
||||
loadChat(data.chat_id);
|
||||
}
|
||||
@@ -577,6 +615,7 @@
|
||||
commandSessionsTimer = null;
|
||||
window.removeEventListener('cptr:inspect-command-session', handleInspectCommandSession);
|
||||
if (landingRefreshTimer) clearTimeout(landingRefreshTimer);
|
||||
if (taskClearTimer) clearTimeout(taskClearTimer);
|
||||
// Don't clear streamingChatTabs here -- the global listener in
|
||||
// chat.ts handles cleanup when the "done" event arrives, so the
|
||||
// spinner persists even when the chat tab is not active.
|
||||
@@ -1481,6 +1520,7 @@
|
||||
{sending}
|
||||
{workspace}
|
||||
placeholder={$t('chat.placeholder', { name: workspaceDisplayName })}
|
||||
tasks={chatTasks}
|
||||
onsend={send}
|
||||
onstatus={handleStatusCommand}
|
||||
{queuedMessages}
|
||||
@@ -1524,6 +1564,7 @@
|
||||
<UserMessage
|
||||
content={msg.content}
|
||||
meta={msg.meta}
|
||||
createdAt={msg.created_at}
|
||||
{siblingIndex}
|
||||
siblingTotal={siblingIds.length}
|
||||
onnavigate={(dir) => handleNavigate(msg.id, dir)}
|
||||
@@ -1537,6 +1578,7 @@
|
||||
usage={msg.usage}
|
||||
{chatId}
|
||||
messageId={msg.id}
|
||||
createdAt={msg.created_at}
|
||||
{siblingIndex}
|
||||
siblingTotal={siblingIds.length}
|
||||
speaking={speakingMessageId === msg.id}
|
||||
@@ -1590,6 +1632,7 @@
|
||||
{streaming}
|
||||
{workspace}
|
||||
{contextUsage}
|
||||
tasks={chatTasks}
|
||||
onsend={send}
|
||||
oncompact={handleManualCompact}
|
||||
onplan={handlePlanCommand}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<script lang="ts">
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
|
||||
interface Props {
|
||||
createdAt?: number | null;
|
||||
side?: 'left' | 'right';
|
||||
}
|
||||
|
||||
let { createdAt = null, side = 'right' }: Props = $props();
|
||||
|
||||
function toDate(ts: number | null | undefined): Date | null {
|
||||
if (!ts) return null;
|
||||
const date = new Date(ts < 1_000_000_000_000 ? ts * 1000 : ts);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
const date = $derived(toDate(createdAt));
|
||||
const label = $derived(
|
||||
date?.toLocaleString(undefined, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
}) ?? ''
|
||||
);
|
||||
const fullLabel = $derived(
|
||||
date?.toLocaleString(undefined, {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
}) ?? ''
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if date && label}
|
||||
<time
|
||||
datetime={date.toISOString()}
|
||||
class="{side === 'left'
|
||||
? 'mr-1'
|
||||
: 'ml-1'} text-[0.6875rem] tabular-nums text-gray-400 dark:text-gray-600 select-none opacity-0 pointer-events-none transition-opacity duration-100 group-hover/timestamp-toolbar:opacity-100 group-hover/timestamp-toolbar:pointer-events-auto group-focus-within/timestamp-toolbar:opacity-100 group-focus-within/timestamp-toolbar:pointer-events-auto"
|
||||
use:tooltip={fullLabel}
|
||||
>
|
||||
{label}
|
||||
</time>
|
||||
{/if}
|
||||
@@ -0,0 +1,70 @@
|
||||
<script lang="ts">
|
||||
import Icon from '../Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import type { ChatTask } from '$lib/apis/chat';
|
||||
|
||||
interface Props {
|
||||
tasks: ChatTask[];
|
||||
}
|
||||
|
||||
let { tasks }: Props = $props();
|
||||
let collapsed = $state(false);
|
||||
|
||||
const completedCount = $derived(tasks.filter((task) => task.status === 'completed').length);
|
||||
const totalCount = $derived(tasks.length);
|
||||
</script>
|
||||
|
||||
{#if tasks.length > 0}
|
||||
<div class="app-subtle-surface my-1 overflow-hidden rounded-3xl border shadow-sm">
|
||||
<div class="flex items-center justify-between px-3.5 pt-1.5 pb-1">
|
||||
<div class="app-muted flex min-w-0 items-center gap-2 text-xs">
|
||||
<Icon name="list" size={14} />
|
||||
<span class="truncate">
|
||||
{completedCount}
|
||||
{$t('chat.tasksOutOf')}
|
||||
{totalCount}
|
||||
{$t('chat.tasksCompleted')}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="app-muted flex size-6 items-center justify-center rounded-full bg-transparent transition-colors hover:text-gray-600 dark:hover:text-gray-300"
|
||||
onclick={() => (collapsed = !collapsed)}
|
||||
aria-label={collapsed ? $t('chat.tasksExpand') : $t('chat.tasksCollapse')}
|
||||
>
|
||||
<Icon name={collapsed ? 'chevron-down' : 'chevron-up'} size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if !collapsed}
|
||||
<div class="space-y-1 px-2.5 pb-3">
|
||||
{#each tasks as task, idx (task.id)}
|
||||
<div class="flex items-start gap-2 rounded-2xl px-1 py-0.5 text-xs">
|
||||
<span class="app-muted mt-0.5 flex size-3.5 shrink-0 items-center justify-center">
|
||||
{#if task.status === 'completed'}
|
||||
<Icon name="check" size={14} strokeWidth={2.5} />
|
||||
{:else if task.status === 'in_progress'}
|
||||
<span
|
||||
class="size-3 rounded-full border-2 border-current border-t-transparent opacity-70 animate-spin"
|
||||
></span>
|
||||
{:else if task.status === 'cancelled'}
|
||||
<span class="size-3 rounded-full border border-dashed border-current"></span>
|
||||
{:else}
|
||||
<span class="size-3 rounded-full border border-current"></span>
|
||||
{/if}
|
||||
</span>
|
||||
<span
|
||||
class="line-clamp-2 {task.status === 'completed'
|
||||
? 'app-muted line-through'
|
||||
: task.status === 'cancelled'
|
||||
? 'app-muted line-through'
|
||||
: 'text-gray-700 dark:text-gray-300'}"
|
||||
>
|
||||
{idx + 1}. {task.content}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { tick } from 'svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import MessageTimestamp from './MessageTimestamp.svelte';
|
||||
import { fileIconName } from '$lib/utils/fileIcon';
|
||||
import { openFileTab, setFileBrowserCwd, setActiveTab } from '$lib/stores';
|
||||
import { t } from '$lib/i18n';
|
||||
@@ -8,6 +9,7 @@
|
||||
interface Props {
|
||||
content: string;
|
||||
meta?: Record<string, any> | null;
|
||||
createdAt?: number | null;
|
||||
siblingIndex?: number;
|
||||
siblingTotal?: number;
|
||||
onedit?: (content: string, submit: boolean) => void;
|
||||
@@ -16,6 +18,7 @@
|
||||
let {
|
||||
content,
|
||||
meta = null,
|
||||
createdAt = null,
|
||||
siblingIndex = 0,
|
||||
siblingTotal = 1,
|
||||
onedit,
|
||||
@@ -240,7 +243,10 @@
|
||||
</div>
|
||||
</div>
|
||||
{#if siblingTotal > 1 || onedit}
|
||||
<div class="flex justify-end items-center gap-1 mt-0.5 invisible group-hover:visible">
|
||||
<div
|
||||
class="group/timestamp-toolbar flex w-full justify-end items-center gap-1 mt-1 invisible group-hover:visible"
|
||||
>
|
||||
<MessageTimestamp {createdAt} side="left" />
|
||||
{#if siblingTotal > 1}
|
||||
<button
|
||||
class="p-0.5 rounded text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-300 disabled:opacity-30 disabled:cursor-default transition-colors duration-100"
|
||||
|
||||
@@ -577,6 +577,10 @@
|
||||
"chat.tool.backgroundCommand": "Background: {{command}}",
|
||||
"chat.tool.checkTask": "Check task {{id}}",
|
||||
"chat.tool.killTask": "Kill task {{id}}",
|
||||
"chat.tasksOutOf": "out of",
|
||||
"chat.tasksCompleted": "tasks completed",
|
||||
"chat.tasksExpand": "Expand tasks",
|
||||
"chat.tasksCollapse": "Collapse tasks",
|
||||
"chat.asyncSubagentComplete": "Background sub-agent finished",
|
||||
"chat.tool.webSearch": "Search web: \"{{query}}\"",
|
||||
"chat.tool.fetchUrl": "Fetch {{hostname}}",
|
||||
@@ -923,6 +927,8 @@
|
||||
"models.builtinTools.chatsDesc": "Search previous chats",
|
||||
"models.builtinTools.skills": "Skills",
|
||||
"models.builtinTools.skillsDesc": "View and manage Computer skills",
|
||||
"models.builtinTools.tasks": "Tasks",
|
||||
"models.builtinTools.tasksDesc": "Show visible task progress in chat",
|
||||
"models.builtinTools.automations": "Automations",
|
||||
"models.builtinTools.automationsDesc": "List and manage scheduled automations",
|
||||
"models.builtinTools.images": "Images",
|
||||
|
||||
@@ -271,6 +271,9 @@ async def get_chat(
|
||||
|
||||
messages = await ChatMessage.get_all_by_chat(chat_id)
|
||||
context_usage = await _get_chat_context_usage(chat, model_id)
|
||||
from cptr.utils.tools import _normalize_tasks
|
||||
|
||||
tasks = _normalize_tasks((chat.meta or {}).get("tasks"))
|
||||
return {
|
||||
"chat": {
|
||||
"id": chat.id,
|
||||
@@ -282,6 +285,7 @@ async def get_chat(
|
||||
"updated_at": chat.updated_at,
|
||||
},
|
||||
"messages": [_message_dict(m) for m in messages],
|
||||
"tasks": tasks,
|
||||
"context_usage": context_usage,
|
||||
}
|
||||
|
||||
@@ -577,7 +581,11 @@ async def compact_chat(chat_id: str, body: CompactRequest, request: Request):
|
||||
usage = await _get_chat_context_usage(chat, body.model_id)
|
||||
return {"ok": True, "compacted": False, "reason": "too_short", "context_usage": usage}
|
||||
|
||||
from cptr.utils.model_targets import ApiModelTarget, first_api_model_target, resolve_model_target
|
||||
from cptr.utils.model_targets import (
|
||||
ApiModelTarget,
|
||||
first_api_model_target,
|
||||
resolve_model_target,
|
||||
)
|
||||
|
||||
target = await resolve_model_target(body.model_id, request.app.state)
|
||||
if not isinstance(target, ApiModelTarget):
|
||||
|
||||
@@ -39,11 +39,9 @@ async def active_count() -> int:
|
||||
|
||||
async def reserve_async_subagent(max_async: int, **record: Any) -> dict[str, Any]:
|
||||
"""Reserve capacity for a background subagent before creating its chat."""
|
||||
max_async = max(1, int(max_async or 3))
|
||||
max_async = max(1, int(max_async or 20))
|
||||
async with _lock:
|
||||
running = sum(
|
||||
1 for r in _records.values() if r.get("status") in {"starting", "running"}
|
||||
)
|
||||
running = sum(1 for r in _records.values() if r.get("status") in {"starting", "running"})
|
||||
if running >= max_async:
|
||||
return {
|
||||
"status": "rejected",
|
||||
@@ -169,9 +167,7 @@ async def _finalize(
|
||||
|
||||
def _prune_completed_locked() -> None:
|
||||
completed = [
|
||||
(rid, r)
|
||||
for rid, r in _records.items()
|
||||
if r.get("status") not in {"starting", "running"}
|
||||
(rid, r) for rid, r in _records.items() if r.get("status") not in {"starting", "running"}
|
||||
]
|
||||
if len(completed) <= _MAX_RETAINED_COMPLETED:
|
||||
return
|
||||
|
||||
+12
-1
@@ -27,7 +27,14 @@ from cptr.utils.ai import (
|
||||
)
|
||||
from cptr.utils.config import _get_jwt_secret, now_ms
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.tools import ALL_TOOLS, execute_tool, get_tool_list, _fn_to_schema, create_artifact
|
||||
from cptr.utils.tools import (
|
||||
ALL_TOOLS,
|
||||
clear_active_tasks,
|
||||
create_artifact,
|
||||
execute_tool,
|
||||
get_tool_list,
|
||||
_fn_to_schema,
|
||||
)
|
||||
from cptr.utils.chat_export import export_chat_to_file
|
||||
from cptr.utils.json_parser import extract_json
|
||||
from cptr.utils.prompt_templates import load_system_prompt as _load_system_prompt
|
||||
@@ -1282,6 +1289,10 @@ async def run_chat_task(
|
||||
title = "Chat"
|
||||
preview = content[:300] if content else ""
|
||||
ws_name = workspace.rstrip("/").rsplit("/", 1)[-1] if workspace else ""
|
||||
try:
|
||||
await clear_active_tasks(chat_id, user_id, message_id)
|
||||
except Exception:
|
||||
logger.debug("[task %s] clear_active_tasks failed", message_id[:8], exc_info=True)
|
||||
await emit(
|
||||
done=True,
|
||||
title=title,
|
||||
|
||||
+134
-2
@@ -53,6 +53,11 @@ command_sessions: dict[str, dict] = {}
|
||||
MAX_COMMAND_SESSIONS = 5
|
||||
_MAX_LOG_SIZE = 50 * 1024 * 1024 # 50MB — rotate when exceeded
|
||||
|
||||
VALID_TASK_STATUSES = {"pending", "in_progress", "completed", "cancelled"}
|
||||
MAX_TASK_ITEMS = 256
|
||||
MAX_TASK_CONTENT_CHARS = 4000
|
||||
_TASK_TRUNCATION_MARKER = "... [truncated]"
|
||||
|
||||
|
||||
def _spawn_pty(command: str, cwd: str, env: dict) -> tuple:
|
||||
"""Spawn a command under a PTY (Unix only). Returns (proc, master_fd)."""
|
||||
@@ -831,6 +836,131 @@ async def create_artifact(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_tasks(tasks: Any, existing_tasks: Any = None, merge: bool = False) -> list[dict]:
|
||||
if isinstance(tasks, str):
|
||||
try:
|
||||
tasks = json.loads(tasks)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return []
|
||||
if not isinstance(tasks, list):
|
||||
return []
|
||||
|
||||
existing = _normalize_tasks(existing_tasks) if merge else []
|
||||
by_id: dict[str, dict] = {task["id"]: task for task in existing}
|
||||
order: list[str] = [task["id"] for task in existing]
|
||||
next_index = len(order)
|
||||
for item in tasks:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
task_id = str(item.get("id", "") or "").strip()
|
||||
current = by_id.get(task_id) if merge and task_id else None
|
||||
content_value = item.get("content")
|
||||
content = str(content_value).strip() if content_value is not None else ""
|
||||
if len(content) > MAX_TASK_CONTENT_CHARS:
|
||||
keep = MAX_TASK_CONTENT_CHARS - len(_TASK_TRUNCATION_MARKER)
|
||||
content = content[:keep] + _TASK_TRUNCATION_MARKER
|
||||
if current and not content:
|
||||
content = current["content"]
|
||||
if not content:
|
||||
continue
|
||||
status = str(item.get("status", current.get("status") if current else "pending")).lower()
|
||||
if status not in VALID_TASK_STATUSES:
|
||||
status = "pending"
|
||||
task_id = task_id or str(next_index + 1)
|
||||
if task_id in by_id and task_id in order:
|
||||
order.remove(task_id)
|
||||
else:
|
||||
next_index += 1
|
||||
by_id[task_id] = {"id": task_id, "content": content, "status": status}
|
||||
order.append(task_id)
|
||||
return [by_id[task_id] for task_id in order][:MAX_TASK_ITEMS]
|
||||
|
||||
|
||||
async def update_tasks(
|
||||
tasks: list[dict[str, Any]],
|
||||
merge: bool = False,
|
||||
*,
|
||||
__context__: dict,
|
||||
) -> str:
|
||||
"""Update the visible Tasks list for this chat.
|
||||
:param tasks: Task items to show. Each item may include id, content, and status.
|
||||
:param merge: If true, update existing tasks by id and append new ones. If false, replace the list.
|
||||
"""
|
||||
from cptr.models import Chat
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
chat_id = __context__.get("chat_id")
|
||||
user_id = __context__.get("user_id")
|
||||
if not chat_id:
|
||||
return json.dumps({"error": "Chat context not available"})
|
||||
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return json.dumps({"error": "Chat not found"})
|
||||
|
||||
meta = dict(chat.meta or {})
|
||||
next_tasks = _normalize_tasks(tasks, meta.get("tasks"), merge=merge)
|
||||
summary = {
|
||||
"total": len(next_tasks),
|
||||
"pending": sum(1 for task in next_tasks if task["status"] == "pending"),
|
||||
"in_progress": sum(1 for task in next_tasks if task["status"] == "in_progress"),
|
||||
"completed": sum(1 for task in next_tasks if task["status"] == "completed"),
|
||||
"cancelled": sum(1 for task in next_tasks if task["status"] == "cancelled"),
|
||||
}
|
||||
meta["tasks"] = next_tasks
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
|
||||
if user_id:
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:tasks",
|
||||
"chat_id": chat_id,
|
||||
"message_id": __context__.get("message_id"),
|
||||
"tasks": next_tasks,
|
||||
"summary": summary,
|
||||
},
|
||||
)
|
||||
|
||||
return json.dumps({"tasks": next_tasks, "summary": summary}, ensure_ascii=False)
|
||||
|
||||
|
||||
async def clear_active_tasks(
|
||||
chat_id: str, user_id: str | None = None, message_id: str | None = None
|
||||
) -> None:
|
||||
from cptr.models import Chat
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.config import now_ms
|
||||
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
if not chat:
|
||||
return
|
||||
meta = dict(chat.meta or {})
|
||||
tasks = _normalize_tasks(meta.get("tasks"))
|
||||
if not any(task["status"] in {"pending", "in_progress"} for task in tasks):
|
||||
return
|
||||
meta["tasks"] = []
|
||||
await Chat.update_meta(chat_id, meta, now_ms())
|
||||
if user_id:
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:tasks",
|
||||
"chat_id": chat_id,
|
||||
"message_id": message_id,
|
||||
"tasks": [],
|
||||
"summary": {
|
||||
"total": 0,
|
||||
"pending": 0,
|
||||
"in_progress": 0,
|
||||
"completed": 0,
|
||||
"cancelled": 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def write_file(path: str, content: str, *, workspace: str) -> str:
|
||||
"""Write or create a file (full content). Prefer edit_file for modifications.
|
||||
:param path: Path relative to workspace root.
|
||||
@@ -2033,6 +2163,7 @@ TOOLS: dict[str, dict] = {
|
||||
"search_chats": {"fn": search_chats, "auto": True},
|
||||
"list_automations": {"fn": list_automations, "auto": True},
|
||||
"view_skill": {"fn": view_skill, "auto": True},
|
||||
"update_tasks": {"fn": update_tasks, "auto": True},
|
||||
# Write / mutate (require approval unless auto_approve_all)
|
||||
"create_file": {"fn": create_file, "auto": False},
|
||||
"display_file": {"fn": display_file, "auto": False},
|
||||
@@ -2084,10 +2215,10 @@ async def _get_subagent_config() -> dict:
|
||||
from cptr.models import Config
|
||||
|
||||
return {
|
||||
"max_concurrent": int(await Config.get("subagents.max_concurrent") or 3),
|
||||
"max_concurrent": int(await Config.get("subagents.max_concurrent") or 20),
|
||||
"background_enabled": (await Config.get("subagents.background_enabled"))
|
||||
in (True, "true", "1"),
|
||||
"max_async": int(await Config.get("subagents.max_async") or 3),
|
||||
"max_async": int(await Config.get("subagents.max_async") or 20),
|
||||
"max_iterations": int(await Config.get("subagents.max_iterations") or 30),
|
||||
"max_output": int(await Config.get("subagents.max_output") or 30_000),
|
||||
"system_prompt": (await Config.get("subagents.system_prompt")) or _DEFAULT_SUBAGENT_SYSTEM,
|
||||
@@ -2354,6 +2485,7 @@ BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = {
|
||||
"memory": ("update_memory",),
|
||||
"chats": ("search_chats",),
|
||||
"skills": ("view_skill", "manage_skill"),
|
||||
"tasks": ("update_tasks",),
|
||||
"automations": (
|
||||
"list_automations",
|
||||
"create_automation",
|
||||
|
||||
Reference in New Issue
Block a user