mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
29 files changed
+1059
-93
No files matched your search
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.8.1] - 2026-07-06
|
||||
|
||||
### Added
|
||||
|
||||
- ✅ **Visible task progress.** Chats can now show a live checklist so long-running work is easier to follow.
|
||||
- 🕒 **Message timestamps.** Hover over message controls to see when a message was sent.
|
||||
|
||||
### Changed
|
||||
|
||||
- 🧰 **Better model tool control.** Admins can choose which built-in tool groups each model can use, from files and terminal access to web, memory, images, and sub-agents.
|
||||
- 🚀 **More flexible sub-agents.** Sub-agent limits now support higher defaults and unlimited mode for teams that want more parallel work.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 💬 **More reliable chat lists.** Chat history stays in the right order more consistently, even when a saved chat needs extra cleanup.
|
||||
- ✨ **Cleaner skill suggestions.** Skill matches in chat now use a simpler, more consistent icon.
|
||||
|
||||
## [0.8.0] - 2026-07-06
|
||||
|
||||
### Added
|
||||
|
||||
@@ -170,6 +170,7 @@ export interface ModelConfigEntry {
|
||||
request_params?: Record<string, unknown>;
|
||||
system_prompt?: string;
|
||||
compact_token_threshold?: number;
|
||||
builtin_tools?: Record<string, boolean> | null;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
import Icon from '../Icon.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import ModelSelector from '$lib/components/common/ModelSelector.svelte';
|
||||
import ToggleSwitch from '$lib/components/common/ToggleSwitch.svelte';
|
||||
|
||||
type ParamRow = { key: string; value: string };
|
||||
type BuiltinToolsConfig = Record<string, boolean>;
|
||||
type ModelEntry = {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -25,6 +27,7 @@
|
||||
rows: ParamRow[];
|
||||
systemPrompt: string;
|
||||
compactTokenThreshold: number | null;
|
||||
builtinTools: BuiltinToolsConfig;
|
||||
dirty: boolean;
|
||||
};
|
||||
|
||||
@@ -37,6 +40,7 @@
|
||||
let globalRows = $state<ParamRow[]>([]);
|
||||
let globalSystemPrompt = $state('');
|
||||
let globalCompactTokenThreshold = $state<number | null>(null);
|
||||
let globalBuiltinTools = $state<BuiltinToolsConfig>({});
|
||||
let globalDirty = $state(false);
|
||||
let globalExpanded = $state(false);
|
||||
let showVariables = $state(false);
|
||||
@@ -66,6 +70,41 @@
|
||||
{ name: 'MODEL', desc: 'Model ID being used' }
|
||||
];
|
||||
|
||||
const BUILTIN_TOOL_GROUPS = [
|
||||
{ id: 'files', label: 'models.builtinTools.files', desc: 'models.builtinTools.filesDesc' },
|
||||
{
|
||||
id: 'terminal',
|
||||
label: 'models.builtinTools.terminal',
|
||||
desc: 'models.builtinTools.terminalDesc'
|
||||
},
|
||||
{ id: 'web', label: 'models.builtinTools.web', desc: 'models.builtinTools.webDesc' },
|
||||
{
|
||||
id: 'browser',
|
||||
label: 'models.builtinTools.browser',
|
||||
desc: 'models.builtinTools.browserDesc'
|
||||
},
|
||||
{ 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',
|
||||
desc: 'models.builtinTools.automationsDesc'
|
||||
},
|
||||
{ id: 'images', label: 'models.builtinTools.images', desc: 'models.builtinTools.imagesDesc' },
|
||||
{
|
||||
id: 'subagents',
|
||||
label: 'models.builtinTools.subagents',
|
||||
desc: 'models.builtinTools.subagentsDesc'
|
||||
},
|
||||
{
|
||||
id: 'notifications',
|
||||
label: 'models.builtinTools.notifications',
|
||||
desc: 'models.builtinTools.notificationsDesc'
|
||||
}
|
||||
];
|
||||
|
||||
const DEFAULT_PROMPT_PLACEHOLDER = `You are Computer, a helpful assistant running inside the user's computer interface. You have access to tools to read, search, and modify files in the workspace, run commands, and use configured tools. Use them to help the user directly. Approach hard requests with initiative and persistence: make the best possible attempt, adapt as needed, and keep going unless a real constraint prevents progress.
|
||||
|
||||
{{CPTR_CONTEXT}}
|
||||
@@ -95,6 +134,60 @@ Files:
|
||||
return Number.isFinite(threshold) && threshold > 0 ? Math.floor(threshold) : null;
|
||||
}
|
||||
|
||||
function parseBuiltinTools(config: ModelConfigEntry | undefined): BuiltinToolsConfig {
|
||||
const value = config?.params?.builtin_tools;
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).filter(([, enabled]) => typeof enabled === 'boolean')
|
||||
);
|
||||
}
|
||||
|
||||
function builtinEnabled(
|
||||
tools: BuiltinToolsConfig,
|
||||
group: string,
|
||||
inherited: BuiltinToolsConfig | null = null
|
||||
): boolean {
|
||||
if (tools[group] !== undefined) return tools[group] !== false;
|
||||
if (inherited?.[group] !== undefined) return inherited[group] !== false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function setBuiltinEnabled(
|
||||
tools: BuiltinToolsConfig,
|
||||
group: string,
|
||||
enabled: boolean,
|
||||
inherited: BuiltinToolsConfig | null = null
|
||||
): BuiltinToolsConfig {
|
||||
const next = { ...tools };
|
||||
const inheritedEnabled = inherited?.[group] !== undefined ? inherited[group] !== false : true;
|
||||
if (enabled === inheritedEnabled) {
|
||||
delete next[group];
|
||||
} else {
|
||||
next[group] = enabled;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function serializeBuiltinTools(
|
||||
tools: BuiltinToolsConfig,
|
||||
inherited: BuiltinToolsConfig | null = null
|
||||
): BuiltinToolsConfig | null {
|
||||
const result: BuiltinToolsConfig = {};
|
||||
for (const group of BUILTIN_TOOL_GROUPS) {
|
||||
if (tools[group.id] === undefined) continue;
|
||||
const inheritedEnabled =
|
||||
inherited?.[group.id] !== undefined ? inherited[group.id] !== false : true;
|
||||
if (tools[group.id] !== inheritedEnabled) {
|
||||
result[group.id] = tools[group.id];
|
||||
}
|
||||
}
|
||||
return Object.keys(result).length ? result : null;
|
||||
}
|
||||
|
||||
function configuredRowCount(rows: ParamRow[]): number {
|
||||
return rows.filter((row) => row.key.trim()).length;
|
||||
}
|
||||
|
||||
function rowsToRequestParams(rows: ParamRow[]): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const { key, value } of rows) {
|
||||
@@ -119,8 +212,12 @@ Files:
|
||||
globalRows = parseRows(config['*']);
|
||||
globalSystemPrompt = config['*']?.params?.system_prompt || '';
|
||||
globalCompactTokenThreshold = parseCompactTokenThreshold(config['*']);
|
||||
globalBuiltinTools = parseBuiltinTools(config['*']);
|
||||
globalExpanded =
|
||||
globalRows.length > 0 || !!globalSystemPrompt || globalCompactTokenThreshold !== null;
|
||||
globalRows.length > 0 ||
|
||||
!!globalSystemPrompt ||
|
||||
globalCompactTokenThreshold !== null ||
|
||||
Object.keys(globalBuiltinTools).length > 0;
|
||||
}
|
||||
|
||||
models = data.models.map((m) => {
|
||||
@@ -136,6 +233,7 @@ Files:
|
||||
rows: parseRows(mc),
|
||||
systemPrompt: (mc?.params as any)?.system_prompt || '',
|
||||
compactTokenThreshold: parseCompactTokenThreshold(mc),
|
||||
builtinTools: parseBuiltinTools(mc),
|
||||
dirty: false
|
||||
};
|
||||
});
|
||||
@@ -204,13 +302,17 @@ Files:
|
||||
function buildParams(
|
||||
rows: ParamRow[],
|
||||
systemPrompt: string,
|
||||
compactThreshold: number | null
|
||||
compactThreshold: number | null,
|
||||
builtinTools: BuiltinToolsConfig,
|
||||
inheritedBuiltinTools: BuiltinToolsConfig | null = null
|
||||
): Record<string, unknown> {
|
||||
const params: Record<string, unknown> = {};
|
||||
const rp = rowsToRequestParams(rows);
|
||||
const bt = serializeBuiltinTools(builtinTools, inheritedBuiltinTools);
|
||||
if (Object.keys(rp).length) params.request_params = rp;
|
||||
if (systemPrompt.trim()) params.system_prompt = systemPrompt.trim();
|
||||
if (compactThreshold && compactThreshold > 0) params.compact_token_threshold = compactThreshold;
|
||||
if (bt) params.builtin_tools = bt;
|
||||
return params;
|
||||
}
|
||||
|
||||
@@ -221,7 +323,12 @@ Files:
|
||||
if (globalDirty) {
|
||||
promises.push(
|
||||
updateModelConfig('*', {
|
||||
params: buildParams(globalRows, globalSystemPrompt, globalCompactTokenThreshold)
|
||||
params: buildParams(
|
||||
globalRows,
|
||||
globalSystemPrompt,
|
||||
globalCompactTokenThreshold,
|
||||
globalBuiltinTools
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -229,7 +336,13 @@ Files:
|
||||
if (model.dirty) {
|
||||
promises.push(
|
||||
updateModelConfig(model.id, {
|
||||
params: buildParams(model.rows, model.systemPrompt, model.compactTokenThreshold)
|
||||
params: buildParams(
|
||||
model.rows,
|
||||
model.systemPrompt,
|
||||
model.compactTokenThreshold,
|
||||
model.builtinTools,
|
||||
globalBuiltinTools
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -380,6 +493,47 @@ Files:
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet builtinToolsField(
|
||||
tools: BuiltinToolsConfig,
|
||||
inherited: BuiltinToolsConfig | null,
|
||||
onChange: (tools: BuiltinToolsConfig) => void,
|
||||
resetLabel: string
|
||||
)}
|
||||
<div class="mb-2">
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<span class="text-[0.625rem] text-gray-400 dark:text-gray-600 uppercase tracking-wide"
|
||||
>{$t('models.builtinTools')}</span
|
||||
>
|
||||
{#if Object.keys(tools).length > 0}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 dark:text-gray-600 hover:text-gray-600 dark:hover:text-gray-400 transition-colors duration-75"
|
||||
onclick={() => onChange({})}
|
||||
>
|
||||
{resetLabel}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-x-3 gap-y-1">
|
||||
{#each BUILTIN_TOOL_GROUPS as group}
|
||||
<div class="flex items-center justify-between gap-2 min-h-7">
|
||||
<div class="min-w-0">
|
||||
<div class="text-[0.75rem] text-gray-600 dark:text-gray-400 truncate">
|
||||
{$t(group.label)}
|
||||
</div>
|
||||
<div class="text-[0.625rem] text-gray-400 dark:text-gray-600 truncate">
|
||||
{$t(group.desc)}
|
||||
</div>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={builtinEnabled(tools, group.id, inherited)}
|
||||
onchange={(enabled) => onChange(setBuiltinEnabled(tools, group.id, enabled, inherited))}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
{#if loading}
|
||||
<div class="flex justify-center py-8"><Spinner size={16} /></div>
|
||||
@@ -448,11 +602,11 @@ Files:
|
||||
<span class="flex-1 text-[0.8125rem] text-gray-500 dark:text-gray-400"
|
||||
>{$t('models.defaults')}</span
|
||||
>
|
||||
{#if globalRows.filter((r) => r.key.trim()).length > 0 || globalSystemPrompt.trim()}
|
||||
{#if configuredRowCount(globalRows) > 0 || globalSystemPrompt.trim()}
|
||||
<span class="text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{#if globalSystemPrompt.trim()}prompt{/if}
|
||||
{#if globalRows.filter((r) => r.key.trim()).length > 0}
|
||||
{globalRows.filter((r) => r.key.trim()).length} params
|
||||
{#if configuredRowCount(globalRows) > 0}
|
||||
{configuredRowCount(globalRows)} params
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
@@ -480,6 +634,15 @@ Files:
|
||||
},
|
||||
DEFAULT_PROMPT_PLACEHOLDER
|
||||
)}
|
||||
{@render builtinToolsField(
|
||||
globalBuiltinTools,
|
||||
null,
|
||||
(tools) => {
|
||||
globalBuiltinTools = tools;
|
||||
globalDirty = true;
|
||||
},
|
||||
$t('models.resetToDefault')
|
||||
)}
|
||||
{@render paramRows(
|
||||
globalRows,
|
||||
() => (globalDirty = true),
|
||||
@@ -546,6 +709,16 @@ Files:
|
||||
},
|
||||
$t('models.systemPromptInherited')
|
||||
)}
|
||||
{@render builtinToolsField(
|
||||
model.builtinTools,
|
||||
globalBuiltinTools,
|
||||
(tools) => {
|
||||
model.builtinTools = tools;
|
||||
model.dirty = true;
|
||||
models = [...models];
|
||||
},
|
||||
$t('models.resetToDefault')
|
||||
)}
|
||||
{@render paramRows(
|
||||
model.rows,
|
||||
() => (model.dirty = true),
|
||||
|
||||
@@ -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) || '';
|
||||
@@ -86,8 +86,7 @@
|
||||
id="sa-concurrent"
|
||||
type="number"
|
||||
bind:value={maxConcurrent}
|
||||
min="1"
|
||||
max="10"
|
||||
min="-1"
|
||||
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"
|
||||
@@ -123,8 +122,7 @@
|
||||
id="sa-async"
|
||||
type="number"
|
||||
bind:value={maxAsync}
|
||||
min="1"
|
||||
max="10"
|
||||
min="-1"
|
||||
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"
|
||||
|
||||
@@ -83,6 +83,10 @@
|
||||
<path d="M16 9.2C15.2 9.2 14.5 9.7 14.2 10.4" />
|
||||
<path d="M8.6 14.2C9.4 14.2 10.1 13.8 10.5 13.1" />
|
||||
<path d="M15.4 14.2C14.6 14.2 13.9 13.8 13.5 13.1" />
|
||||
{:else if name === 'spark'}
|
||||
<path
|
||||
d="M3 12C9.26752 12 12 9.36306 12 3C12 9.36306 14.7134 12 21 12C14.7134 12 12 14.7134 12 21C12 14.7134 9.26752 12 3 12Z"
|
||||
/>
|
||||
{:else if name === 'plus'}
|
||||
<path d="M6 12H12M18 12H12M12 12V6M12 12V18" />
|
||||
{:else if name === 'xmark'}
|
||||
|
||||
@@ -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,
|
||||
@@ -501,7 +504,7 @@
|
||||
{@const fileKey = filePath || file.path || `file-${displayItem.index}`}
|
||||
{@const collapsed = Boolean(collapsedFiles[fileKey])}
|
||||
<div
|
||||
class="my-2 w-full max-w-2xl overflow-hidden rounded-md border border-gray-200 bg-white dark:border-white/8 dark:bg-gray-950/20"
|
||||
class="my-2 w-full max-w-2xl overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-white/8 dark:bg-gray-950/20"
|
||||
>
|
||||
<div
|
||||
class="flex h-8 items-center {collapsed
|
||||
@@ -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}
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface SuggestionItem {
|
||||
@@ -32,7 +33,7 @@
|
||||
{#if items.length === 0}
|
||||
<div class="app-muted flex items-center h-6 px-2 text-xs">{$t('chat.noSkillsFound')}</div>
|
||||
{:else}
|
||||
<div class="app-muted px-2 pt-1 pb-0.5 text-[0.625rem] leading-none">
|
||||
<div class="app-muted mb-0.5 px-2 pt-1 pb-0.5 text-[0.625rem] leading-none">
|
||||
{$t('chat.skills')}
|
||||
</div>
|
||||
<div bind:this={listEl}>
|
||||
@@ -49,11 +50,7 @@
|
||||
title={item.description}
|
||||
>
|
||||
<span class="app-icon-muted flex items-center justify-center w-4 shrink-0">
|
||||
<svg viewBox="0 0 16 16" fill="currentColor" class="size-3.5">
|
||||
<path
|
||||
d="M8.75 1a.75.75 0 0 0-1.5 0v1.249c-1.373.158-2.476.682-3.33 1.536C3.066 4.639 2.5 5.77 2.5 7.25c0 1.296-.266 2.193-.613 2.852-.35.663-.83 1.132-1.268 1.507a.75.75 0 0 0 .494 1.315h3.137a3.75 3.75 0 0 0 7.5 0h3.137a.75.75 0 0 0 .494-1.315c-.438-.375-.919-.844-1.268-1.507-.347-.659-.613-1.556-.613-2.852 0-1.48-.566-2.611-1.42-3.465-.854-.854-1.957-1.378-3.33-1.536V1ZM6.5 12.924a2.25 2.25 0 0 0 3 0h-3Z"
|
||||
/>
|
||||
</svg>
|
||||
<Icon name="spark" size={13} strokeWidth={1.7} />
|
||||
</span>
|
||||
<span class="flex-1 min-w-0 flex items-baseline gap-1.5 overflow-hidden">
|
||||
<span class="truncate">{item.label}</span>
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "Chat-Vervollständigungen",
|
||||
"connections.responses": "Antworten",
|
||||
"admin.agentsNoProfiles": "Keine Agentenprofile",
|
||||
"models.builtinTools": "Integrierte Tools",
|
||||
"models.builtinTools.files": "Dateien",
|
||||
"models.builtinTools.filesDesc": "Workspace-Dateien lesen, suchen, erstellen und bearbeiten",
|
||||
"models.builtinTools.terminal": "Terminal",
|
||||
"models.builtinTools.terminalDesc": "Befehle ausführen und Befehlssitzungen verwalten",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Das Web durchsuchen und URLs lesen",
|
||||
"models.builtinTools.browser": "Browser",
|
||||
"models.builtinTools.browserDesc": "Seiten öffnen, prüfen, anklicken, Texte eingeben, Screenshots erstellen und auswerten",
|
||||
"models.builtinTools.memory": "Speicher",
|
||||
"models.builtinTools.memoryDesc": "Dauerhafte Benutzer- und Workspace-Erinnerungen speichern",
|
||||
"models.builtinTools.chats": "Chats",
|
||||
"models.builtinTools.chatsDesc": "Frühere Chats durchsuchen",
|
||||
"models.builtinTools.skills": "Skills",
|
||||
"models.builtinTools.skillsDesc": "Computer-Skills anzeigen und verwalten",
|
||||
"models.builtinTools.automations": "Automatisierungen",
|
||||
"models.builtinTools.automationsDesc": "Geplante Automatisierungen auflisten und verwalten",
|
||||
"models.builtinTools.images": "Bilder",
|
||||
"models.builtinTools.imagesDesc": "Bilder erstellen oder bearbeiten",
|
||||
"models.builtinTools.subagents": "Subagenten",
|
||||
"models.builtinTools.subagentsDesc": "Aufgaben an Subagenten delegieren",
|
||||
"models.builtinTools.notifications": "Benachrichtigungen",
|
||||
"models.builtinTools.notificationsDesc": "Benutzerbenachrichtigungen senden",
|
||||
"models.requestParams": "Anfrageparameter",
|
||||
"models.paramKey": "Schlüssel",
|
||||
"models.paramValue": "Wert",
|
||||
|
||||
@@ -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}}",
|
||||
@@ -908,6 +912,31 @@
|
||||
"connections.chatCompletions": "Chat Completions",
|
||||
"connections.responses": "Responses",
|
||||
"admin.agentsNoProfiles": "No agent profiles",
|
||||
"models.builtinTools": "Builtin Tools",
|
||||
"models.builtinTools.files": "Files",
|
||||
"models.builtinTools.filesDesc": "Read, search, create, and edit workspace files",
|
||||
"models.builtinTools.terminal": "Terminal",
|
||||
"models.builtinTools.terminalDesc": "Run commands and manage command sessions",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Search the web and read URLs",
|
||||
"models.builtinTools.browser": "Browser",
|
||||
"models.builtinTools.browserDesc": "Navigate, inspect, click, type, screenshot, and evaluate pages",
|
||||
"models.builtinTools.memory": "Memory",
|
||||
"models.builtinTools.memoryDesc": "Save durable user and workspace memories",
|
||||
"models.builtinTools.chats": "Chats",
|
||||
"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",
|
||||
"models.builtinTools.imagesDesc": "Generate or edit images",
|
||||
"models.builtinTools.subagents": "Subagents",
|
||||
"models.builtinTools.subagentsDesc": "Delegate work to sub-agents",
|
||||
"models.builtinTools.notifications": "Notifications",
|
||||
"models.builtinTools.notificationsDesc": "Send user notifications",
|
||||
"models.requestParams": "Request params",
|
||||
"models.paramKey": "key",
|
||||
"models.paramValue": "value",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "Completados de chat",
|
||||
"connections.responses": "Respuestas",
|
||||
"admin.agentsNoProfiles": "No hay perfiles de agente",
|
||||
"models.builtinTools": "Herramientas integradas",
|
||||
"models.builtinTools.files": "Archivos",
|
||||
"models.builtinTools.filesDesc": "Leer, buscar, crear y editar archivos del espacio de trabajo",
|
||||
"models.builtinTools.terminal": "Terminal",
|
||||
"models.builtinTools.terminalDesc": "Ejecutar comandos y administrar sesiones de comandos",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Buscar en la web y leer URLs",
|
||||
"models.builtinTools.browser": "Navegador",
|
||||
"models.builtinTools.browserDesc": "Navegar, inspeccionar, hacer clic, escribir, capturar pantalla y evaluar páginas",
|
||||
"models.builtinTools.memory": "Memoria",
|
||||
"models.builtinTools.memoryDesc": "Guardar recuerdos duraderos del usuario y del espacio de trabajo",
|
||||
"models.builtinTools.chats": "Chats",
|
||||
"models.builtinTools.chatsDesc": "Buscar chats anteriores",
|
||||
"models.builtinTools.skills": "Habilidades",
|
||||
"models.builtinTools.skillsDesc": "Ver y administrar habilidades de Computer",
|
||||
"models.builtinTools.automations": "Automatizaciones",
|
||||
"models.builtinTools.automationsDesc": "Listar y administrar automatizaciones programadas",
|
||||
"models.builtinTools.images": "Imágenes",
|
||||
"models.builtinTools.imagesDesc": "Generar o editar imágenes",
|
||||
"models.builtinTools.subagents": "Subagentes",
|
||||
"models.builtinTools.subagentsDesc": "Delegar trabajo a subagentes",
|
||||
"models.builtinTools.notifications": "Notificaciones",
|
||||
"models.builtinTools.notificationsDesc": "Enviar notificaciones al usuario",
|
||||
"models.requestParams": "Parámetros de solicitud",
|
||||
"models.paramKey": "clave",
|
||||
"models.paramValue": "valor",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "Complétions de chat",
|
||||
"connections.responses": "Réponses",
|
||||
"admin.agentsNoProfiles": "Aucun profil d’agent",
|
||||
"models.builtinTools": "Outils intégrés",
|
||||
"models.builtinTools.files": "Fichiers",
|
||||
"models.builtinTools.filesDesc": "Lire, rechercher, créer et modifier les fichiers de l’espace de travail",
|
||||
"models.builtinTools.terminal": "Terminal",
|
||||
"models.builtinTools.terminalDesc": "Exécuter des commandes et gérer les sessions de commande",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Rechercher sur le web et lire des URL",
|
||||
"models.builtinTools.browser": "Navigateur",
|
||||
"models.builtinTools.browserDesc": "Naviguer, inspecter, cliquer, saisir, capturer et évaluer des pages",
|
||||
"models.builtinTools.memory": "Mémoire",
|
||||
"models.builtinTools.memoryDesc": "Enregistrer des souvenirs durables de l’utilisateur et de l’espace de travail",
|
||||
"models.builtinTools.chats": "Chats",
|
||||
"models.builtinTools.chatsDesc": "Rechercher dans les chats précédents",
|
||||
"models.builtinTools.skills": "Compétences",
|
||||
"models.builtinTools.skillsDesc": "Afficher et gérer les compétences Computer",
|
||||
"models.builtinTools.automations": "Automatisations",
|
||||
"models.builtinTools.automationsDesc": "Lister et gérer les automatisations planifiées",
|
||||
"models.builtinTools.images": "Images",
|
||||
"models.builtinTools.imagesDesc": "Générer ou modifier des images",
|
||||
"models.builtinTools.subagents": "Sous-agents",
|
||||
"models.builtinTools.subagentsDesc": "Déléguer le travail à des sous-agents",
|
||||
"models.builtinTools.notifications": "Notifications",
|
||||
"models.builtinTools.notificationsDesc": "Envoyer des notifications utilisateur",
|
||||
"models.requestParams": "Paramètres de requête",
|
||||
"models.paramKey": "clé",
|
||||
"models.paramValue": "valeur",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "チャット補完",
|
||||
"connections.responses": "レスポンス",
|
||||
"admin.agentsNoProfiles": "エージェントプロファイルがありません",
|
||||
"models.builtinTools": "組み込みツール",
|
||||
"models.builtinTools.files": "ファイル",
|
||||
"models.builtinTools.filesDesc": "ワークスペースのファイルを読み取り、検索、作成、編集します",
|
||||
"models.builtinTools.terminal": "ターミナル",
|
||||
"models.builtinTools.terminalDesc": "コマンドの実行とコマンドセッションの管理を行います",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Web を検索し、URL を読み取ります",
|
||||
"models.builtinTools.browser": "ブラウザ",
|
||||
"models.builtinTools.browserDesc": "ページの移動、検査、クリック、入力、スクリーンショット、評価を行います",
|
||||
"models.builtinTools.memory": "メモリ",
|
||||
"models.builtinTools.memoryDesc": "ユーザーとワークスペースの永続的な記憶を保存します",
|
||||
"models.builtinTools.chats": "チャット",
|
||||
"models.builtinTools.chatsDesc": "過去のチャットを検索します",
|
||||
"models.builtinTools.skills": "スキル",
|
||||
"models.builtinTools.skillsDesc": "Computer のスキルを表示および管理します",
|
||||
"models.builtinTools.automations": "自動化",
|
||||
"models.builtinTools.automationsDesc": "スケジュール済みの自動化を一覧表示して管理します",
|
||||
"models.builtinTools.images": "画像",
|
||||
"models.builtinTools.imagesDesc": "画像を生成または編集します",
|
||||
"models.builtinTools.subagents": "サブエージェント",
|
||||
"models.builtinTools.subagentsDesc": "作業をサブエージェントに委任します",
|
||||
"models.builtinTools.notifications": "通知",
|
||||
"models.builtinTools.notificationsDesc": "ユーザー通知を送信します",
|
||||
"models.requestParams": "リクエストパラメータ",
|
||||
"models.paramKey": "キー",
|
||||
"models.paramValue": "値",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "채팅 완성",
|
||||
"connections.responses": "응답",
|
||||
"admin.agentsNoProfiles": "에이전트 프로필 없음",
|
||||
"models.builtinTools": "내장 도구",
|
||||
"models.builtinTools.files": "파일",
|
||||
"models.builtinTools.filesDesc": "워크스페이스 파일을 읽고, 검색하고, 만들고, 편집합니다",
|
||||
"models.builtinTools.terminal": "터미널",
|
||||
"models.builtinTools.terminalDesc": "명령을 실행하고 명령 세션을 관리합니다",
|
||||
"models.builtinTools.web": "웹",
|
||||
"models.builtinTools.webDesc": "웹을 검색하고 URL을 읽습니다",
|
||||
"models.builtinTools.browser": "브라우저",
|
||||
"models.builtinTools.browserDesc": "페이지를 탐색, 검사, 클릭, 입력, 스크린샷 촬영, 평가합니다",
|
||||
"models.builtinTools.memory": "메모리",
|
||||
"models.builtinTools.memoryDesc": "사용자와 워크스페이스의 지속 메모리를 저장합니다",
|
||||
"models.builtinTools.chats": "채팅",
|
||||
"models.builtinTools.chatsDesc": "이전 채팅을 검색합니다",
|
||||
"models.builtinTools.skills": "스킬",
|
||||
"models.builtinTools.skillsDesc": "Computer 스킬을 보고 관리합니다",
|
||||
"models.builtinTools.automations": "자동화",
|
||||
"models.builtinTools.automationsDesc": "예약된 자동화를 나열하고 관리합니다",
|
||||
"models.builtinTools.images": "이미지",
|
||||
"models.builtinTools.imagesDesc": "이미지를 생성하거나 편집합니다",
|
||||
"models.builtinTools.subagents": "하위 에이전트",
|
||||
"models.builtinTools.subagentsDesc": "작업을 하위 에이전트에 위임합니다",
|
||||
"models.builtinTools.notifications": "알림",
|
||||
"models.builtinTools.notificationsDesc": "사용자 알림을 보냅니다",
|
||||
"models.requestParams": "요청 매개변수",
|
||||
"models.paramKey": "키",
|
||||
"models.paramValue": "값",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "Completações de chat",
|
||||
"connections.responses": "Respostas",
|
||||
"admin.agentsNoProfiles": "Nenhum perfil de agente",
|
||||
"models.builtinTools": "Ferramentas integradas",
|
||||
"models.builtinTools.files": "Arquivos",
|
||||
"models.builtinTools.filesDesc": "Ler, pesquisar, criar e editar arquivos do espaço de trabalho",
|
||||
"models.builtinTools.terminal": "Terminal",
|
||||
"models.builtinTools.terminalDesc": "Executar comandos e gerenciar sessões de comando",
|
||||
"models.builtinTools.web": "Web",
|
||||
"models.builtinTools.webDesc": "Pesquisar na web e ler URLs",
|
||||
"models.builtinTools.browser": "Navegador",
|
||||
"models.builtinTools.browserDesc": "Navegar, inspecionar, clicar, digitar, capturar tela e avaliar páginas",
|
||||
"models.builtinTools.memory": "Memória",
|
||||
"models.builtinTools.memoryDesc": "Salvar memórias duráveis do usuário e do espaço de trabalho",
|
||||
"models.builtinTools.chats": "Chats",
|
||||
"models.builtinTools.chatsDesc": "Pesquisar chats anteriores",
|
||||
"models.builtinTools.skills": "Habilidades",
|
||||
"models.builtinTools.skillsDesc": "Ver e gerenciar habilidades do Computer",
|
||||
"models.builtinTools.automations": "Automações",
|
||||
"models.builtinTools.automationsDesc": "Listar e gerenciar automações agendadas",
|
||||
"models.builtinTools.images": "Imagens",
|
||||
"models.builtinTools.imagesDesc": "Gerar ou editar imagens",
|
||||
"models.builtinTools.subagents": "Subagentes",
|
||||
"models.builtinTools.subagentsDesc": "Delegar trabalho a subagentes",
|
||||
"models.builtinTools.notifications": "Notificações",
|
||||
"models.builtinTools.notificationsDesc": "Enviar notificações ao usuário",
|
||||
"models.requestParams": "Parâmetros da requisição",
|
||||
"models.paramKey": "chave",
|
||||
"models.paramValue": "valor",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "Чат-завершения",
|
||||
"connections.responses": "Ответы",
|
||||
"admin.agentsNoProfiles": "Нет профилей агентов",
|
||||
"models.builtinTools": "Встроенные инструменты",
|
||||
"models.builtinTools.files": "Файлы",
|
||||
"models.builtinTools.filesDesc": "Чтение, поиск, создание и редактирование файлов рабочей области",
|
||||
"models.builtinTools.terminal": "Терминал",
|
||||
"models.builtinTools.terminalDesc": "Запуск команд и управление командными сеансами",
|
||||
"models.builtinTools.web": "Веб",
|
||||
"models.builtinTools.webDesc": "Поиск в интернете и чтение URL",
|
||||
"models.builtinTools.browser": "Браузер",
|
||||
"models.builtinTools.browserDesc": "Навигация, проверка, клики, ввод, скриншоты и оценка страниц",
|
||||
"models.builtinTools.memory": "Память",
|
||||
"models.builtinTools.memoryDesc": "Сохранение долговременной памяти пользователя и рабочей области",
|
||||
"models.builtinTools.chats": "Чаты",
|
||||
"models.builtinTools.chatsDesc": "Поиск по прошлым чатам",
|
||||
"models.builtinTools.skills": "Навыки",
|
||||
"models.builtinTools.skillsDesc": "Просмотр и управление навыками Computer",
|
||||
"models.builtinTools.automations": "Автоматизации",
|
||||
"models.builtinTools.automationsDesc": "Список и управление запланированными автоматизациями",
|
||||
"models.builtinTools.images": "Изображения",
|
||||
"models.builtinTools.imagesDesc": "Создание или редактирование изображений",
|
||||
"models.builtinTools.subagents": "Субагенты",
|
||||
"models.builtinTools.subagentsDesc": "Делегирование работы субагентам",
|
||||
"models.builtinTools.notifications": "Уведомления",
|
||||
"models.builtinTools.notificationsDesc": "Отправка уведомлений пользователю",
|
||||
"models.requestParams": "Параметры запроса",
|
||||
"models.paramKey": "ключ",
|
||||
"models.paramValue": "значение",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "聊天补全",
|
||||
"connections.responses": "响应",
|
||||
"admin.agentsNoProfiles": "没有代理配置",
|
||||
"models.builtinTools": "内置工具",
|
||||
"models.builtinTools.files": "文件",
|
||||
"models.builtinTools.filesDesc": "读取、搜索、创建和编辑工作区文件",
|
||||
"models.builtinTools.terminal": "终端",
|
||||
"models.builtinTools.terminalDesc": "运行命令并管理命令会话",
|
||||
"models.builtinTools.web": "网页",
|
||||
"models.builtinTools.webDesc": "搜索网页并读取 URL",
|
||||
"models.builtinTools.browser": "浏览器",
|
||||
"models.builtinTools.browserDesc": "导航、检查、点击、输入、截图和评估页面",
|
||||
"models.builtinTools.memory": "记忆",
|
||||
"models.builtinTools.memoryDesc": "保存持久的用户和工作区记忆",
|
||||
"models.builtinTools.chats": "聊天",
|
||||
"models.builtinTools.chatsDesc": "搜索以前的聊天",
|
||||
"models.builtinTools.skills": "技能",
|
||||
"models.builtinTools.skillsDesc": "查看和管理 Computer 技能",
|
||||
"models.builtinTools.automations": "自动化",
|
||||
"models.builtinTools.automationsDesc": "列出并管理计划自动化",
|
||||
"models.builtinTools.images": "图片",
|
||||
"models.builtinTools.imagesDesc": "生成或编辑图片",
|
||||
"models.builtinTools.subagents": "子代理",
|
||||
"models.builtinTools.subagentsDesc": "将工作委派给子代理",
|
||||
"models.builtinTools.notifications": "通知",
|
||||
"models.builtinTools.notificationsDesc": "发送用户通知",
|
||||
"models.requestParams": "请求参数",
|
||||
"models.paramKey": "键",
|
||||
"models.paramValue": "值",
|
||||
|
||||
@@ -906,6 +906,29 @@
|
||||
"connections.chatCompletions": "聊天補全",
|
||||
"connections.responses": "回應",
|
||||
"admin.agentsNoProfiles": "沒有代理設定檔",
|
||||
"models.builtinTools": "內建工具",
|
||||
"models.builtinTools.files": "檔案",
|
||||
"models.builtinTools.filesDesc": "讀取、搜尋、建立和編輯工作區檔案",
|
||||
"models.builtinTools.terminal": "終端機",
|
||||
"models.builtinTools.terminalDesc": "執行命令並管理命令工作階段",
|
||||
"models.builtinTools.web": "網頁",
|
||||
"models.builtinTools.webDesc": "搜尋網頁並讀取 URL",
|
||||
"models.builtinTools.browser": "瀏覽器",
|
||||
"models.builtinTools.browserDesc": "導覽、檢查、點擊、輸入、截圖和評估頁面",
|
||||
"models.builtinTools.memory": "記憶",
|
||||
"models.builtinTools.memoryDesc": "儲存持久的使用者和工作區記憶",
|
||||
"models.builtinTools.chats": "聊天",
|
||||
"models.builtinTools.chatsDesc": "搜尋過去的聊天",
|
||||
"models.builtinTools.skills": "技能",
|
||||
"models.builtinTools.skillsDesc": "檢視和管理 Computer 技能",
|
||||
"models.builtinTools.automations": "自動化",
|
||||
"models.builtinTools.automationsDesc": "列出並管理排程自動化",
|
||||
"models.builtinTools.images": "圖片",
|
||||
"models.builtinTools.imagesDesc": "生成或編輯圖片",
|
||||
"models.builtinTools.subagents": "子代理",
|
||||
"models.builtinTools.subagentsDesc": "將工作委派給子代理",
|
||||
"models.builtinTools.notifications": "通知",
|
||||
"models.builtinTools.notificationsDesc": "傳送使用者通知",
|
||||
"models.requestParams": "請求參數",
|
||||
"models.paramKey": "鍵",
|
||||
"models.paramValue": "值",
|
||||
|
||||
+145
-33
@@ -56,26 +56,31 @@ async def list_chats(
|
||||
if not chats_dir.exists():
|
||||
return {"chats": [], "total": 0, "has_more": False}
|
||||
|
||||
# Scan filesystem for chat JSON files in a thread
|
||||
# Scan filesystem for chat files.
|
||||
def _scan_chat_files() -> list[dict]:
|
||||
entries = []
|
||||
chat_files = []
|
||||
for json_file in chats_dir.rglob("*.json"):
|
||||
chat_id = json_file.stem
|
||||
rel_folder = str(json_file.parent.relative_to(chats_dir))
|
||||
if rel_folder == ".":
|
||||
rel_folder = ""
|
||||
entries.append({"id": chat_id, "folder": rel_folder})
|
||||
return entries
|
||||
chat_files.append(
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"folder": rel_folder,
|
||||
"path": json_file,
|
||||
}
|
||||
)
|
||||
return chat_files
|
||||
|
||||
chat_entries = await asyncio.to_thread(_scan_chat_files)
|
||||
chat_files = await asyncio.to_thread(_scan_chat_files)
|
||||
|
||||
if not chat_entries:
|
||||
if not chat_files:
|
||||
return {"chats": [], "total": 0, "has_more": False}
|
||||
|
||||
# Batch-fetch from DB
|
||||
chat_ids = [e["id"] for e in chat_entries]
|
||||
chats = await Chat.get_by_ids(chat_ids)
|
||||
chat_map = {c.id: c for c in chats}
|
||||
db_chats = await Chat.get_by_ids([chat_file["chat_id"] for chat_file in chat_files])
|
||||
chat_by_id = {chat.id: chat for chat in db_chats}
|
||||
|
||||
# Detect which chats have a running task (in-memory check, no DB hit)
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
@@ -83,31 +88,130 @@ async def list_chats(
|
||||
active_ids = get_active_chat_ids()
|
||||
|
||||
# Build response: only include chats owned by this user
|
||||
result = []
|
||||
for entry in chat_entries:
|
||||
chat = chat_map.get(entry["id"])
|
||||
if chat and chat.user_id == user_id:
|
||||
result.append(
|
||||
{
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"summary": chat.summary,
|
||||
"folder": entry["folder"],
|
||||
"meta": chat.meta,
|
||||
"current_message_id": chat.current_message_id,
|
||||
"created_at": chat.created_at,
|
||||
"updated_at": chat.updated_at,
|
||||
"is_active": chat.id in active_ids,
|
||||
}
|
||||
visible_chats = []
|
||||
for chat_file in chat_files:
|
||||
chat = chat_by_id.get(chat_file["chat_id"])
|
||||
if not chat or chat.user_id != user_id:
|
||||
continue
|
||||
|
||||
chat_meta = chat.meta if isinstance(chat.meta, dict) else {}
|
||||
if chat.meta is not None and not isinstance(chat.meta, dict):
|
||||
log.warning(
|
||||
"chat.list.bad_meta workspace=%r chat_id=%s title=%r meta_type=%s",
|
||||
workspace,
|
||||
chat.id,
|
||||
chat.title,
|
||||
type(chat.meta).__name__,
|
||||
)
|
||||
|
||||
chat_file_updated_at = None
|
||||
listing_updated_at = chat.updated_at or chat.created_at or 0
|
||||
if not chat.updated_at:
|
||||
try:
|
||||
chat_file_data = json.loads(chat_file["path"].read_text())
|
||||
chat_file_updated_at = chat_file_data.get("updated_at")
|
||||
if isinstance(chat_file_updated_at, int):
|
||||
listing_updated_at = max(listing_updated_at, chat_file_updated_at)
|
||||
except Exception as exc:
|
||||
log.warning(
|
||||
"chat.list.file_read_error workspace=%r chat_id=%s path=%s error=%s: %s",
|
||||
workspace,
|
||||
chat.id,
|
||||
chat_file["path"],
|
||||
type(exc).__name__,
|
||||
exc,
|
||||
)
|
||||
log.warning(
|
||||
"chat.list.timestamp_anomaly workspace=%r chat_id=%s title=%r db_updated_at=%r chat_file_updated_at=%r created_at=%r listing_updated_at=%r",
|
||||
workspace,
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.updated_at,
|
||||
chat_file_updated_at,
|
||||
chat.created_at,
|
||||
listing_updated_at,
|
||||
)
|
||||
|
||||
stored_tasks = chat_meta.get("tasks")
|
||||
if stored_tasks is not None:
|
||||
malformed_task_count = 0
|
||||
unfinished_task_count = 0
|
||||
task_status_counts: dict[str, int] = {}
|
||||
if isinstance(stored_tasks, list):
|
||||
for task in stored_tasks:
|
||||
if not isinstance(task, dict):
|
||||
malformed_task_count += 1
|
||||
continue
|
||||
status = str(task.get("status", "pending"))
|
||||
task_status_counts[status] = task_status_counts.get(status, 0) + 1
|
||||
if status in {"pending", "in_progress"}:
|
||||
unfinished_task_count += 1
|
||||
if not task.get("id") or not task.get("content"):
|
||||
malformed_task_count += 1
|
||||
else:
|
||||
malformed_task_count += 1
|
||||
if unfinished_task_count or malformed_task_count:
|
||||
log.warning(
|
||||
"chat.list.task_state_anomaly workspace=%r chat_id=%s title=%r db_updated_at=%r chat_file_updated_at=%r current_message_id=%r task_type=%s task_count=%s unfinished=%d malformed=%d statuses=%r",
|
||||
workspace,
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.updated_at,
|
||||
chat_file_updated_at,
|
||||
chat.current_message_id,
|
||||
type(stored_tasks).__name__,
|
||||
len(stored_tasks) if isinstance(stored_tasks, list) else "n/a",
|
||||
unfinished_task_count,
|
||||
malformed_task_count,
|
||||
task_status_counts,
|
||||
)
|
||||
|
||||
chat_list_meta = dict(chat_meta)
|
||||
chat_list_meta.pop("tasks", None)
|
||||
visible_chats.append(
|
||||
{
|
||||
"id": chat.id,
|
||||
"title": chat.title,
|
||||
"summary": chat.summary,
|
||||
"folder": chat_file["folder"],
|
||||
"meta": chat_list_meta,
|
||||
"current_message_id": chat.current_message_id,
|
||||
"created_at": chat.created_at,
|
||||
"updated_at": listing_updated_at,
|
||||
"is_active": chat.id in active_ids,
|
||||
}
|
||||
)
|
||||
|
||||
# Sort by requested field
|
||||
sort_field = sort_by if sort_by in ("title", "updated_at") else "updated_at"
|
||||
reverse = sort_dir != "asc"
|
||||
result.sort(key=lambda c: c[sort_field] or "", reverse=reverse)
|
||||
total = len(result)
|
||||
page = result[offset : offset + limit]
|
||||
return {"chats": page, "total": total, "has_more": offset + limit < total}
|
||||
if sort_field == "updated_at":
|
||||
visible_chats.sort(
|
||||
key=lambda c: c["updated_at"] if isinstance(c["updated_at"], int) else 0,
|
||||
reverse=reverse,
|
||||
)
|
||||
else:
|
||||
visible_chats.sort(key=lambda c: str(c["title"] or ""), reverse=reverse)
|
||||
total_chats = len(visible_chats)
|
||||
chat_page = visible_chats[offset : offset + limit]
|
||||
log.info(
|
||||
"chat.list workspace=%r chat_file_count=%d db_chat_count=%d visible_count=%d limit=%d offset=%d sort=%s/%s page_count=%d has_more=%s",
|
||||
workspace,
|
||||
len(chat_files),
|
||||
len(db_chats),
|
||||
total_chats,
|
||||
limit,
|
||||
offset,
|
||||
sort_field,
|
||||
sort_dir,
|
||||
len(chat_page),
|
||||
offset + limit < total_chats,
|
||||
)
|
||||
return {
|
||||
"chats": chat_page,
|
||||
"total": total_chats,
|
||||
"has_more": offset + limit < total_chats,
|
||||
}
|
||||
|
||||
|
||||
# ── Models aggregation ──────────────────────────────────────
|
||||
@@ -271,6 +375,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 +389,7 @@ async def get_chat(
|
||||
"updated_at": chat.updated_at,
|
||||
},
|
||||
"messages": [_message_dict(m) for m in messages],
|
||||
"tasks": tasks,
|
||||
"context_usage": context_usage,
|
||||
}
|
||||
|
||||
@@ -396,11 +504,11 @@ async def delete_chat(chat_id: str, request: Request):
|
||||
if not chat or chat.user_id != user_id:
|
||||
raise HTTPException(404, "chat not found")
|
||||
|
||||
# Remove .cptr/chats/{id}.json marker
|
||||
# Remove the workspace chat file.
|
||||
workspace = chat.meta.get("workspace", "") if chat.meta else ""
|
||||
if workspace:
|
||||
marker = Path(workspace) / ".cptr" / "chats" / f"{chat_id}.json"
|
||||
await asyncio.to_thread(marker.unlink, True) # missing_ok=True
|
||||
chat_file = Path(workspace) / ".cptr" / "chats" / f"{chat_id}.json"
|
||||
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
|
||||
|
||||
await Chat.delete(chat_id)
|
||||
return {"ok": True}
|
||||
@@ -577,7 +685,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,12 +39,12 @@ 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 = int(max_async or 20)
|
||||
if max_async != -1:
|
||||
max_async = max(1, max_async)
|
||||
async with _lock:
|
||||
running = sum(
|
||||
1 for r in _records.values() if r.get("status") in {"starting", "running"}
|
||||
)
|
||||
if running >= max_async:
|
||||
running = sum(1 for r in _records.values() if r.get("status") in {"starting", "running"})
|
||||
if max_async != -1 and running >= max_async:
|
||||
return {
|
||||
"status": "rejected",
|
||||
"error": (
|
||||
@@ -169,9 +169,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
|
||||
|
||||
+51
-11
@@ -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
|
||||
@@ -52,6 +59,27 @@ PLAN_MODE_PROMPT = (
|
||||
|
||||
SKILLS_CREATE_RE = re.compile(r"^/skills:create(?:\s+(.*))?$", re.IGNORECASE | re.DOTALL)
|
||||
|
||||
|
||||
def resolve_builtin_tools_config(
|
||||
chat_models_config: dict | None, *model_ids: str | None
|
||||
) -> dict | None:
|
||||
"""Merge global/model builtin tool group config. Missing/null means default."""
|
||||
if not isinstance(chat_models_config, dict):
|
||||
return None
|
||||
merged: dict = {}
|
||||
found = False
|
||||
for model_id in ("*", *[m for m in model_ids if m]):
|
||||
model_config = chat_models_config.get(model_id)
|
||||
if not isinstance(model_config, dict):
|
||||
continue
|
||||
params = model_config.get("params", {})
|
||||
value = params.get("builtin_tools") if isinstance(params, dict) else None
|
||||
if isinstance(value, dict):
|
||||
merged.update(value)
|
||||
found = True
|
||||
return merged if found else None
|
||||
|
||||
|
||||
COMPUTER_SKILL_AUTHORING_STANDARDS = """\
|
||||
Follow the Computer skill-authoring standards:
|
||||
|
||||
@@ -1261,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,
|
||||
@@ -1631,6 +1663,11 @@ async def run_chat_task(
|
||||
chat_obj = await Chat.get_by_id(chat_id)
|
||||
chat_params = (chat_obj.meta or {}).get("params", {}) if chat_obj else {}
|
||||
configured_model = (msg.model if msg else None) or model
|
||||
try:
|
||||
chat_models_config = await Config.get("chat.models") or {}
|
||||
except Exception:
|
||||
chat_models_config = {}
|
||||
builtin_tools = resolve_builtin_tools_config(chat_models_config, model, configured_model)
|
||||
messages, loaded_summary = await _load_message_history(chat_id, message_id)
|
||||
_apply_skills_create_prompt(messages)
|
||||
memory_message, memory_files = _memory_recall_inputs(messages, regeneration_prompt)
|
||||
@@ -1646,7 +1683,7 @@ async def run_chat_task(
|
||||
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
|
||||
if regeneration_prompt:
|
||||
messages.append({"role": "user", "content": regeneration_prompt})
|
||||
tools = await get_tool_list()
|
||||
tools = await get_tool_list(builtin_tools=builtin_tools)
|
||||
|
||||
# Remove view_skill tool if no skills are available
|
||||
skills = discover_skills(workspace)
|
||||
@@ -1715,15 +1752,17 @@ async def run_chat_task(
|
||||
global_rp = {}
|
||||
model_rp = {}
|
||||
compact_token_threshold = None
|
||||
try:
|
||||
chat_models_config = await Config.get("chat.models") or {}
|
||||
global_rp = chat_models_config.get("*", {}).get("params", {}).get("request_params", {})
|
||||
model_rp = chat_models_config.get(model, {}).get("params", {}).get("request_params", {})
|
||||
compact_token_threshold = resolve_compact_token_threshold(
|
||||
configured_model, chat_models_config=chat_models_config
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
global_params = chat_models_config.get("*", {}).get("params", {})
|
||||
if not isinstance(global_params, dict):
|
||||
global_params = {}
|
||||
model_params = chat_models_config.get(model, {}).get("params", {})
|
||||
if not isinstance(model_params, dict):
|
||||
model_params = {}
|
||||
global_rp = global_params.get("request_params") or {}
|
||||
model_rp = model_params.get("request_params") or {}
|
||||
compact_token_threshold = resolve_compact_token_threshold(
|
||||
configured_model, chat_models_config=chat_models_config
|
||||
)
|
||||
compact_token_threshold = compact_token_threshold or resolve_compact_token_threshold()
|
||||
request_params = {**global_rp, **model_rp, **chat_request_params} or None
|
||||
|
||||
@@ -1941,6 +1980,7 @@ async def run_chat_task(
|
||||
"chat_id": chat_id,
|
||||
"message_id": message_id,
|
||||
"connection": connection,
|
||||
"builtin_tools": builtin_tools,
|
||||
}
|
||||
|
||||
# Check if any call needs approval
|
||||
|
||||
+205
-4
@@ -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,
|
||||
@@ -2187,8 +2318,20 @@ async def delegate_task(
|
||||
}
|
||||
)
|
||||
|
||||
if config["max_concurrent"] == -1:
|
||||
return await _run_subagent_chat(
|
||||
task=task,
|
||||
context=context,
|
||||
workspace=__context__["workspace"],
|
||||
connection=__context__["connection"],
|
||||
model=__context__["model_id"],
|
||||
user_id=__context__["user_id"],
|
||||
parent_chat_id=__context__["chat_id"],
|
||||
config=config,
|
||||
)
|
||||
|
||||
if _subagent_semaphore is None:
|
||||
_subagent_semaphore = asyncio.Semaphore(config["max_concurrent"])
|
||||
_subagent_semaphore = asyncio.Semaphore(max(1, config["max_concurrent"]))
|
||||
|
||||
async with _subagent_semaphore:
|
||||
return await _run_subagent_chat(
|
||||
@@ -2330,6 +2473,58 @@ SUBAGENT_TOOLS: dict[str, dict] = {
|
||||
# Combined lookup for execution and approval (always available regardless of config)
|
||||
ALL_TOOLS: dict[str, dict] = {**TOOLS, **BROWSER_TOOLS, **SUBAGENT_TOOLS}
|
||||
|
||||
BUILTIN_TOOL_GROUPS: dict[str, tuple[str, ...]] = {
|
||||
"files": (
|
||||
"read_file",
|
||||
"list_directory",
|
||||
"search_files",
|
||||
"create_file",
|
||||
"display_file",
|
||||
"edit_file",
|
||||
"multi_edit_file",
|
||||
"write_file",
|
||||
),
|
||||
"terminal": ("run_command", "send_input", "check_task", "kill_task"),
|
||||
"web": ("web_search", "read_url"),
|
||||
"browser": (
|
||||
"browser_navigate",
|
||||
"browser_snapshot",
|
||||
"browser_click",
|
||||
"browser_type",
|
||||
"browser_screenshot",
|
||||
"browser_evaluate",
|
||||
),
|
||||
"memory": ("update_memory",),
|
||||
"chats": ("search_chats",),
|
||||
"skills": ("view_skill", "manage_skill"),
|
||||
"tasks": ("update_tasks",),
|
||||
"automations": (
|
||||
"list_automations",
|
||||
"create_automation",
|
||||
"update_automation",
|
||||
"toggle_automation",
|
||||
"delete_automation",
|
||||
),
|
||||
"images": ("image_generate",),
|
||||
"subagents": ("delegate_task",),
|
||||
"notifications": ("notify",),
|
||||
}
|
||||
|
||||
|
||||
def disabled_builtin_tool_names(builtin_tools: dict | None) -> set[str]:
|
||||
"""Return builtin tool names disabled by group config."""
|
||||
if not isinstance(builtin_tools, dict):
|
||||
return set()
|
||||
disabled: set[str] = set()
|
||||
for group, enabled in builtin_tools.items():
|
||||
if enabled is False:
|
||||
disabled.update(BUILTIN_TOOL_GROUPS.get(group, ()))
|
||||
return disabled
|
||||
|
||||
|
||||
def is_builtin_tool_enabled(name: str, builtin_tools: dict | None) -> bool:
|
||||
return name not in disabled_builtin_tool_names(builtin_tools)
|
||||
|
||||
|
||||
# ── External tool servers ───────────────────────────────────
|
||||
|
||||
@@ -2633,7 +2828,7 @@ def _without_background_param(schema: dict) -> dict:
|
||||
return schema
|
||||
|
||||
|
||||
async def get_tool_list() -> list[dict]:
|
||||
async def get_tool_list(builtin_tools: dict | None = None) -> list[dict]:
|
||||
"""Return tool schemas for the LLM.
|
||||
|
||||
Automatically includes browser tools when browser.enabled is true,
|
||||
@@ -2668,6 +2863,10 @@ async def get_tool_list() -> list[dict]:
|
||||
tools.pop("image_generate", None)
|
||||
pass
|
||||
|
||||
disabled_tools = disabled_builtin_tool_names(builtin_tools)
|
||||
if disabled_tools:
|
||||
tools = {name: tool for name, tool in tools.items() if name not in disabled_tools}
|
||||
|
||||
schemas = [_fn_to_schema(name, t["fn"]) for name, t in tools.items()]
|
||||
if not background_subagents_enabled:
|
||||
schemas = [_without_background_param(s) for s in schemas]
|
||||
@@ -2687,6 +2886,8 @@ async def execute_tool(name: str, args: dict, __context__: dict) -> str:
|
||||
"""Execute a tool by name, injecting execution context."""
|
||||
info = ALL_TOOLS.get(name)
|
||||
if info:
|
||||
if not is_builtin_tool_enabled(name, __context__.get("builtin_tools")):
|
||||
return f"Error: tool disabled: {name}"
|
||||
fn = info["fn"]
|
||||
try:
|
||||
sig = inspect.signature(fn)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.8.0"
|
||||
version = "0.8.1"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
|
||||
Reference in new issue
Block a user