Merge pull request #75 from open-webui/main

0.6.1
This commit is contained in:
Tim Baek authored and GitHub committed 2026-06-20 18:08:21 +02:00
commit 342eba27b2
19 files changed
+741 -223

No files matched your search

+13
View File
@@ -5,6 +5,19 @@ 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.6.1] - 2026-06-20
### Added
- 🔍 **Firecrawl web search.** Added Firecrawl as a web search provider. Configure your API key from Settings > Web, or set `FIRECRAWL_API_KEY` as an environment variable. Firecrawl slots in between Brave and DuckDuckGo in the automatic provider order, and also works with a custom self-hosted endpoint.
### Changed
- 📂 **Workspace paths are normalized.** Paths like `~/Projects/myapp` and `/Users/you/Projects/myapp` now resolve to the same workspace instead of creating duplicates. Existing duplicates are cleaned up automatically when you open or save a workspace.
- 🔔 **Clicking a browser notification opens the chat.** Desktop notifications for completed tasks now take you straight to the conversation when you click them, instead of just bringing the window to the front.
- 🏷️ **Workspace names display consistently.** Folder names shown in the sidebar, search results, automation list, and notifications now all use the same logic, so you see the same label everywhere.
- 🧹 **Pending messages follow the right branch.** When queued messages or background sub-agent results come in, they now attach to the correct point in the conversation instead of occasionally landing on the wrong branch.
## [0.6.0] - 2026-06-20
### Added
@@ -8,6 +8,7 @@
import DropdownMenu from '../DropdownMenu.svelte';
import ModelSelector from '../common/ModelSelector.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import { createBot, updateBot, verifyBotToken, type BotData, type BotForm } from '$lib/apis/bots';
import { toast } from 'svelte-sonner';
import { t } from '$lib/i18n';
@@ -35,7 +36,7 @@
// Workspace dropdown
let showWsMenu = $state(false);
let wsBtnEl: HTMLButtonElement | undefined = $state();
let workspaceButtonEl: HTMLButtonElement | undefined = $state();
$effect(() => {
if (!workspace && $workspaceList.length > 0) {
@@ -43,18 +44,22 @@
}
});
let wsMenuItems = $derived(
$workspaceList.map((ws) => ({
label: ws.name,
let workspaceMenuItems = $derived(
$workspaceList.map((workspaceOption) => ({
label: workspaceOption.name,
icon: 'folder',
active: ws.path === workspace,
active: workspaceOption.path === workspace,
check: true,
onclick: () => { workspace = ws.path; }
onclick: () => {
workspace = workspaceOption.path;
}
}))
);
let selectedWsName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || $t('automationModal.selectWorkspace')
let selectedWorkspaceName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name ||
getPathDisplayName(workspace) ||
$t('automationModal.selectWorkspace')
);
const platformHints: Record<string, string> = $derived({
@@ -89,7 +94,11 @@
name: name.trim(),
model_id: modelId,
workspace,
allowed_senders: allowedSenders.split(',').map((s) => s.trim()).filter(Boolean) || undefined
allowed_senders:
allowedSenders
.split(',')
.map((s) => s.trim())
.filter(Boolean) || undefined
};
if (token.trim()) update.token = token.trim();
await updateBot(bot.id, update);
@@ -100,7 +109,11 @@
token: token.trim(),
model_id: modelId,
workspace,
allowed_senders: allowedSenders.split(',').map((s) => s.trim()).filter(Boolean) || undefined
allowed_senders:
allowedSenders
.split(',')
.map((s) => s.trim())
.filter(Boolean) || undefined
});
}
onsave();
@@ -141,10 +154,14 @@
/>
</div>
<div class="w-28 shrink-0">
<label class="text-[10px] text-gray-400 dark:text-gray-600">{$t('messaging.platform')}</label>
<label class="text-[10px] text-gray-400 dark:text-gray-600"
>{$t('messaging.platform')}</label
>
<select
bind:value={platform}
onchange={() => { verifyResult = null; }}
onchange={() => {
verifyResult = null;
}}
class="block w-full bg-transparent text-[13px] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
>
<option value="telegram">Telegram</option>
@@ -177,7 +194,9 @@
<input
type="password"
bind:value={token}
placeholder={bot ? $t('messaging.tokenKeep') : platformHints[platform] || $t('messaging.tokenPaste')}
placeholder={bot
? $t('messaging.tokenKeep')
: platformHints[platform] || $t('messaging.tokenPaste')}
autocomplete="new-password"
class="flex-1 bg-transparent text-[13px] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
/>
@@ -200,7 +219,9 @@
{#if verifyResult}
<p class="text-[10px] mb-1 text-gray-500 dark:text-gray-400">
{#if verifyResult.ok}
✓ {verifyResult.info?.username ? `@${verifyResult.info.username}` : `ID: ${verifyResult.info?.id}`}
✓ {verifyResult.info?.username
? `@${verifyResult.info.username}`
: `ID: ${verifyResult.info?.id}`}
{:else}
✗ {verifyResult.error}
{/if}
@@ -208,8 +229,12 @@
{/if}
<!-- Allowed senders -->
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1">{$t('messaging.allowedSenders')}</label>
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">{$t('messaging.allowedSendersHint')}</p>
<label class="text-[10px] text-gray-400 dark:text-gray-600 mt-1"
>{$t('messaging.allowedSenders')}</label
>
<p class="text-[10px] text-gray-300 dark:text-gray-700 mb-0.5">
{$t('messaging.allowedSendersHint')}
</p>
<input
type="text"
bind:value={allowedSenders}
@@ -227,14 +252,22 @@
<!-- Workspace selector -->
<button
bind:this={wsBtnEl}
bind:this={workspaceButtonEl}
type="button"
class="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors duration-100"
onclick={() => (showWsMenu = !showWsMenu)}
>
<Icon name="folder" size={12} />
<span class="truncate max-w-[120px]">{selectedWsName}</span>
<svg class="w-3 h-3 opacity-50" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<span class="truncate max-w-[120px]">{selectedWorkspaceName}</span>
<svg
class="w-3 h-3 opacity-50"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
@@ -256,10 +289,10 @@
</div>
</Modal>
{#if showWsMenu && wsBtnEl}
{#if showWsMenu && workspaceButtonEl}
<DropdownMenu
items={wsMenuItems}
anchor={wsBtnEl}
items={workspaceMenuItems}
anchor={workspaceButtonEl}
onclose={() => (showWsMenu = false)}
preferAbove={true}
maxHeight="15rem"
@@ -19,6 +19,8 @@
let braveKey = $state('');
let perplexityKey = $state('');
let perplexityBaseUrl = $state('');
let firecrawlSearchKey = $state('');
let firecrawlSearchBaseUrl = $state('https://api.firecrawl.dev');
let ccKey = $state('');
let ccBaseUrl = $state('');
let ccModel = $state('');
@@ -46,6 +48,8 @@
braveKey = (config['web.brave_api_key'] as string) || '';
perplexityKey = (config['web.perplexity_api_key'] as string) || '';
perplexityBaseUrl = (config['web.perplexity_base_url'] as string) || '';
firecrawlSearchKey = (config['web.firecrawl_api_key'] as string) || '';
firecrawlSearchBaseUrl = (config['web.firecrawl_base_url'] as string) || 'https://api.firecrawl.dev';
ccKey = (config['web.chat_completions_api_key'] as string) || '';
ccBaseUrl = (config['web.chat_completions_base_url'] as string) || '';
ccModel = (config['web.chat_completions_model'] as string) || '';
@@ -77,6 +81,8 @@
'web.brave_api_key': braveKey,
'web.perplexity_api_key': perplexityKey,
'web.perplexity_base_url': perplexityBaseUrl,
'web.firecrawl_api_key': firecrawlSearchKey,
'web.firecrawl_base_url': firecrawlSearchBaseUrl,
'web.chat_completions_api_key': ccKey,
'web.chat_completions_base_url': ccBaseUrl,
'web.chat_completions_model': ccModel,
@@ -147,6 +153,7 @@
<option value="exa">Exa</option>
<option value="tavily">Tavily</option>
<option value="brave">Brave</option>
<option value="firecrawl">{$t('admin.browserFirecrawl')}</option>
<option value="perplexity">Perplexity</option>
<option value="duckduckgo">DuckDuckGo</option>
<option value="chat_completions">{$t('admin.webChatCompletions')}</option>
@@ -181,6 +188,19 @@
class="w-full mt-1 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" />
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-0.5">{$t('admin.webBraveHint')}</p>
</div>
{:else if searchProvider === 'firecrawl'}
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="web-fc-key">{$t('admin.webFirecrawlKey')}</label>
<input id="web-fc-key" type="password" bind:value={firecrawlSearchKey} placeholder="fc-..."
class="w-full mt-1 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" />
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-0.5">{$t('admin.webFirecrawlHint')}</p>
</div>
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="web-fc-url">{$t('admin.webFirecrawlBaseUrl')}</label>
<input id="web-fc-url" type="text" bind:value={firecrawlSearchBaseUrl} placeholder="https://api.firecrawl.dev"
class="w-full mt-1 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" />
<p class="text-[11px] text-gray-400 dark:text-gray-600 mt-0.5">{$t('admin.browserFirecrawlBaseUrlHint')}</p>
</div>
{:else if searchProvider === 'perplexity'}
<div>
<label class="text-xs text-gray-600 dark:text-gray-400" for="pplx-key">{$t('admin.webPerplexityKey')}</label>
@@ -1,5 +1,6 @@
<script lang="ts">
import { workspaceList, currentWorkspace, showSearch } from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import {
unifiedSearch,
getRecentChats,
@@ -34,9 +35,7 @@
// When on /automations or other non-workspace pages, $currentWorkspace
// retains the last workspace but we should search across all.
const urlWorkspacePath = $derived($page.url.searchParams.get('workspace'));
const effectiveWorkspace = $derived(
urlWorkspacePath ? $currentWorkspace : null
);
const effectiveWorkspace = $derived(urlWorkspacePath ? $currentWorkspace : null);
// Show recents when no query, search results when query exists
const showingRecents = $derived(!query.trim());
@@ -119,11 +118,10 @@
}
}
function workspaceName(wsPath: string): string {
const ws = $workspaceList.find((w) => w.path === wsPath);
if (ws) return ws.name;
const parts = wsPath.split('/');
return parts[parts.length - 1] || wsPath;
function getWorkspaceDisplayName(workspacePath: string): string {
const workspace = $workspaceList.find((item) => item.path === workspacePath);
if (workspace) return workspace.name;
return getPathDisplayName(workspacePath, workspacePath);
}
function selectChat(chat: ChatSearchResult) {
@@ -134,9 +132,13 @@
function selectFile(file: FileSearchResult) {
onclose();
if (file.type === 'file') {
goto(`/?workspace=${encodeURIComponent(file.workspace)}&file=${encodeURIComponent(file.path)}`);
goto(
`/?workspace=${encodeURIComponent(file.workspace)}&file=${encodeURIComponent(file.path)}`
);
} else if (file.type === 'directory') {
goto(`/?workspace=${encodeURIComponent(file.workspace)}&dir=${encodeURIComponent(file.path)}`);
goto(
`/?workspace=${encodeURIComponent(file.workspace)}&dir=${encodeURIComponent(file.path)}`
);
}
}
@@ -224,7 +226,11 @@
<div bind:this={resultsEl} class="overflow-y-auto px-1.5 pb-1.5 flex-1 min-h-0">
{#if showingRecents && filteredRecents.length > 0}
<!-- Recent chats (empty query) -->
<div class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5">{$t('search.recentChats')}</div>
<div
class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5"
>
{$t('search.recentChats')}
</div>
{#each filteredRecents as chat, i (chat.id)}
<button
data-idx={i}
@@ -236,18 +242,29 @@
onmouseenter={() => (selectedIndex = i)}
>
<span class="text-xs font-medium truncate flex-1">{chat.title}</span>
{#if i < 9 && !isWorkspaceScoped}
<KeyPill text={`⌘${i + 1}`} class="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-100" />
{#if i < 9 && !isWorkspaceScoped}
<KeyPill
text={`⌘${i + 1}`}
class="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-100"
/>
{/if}
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">{workspaceName(chat.workspace)}</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0"
>{getWorkspaceDisplayName(chat.workspace)}</span
>
</button>
{/each}
{:else if showingRecents}
<div class="py-6 text-center text-xs text-gray-400 dark:text-gray-600">{$t('search.noRecentChats')}</div>
<div class="py-6 text-center text-xs text-gray-400 dark:text-gray-600">
{$t('search.noRecentChats')}
</div>
{:else if !showingRecents}
{#if displayedChats.length > 0}
<!-- Chat search results -->
<div class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5">{$t('search.chats')}</div>
<div
class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5"
>
{$t('search.chats')}
</div>
{#each displayedChats as chat, i (chat.id)}
{@const idx = i}
<button
@@ -262,20 +279,33 @@
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2">
<span class="text-xs font-medium truncate">{chat.title}</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">{relativeTime(chat.updated_at)}</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0"
>{relativeTime(chat.updated_at)}</span
>
</div>
{#if chat.snippet}
<div class="text-[11px] text-gray-400 dark:text-gray-600 truncate mt-0.5">{chat.snippet}</div>
<div class="text-[11px] text-gray-400 dark:text-gray-600 truncate mt-0.5">
{chat.snippet}
</div>
{/if}
</div>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0">{workspaceName(chat.workspace)}</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0"
>{getWorkspaceDisplayName(chat.workspace)}</span
>
</button>
{/each}
{/if}
{#if fileResults.length > 0}
<!-- File search results -->
<div class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5 {displayedChats.length > 0 ? 'mt-1' : ''}">{$t('search.files')}</div>
<div
class="text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600 px-2 pt-1 pb-0.5 {displayedChats.length >
0
? 'mt-1'
: ''}"
>
{$t('search.files')}
</div>
{#each fileResults as file, i (file.path)}
{@const idx = displayedChats.length + i}
<button
@@ -296,7 +326,9 @@
<span class="text-[11px] text-gray-400 overflow-hidden text-ellipsis whitespace-nowrap"
>{relPath(file.path, file.workspace)}</span
>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0 ml-auto">{workspaceName(file.workspace)}</span>
<span class="text-[10px] text-gray-400 dark:text-gray-600 shrink-0 ml-auto"
>{getWorkspaceDisplayName(file.workspace)}</span
>
</button>
{/each}
{/if}
@@ -9,6 +9,7 @@
import ModelSelector from '../common/ModelSelector.svelte';
import ScheduleDropdown from './ScheduleDropdown.svelte';
import { selectedModelId, workspaceList } from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import type { AutomationData, AutomationForm } from '$lib/apis/automations';
import { createAutomation, updateAutomation } from '$lib/apis/automations';
import { toast } from 'svelte-sonner';
@@ -31,7 +32,7 @@
// Workspaces
let showWsMenu = $state(false);
let wsBtnEl: HTMLButtonElement | undefined = $state();
let workspaceButtonEl: HTMLButtonElement | undefined = $state();
$effect(() => {
if (!workspace && $workspaceList.length > 0) {
@@ -39,18 +40,22 @@
}
});
let wsMenuItems = $derived(
$workspaceList.map((ws) => ({
label: ws.name,
let workspaceMenuItems = $derived(
$workspaceList.map((workspaceOption) => ({
label: workspaceOption.name,
icon: 'folder',
active: ws.path === workspace,
active: workspaceOption.path === workspace,
check: true,
onclick: () => { workspace = ws.path; }
onclick: () => {
workspace = workspaceOption.path;
}
}))
);
let selectedWsName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name || workspace.split('/').pop() || $t('automationModal.selectWorkspace')
let selectedWorkspaceName = $derived(
$workspaceList.find((w) => w.path === workspace)?.name ||
getPathDisplayName(workspace) ||
$t('automationModal.selectWorkspace')
);
async function handleSubmit() {
@@ -103,7 +108,9 @@
<!-- Prompt -->
<div class="px-5 pb-2">
<div class="mb-1 text-[11px] text-gray-400 dark:text-gray-500">{$t('automationModal.instructions')}</div>
<div class="mb-1 text-[11px] text-gray-400 dark:text-gray-500">
{$t('automationModal.instructions')}
</div>
<textarea
class="w-full text-xs bg-transparent outline-none placeholder:text-gray-300 dark:placeholder:text-gray-700 text-gray-700 dark:text-gray-300 resize-none"
bind:value={prompt}
@@ -124,14 +131,22 @@
<!-- Workspace selector -->
<button
bind:this={wsBtnEl}
bind:this={workspaceButtonEl}
type="button"
class="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors duration-100"
onclick={() => (showWsMenu = !showWsMenu)}
>
<Icon name="folder" size={12} />
<span class="truncate max-w-[120px]">{selectedWsName}</span>
<svg class="w-3 h-3 opacity-50" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<span class="truncate max-w-[120px]">{selectedWorkspaceName}</span>
<svg
class="w-3 h-3 opacity-50"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<polyline points="6 9 12 15 18 9" />
</svg>
</button>
@@ -151,17 +166,21 @@
onclick={handleSubmit}
disabled={saving || !name.trim() || !prompt.trim() || !modelId || !workspace}
>
{saving ? $t('automationModal.saving') : automation ? $t('automationModal.save') : $t('automationModal.createBtn')}
{saving
? $t('automationModal.saving')
: automation
? $t('automationModal.save')
: $t('automationModal.createBtn')}
</button>
</div>
</div>
</div>
</Modal>
{#if showWsMenu && wsBtnEl}
{#if showWsMenu && workspaceButtonEl}
<DropdownMenu
items={wsMenuItems}
anchor={wsBtnEl}
items={workspaceMenuItems}
anchor={workspaceButtonEl}
onclose={() => (showWsMenu = false)}
preferAbove={true}
maxHeight="15rem"
@@ -9,6 +9,7 @@
import Spinner from '../common/Spinner.svelte';
import AutomationModal from './AutomationModal.svelte';
import { sidebarOpen } from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import {
getAutomations,
toggleAutomation,
@@ -194,7 +195,11 @@
</div>
{:else if detail}
<!-- Header -->
<div class="flex items-center gap-2 h-9 {$sidebarOpen ? 'px-3' : 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0">
<div
class="flex items-center gap-2 h-9 {$sidebarOpen
? 'px-3'
: 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0"
>
{#if !$sidebarOpen}
<button
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
@@ -225,7 +230,10 @@
</button>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => { editingAutomation = detail; showModal = true; }}
onclick={() => {
editingAutomation = detail;
showModal = true;
}}
title={$t('automationModal.save')}
>
<Icon name="pencil" size={11} />
@@ -245,33 +253,61 @@
<!-- Info rows -->
<div class="border-b border-gray-200 dark:border-white/6">
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.status')}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0"
>{$t('automations.status')}</span
>
<div class="flex items-center gap-1.5">
<span class="w-1.5 h-1.5 rounded-full {detail.is_active ? 'bg-emerald-500' : 'bg-gray-400'}"></span>
<span class="text-xs text-gray-700 dark:text-gray-300">{detail.is_active ? $t('automations.active') : $t('automations.paused')}</span>
<span
class="w-1.5 h-1.5 rounded-full {detail.is_active
? 'bg-emerald-500'
: 'bg-gray-400'}"
></span>
<span class="text-xs text-gray-700 dark:text-gray-300"
>{detail.is_active ? $t('automations.active') : $t('automations.paused')}</span
>
</div>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.schedule')}</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{parseFrequency(detail.rrule)}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0"
>{$t('automations.schedule')}</span
>
<span class="text-xs text-gray-700 dark:text-gray-300"
>{parseFrequency(detail.rrule)}</span
>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.model')}</span>
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono">{detail.model_id}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0"
>{$t('automations.model')}</span
>
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono"
>{detail.model_id}</span
>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.nextRun')}</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{formatTime(detail.next_run_at)}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0"
>{$t('automations.nextRun')}</span
>
<span class="text-xs text-gray-700 dark:text-gray-300"
>{formatTime(detail.next_run_at)}</span
>
</div>
<div class="flex items-center h-7 px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.lastRun')}</span>
<span class="text-xs text-gray-700 dark:text-gray-300">{formatTime(detail.last_run_at)}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0"
>{$t('automations.lastRun')}</span
>
<span class="text-xs text-gray-700 dark:text-gray-300"
>{formatTime(detail.last_run_at)}</span
>
</div>
<div class="flex items-center min-h-[1.75rem] px-3">
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0">{$t('automations.webhook')}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-500 w-20 shrink-0"
>{$t('automations.webhook')}</span
>
{#if detail.webhook_url}
<div class="flex items-center gap-1.5 min-w-0 flex-1">
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono truncate">...?token={detail.webhook_url.split('token=')[1]?.slice(0, 12)}...</span>
<span class="text-[11px] text-gray-500 dark:text-gray-400 font-mono truncate"
>...?token={detail.webhook_url.split('token=')[1]?.slice(0, 12)}...</span
>
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75 shrink-0"
onclick={copyWebhookUrl}
@@ -282,7 +318,9 @@
{:else if detail.has_webhook}
<!-- Webhook enabled, URL not available -->
<div class="flex items-center gap-1.5">
<span class="text-[11px] text-gray-700 dark:text-gray-300">{$t('automations.enabled')}</span>
<span class="text-[11px] text-gray-700 dark:text-gray-300"
>{$t('automations.enabled')}</span
>
<span class="text-gray-300 dark:text-gray-600">·</span>
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
@@ -314,36 +352,52 @@
<!-- Prompt -->
<div class="border-b border-gray-200 dark:border-white/6 px-3 py-2">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">{$t('automations.prompt')}</div>
<div class="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap font-mono leading-relaxed max-h-32 overflow-y-auto">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">
{$t('automations.prompt')}
</div>
<div
class="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap font-mono leading-relaxed max-h-32 overflow-y-auto"
>
{detail.prompt}
</div>
</div>
<!-- Runs -->
<div class="px-3 py-2">
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">{$t('automations.runs')}</div>
<div class="text-[11px] text-gray-400 dark:text-gray-500 mb-1">
{$t('automations.runs')}
</div>
{#if runs.length === 0}
<div class="text-[11px] text-gray-400 dark:text-gray-600 py-2">{$t('automations.noRuns')}</div>
<div class="text-[11px] text-gray-400 dark:text-gray-600 py-2">
{$t('automations.noRuns')}
</div>
{:else}
{#each runs as run}
<div class="flex items-center gap-2 h-7 text-xs">
<span class="w-1.5 h-1.5 rounded-full shrink-0 {run.status === 'success' ? 'bg-emerald-500' : 'bg-red-400'}"></span>
<span
class="w-1.5 h-1.5 rounded-full shrink-0 {run.status === 'success'
? 'bg-emerald-500'
: 'bg-red-400'}"
></span>
<span class="text-gray-500 dark:text-gray-400">{formatTime(run.created_at)}</span>
{#if run.chat_id}
<button
class="text-[11px] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => {
const ws = detail?.workspace;
const wsParam = ws ? `workspace=${encodeURIComponent(ws)}&` : '';
goto(`/?${wsParam}chatId=${encodeURIComponent(run.chat_id!)}`);
const workspacePath = detail?.workspace;
const workspaceQuery = workspacePath
? `workspace=${encodeURIComponent(workspacePath)}&`
: '';
goto(`/?${workspaceQuery}chatId=${encodeURIComponent(run.chat_id!)}`);
}}
>
{$t('automations.viewChat')}
</button>
{/if}
{#if run.error}
<span class="text-[11px] text-red-400 truncate" title={run.error}>{run.error}</span>
<span class="text-[11px] text-red-400 truncate" title={run.error}
>{run.error}</span
>
{/if}
</div>
{/each}
@@ -354,7 +408,11 @@
{:else}
<!-- ── List ── -->
<!-- Header -->
<div class="flex items-center gap-2 h-9 {$sidebarOpen ? 'px-3' : 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0">
<div
class="flex items-center gap-2 h-9 {$sidebarOpen
? 'px-3'
: 'px-1.5'} border-b border-gray-200 dark:border-white/6 shrink-0"
>
{#if !$sidebarOpen}
<button
class="flex items-center justify-center w-7 h-7 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors duration-100"
@@ -381,7 +439,10 @@
</select>
<button
class="flex items-center justify-center w-5 h-5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
onclick={() => { editingAutomation = null; showModal = true; }}
onclick={() => {
editingAutomation = null;
showModal = true;
}}
title={$t('automations.newAutomation')}
>
<Icon name="plus" size={13} />
@@ -390,7 +451,9 @@
</div>
<!-- Search -->
<div class="flex items-center gap-1.5 h-8 px-3 border-b border-gray-200 dark:border-white/6 shrink-0">
<div
class="flex items-center gap-1.5 h-8 px-3 border-b border-gray-200 dark:border-white/6 shrink-0"
>
<Icon name="search" size={13} class="text-gray-400 shrink-0" />
<input
type="text"
@@ -400,7 +463,13 @@
oninput={loadList}
/>
{#if searchQuery}
<button class="text-gray-400 flex items-center" onclick={() => { searchQuery = ''; loadList(); }}>
<button
class="text-gray-400 flex items-center"
onclick={() => {
searchQuery = '';
loadList();
}}
>
<Icon name="xmark" size={11} />
</button>
{/if}
@@ -420,7 +489,10 @@
{#if !searchQuery}
<button
class="text-xs text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 px-3 py-1 rounded-lg bg-gray-100 dark:bg-white/6 transition-colors duration-75"
onclick={() => { editingAutomation = null; showModal = true; }}
onclick={() => {
editingAutomation = null;
showModal = true;
}}
>
{$t('automations.create')}
</button>
@@ -429,19 +501,25 @@
{:else}
{#each items as a (a.id)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="flex items-center gap-2 h-7 px-2 rounded-md"
>
<span class="w-1.5 h-1.5 rounded-full shrink-0 {a.is_active ? 'bg-emerald-500' : 'bg-gray-400'}"></span>
<div class="flex items-center gap-2 h-7 px-2 rounded-md">
<span
class="w-1.5 h-1.5 rounded-full shrink-0 {a.is_active
? 'bg-emerald-500'
: 'bg-gray-400'}"
></span>
<button
class="text-xs text-gray-700 dark:text-gray-300 truncate flex-1 text-left hover:underline cursor-pointer transition-colors duration-75"
onclick={() => goto(`/automations/${a.id}`)}
>
{a.name}
</button>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0">{a.workspace.split('/').pop()}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0"
>{getPathDisplayName(a.workspace, a.workspace)}</span
>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0">·</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0">{parseFrequency(a.rrule)}</span>
<span class="text-[11px] text-gray-400 dark:text-gray-600 shrink-0"
>{parseFrequency(a.rrule)}</span
>
<div class="flex items-center gap-2 shrink-0" onclick={(e) => e.stopPropagation()}>
<button
@@ -465,7 +543,10 @@
{#if showModal}
<AutomationModal
automation={editingAutomation}
onclose={() => { showModal = false; editingAutomation = null; }}
onclose={() => {
showModal = false;
editingAutomation = null;
}}
onsave={handleSave}
/>
{/if}
@@ -35,6 +35,7 @@
selectedModelId,
requestParams
} from '$lib/stores';
import { getPathDisplayName } from '$lib/utils/paths';
import {
ttsEnabled,
ttsConfigured,
@@ -149,6 +150,25 @@
return map;
}
function isPendingHiddenMessage(m: ChatMessageRow): boolean {
return !!(m.meta?.queued || m.meta?.async_subagent_pending);
}
function nearestVisibleAncestorId(
messageId: string | null,
allMsgMap: Map<string, ChatMessageRow>,
visibleMsgMap: Map<string, ChatMessageRow>
): string | null {
let cur = messageId;
const seen = new Set<string>();
while (cur && !seen.has(cur)) {
seen.add(cur);
if (visibleMsgMap.has(cur)) return cur;
cur = allMsgMap.get(cur)?.parent_id ?? null;
}
return null;
}
function findLeaf(messageId: string, childrenMap: Map<string | null, ChatMessageRow[]>): string {
let cur = messageId;
while (true) {
@@ -162,18 +182,20 @@
if (!allMessages.length) return [];
// Exclude pending internal inputs until the parent has processed them.
const displayMessages = allMessages.filter(
(m) => !m.meta?.queued && !m.meta?.async_subagent_pending
);
const displayMessages = allMessages.filter((m) => !isPendingHiddenMessage(m));
if (!displayMessages.length) return [];
const allMsgMap = new Map(allMessages.map((m) => [m.id, m]));
const msgMap = new Map(displayMessages.map((m) => [m.id, m]));
const childrenMap = buildChildrenMap(displayMessages);
// Determine effective currentId: fall back to last message if unset
// Determine effective currentId. If the persisted current leaf points at
// a hidden queued/internal input, anchor the display at its visible parent
// instead of falling onto an unrelated branch.
const visibleCurrentId = nearestVisibleAncestorId(currentMessageId, allMsgMap, msgMap);
const effectiveId =
currentMessageId && msgMap.has(currentMessageId)
? currentMessageId
visibleCurrentId && msgMap.has(visibleCurrentId)
? visibleCurrentId
: displayMessages.length > 0
? displayMessages[displayMessages.length - 1].id
: null;
@@ -259,7 +281,7 @@
const streaming = $derived(allMessages.some((m) => m.role === 'assistant' && !m.done));
const isLanding = $derived(allMessages.length === 0 && !chatId);
const workspaceName = $derived(workspace.split('/').pop() || 'workspace');
const workspaceDisplayName = $derived(getPathDisplayName(workspace, 'workspace'));
// Queued messages: user-authored messages waiting behind an active response.
const queuedMessages = $derived(
@@ -373,7 +395,7 @@
pending_inputs_processed?: boolean;
async_subagent_pending?: boolean;
title?: string;
}) {
}) {
// On the landing page, update the chat list in place from socket events
if (isLanding) {
const knownChat = previousChats.some((c) => c.id === data.chat_id);
@@ -684,7 +706,7 @@
parent_id: parentId,
role: 'user' as const,
content: text,
model: null,
model: selectedModel,
done: true,
output: null,
usage: null,
@@ -1345,7 +1367,7 @@
bind:selectedModel
{sending}
{workspace}
placeholder={$t('chat.placeholder', { name: workspaceName })}
placeholder={$t('chat.placeholder', { name: workspaceDisplayName })}
onsend={send}
{queuedMessages}
onqueuesendnow={handleQueueSendNow}
@@ -1378,9 +1400,9 @@
{#if hasHiddenMessages}
<div bind:this={loadSentinelEl} class="h-1 w-full" aria-hidden="true"></div>
{/if}
{#each visiblePath as { msg, siblingIds, siblingIndex } (msg.id)}
{#if msg.role === 'user'}
<UserMessage
{#each visiblePath as { msg, siblingIds, siblingIndex } (msg.id)}
{#if msg.role === 'user'}
<UserMessage
content={msg.content}
meta={msg.meta}
{siblingIndex}
@@ -304,6 +304,9 @@
"admin.webTavilyHint": "Get your API key at tavily.com",
"admin.webBraveKey": "Brave API Key",
"admin.webBraveHint": "Get your API key at brave.com/search/api",
"admin.webFirecrawlKey": "Firecrawl API Key",
"admin.webFirecrawlBaseUrl": "Firecrawl Base URL",
"admin.webFirecrawlHint": "Uses Firecrawl search. Leave base URL as-is unless you self-host Firecrawl.",
"admin.webDuckDuckGoNote": "DuckDuckGo requires no API key (fallback).",
"admin.webPerplexityKey": "Perplexity API Key",
"admin.webPerplexityHint": "Get your API key at perplexity.ai",
+27 -24
View File
@@ -29,6 +29,7 @@ import { changeLocale, i18next } from '$lib/i18n';
import { streamingChatTabs } from '$lib/stores/chat';
import { keybindings, loadKeybindings } from '$lib/stores/keybindings';
import { defaultPwaPreferences, type PwaPreferences } from '$lib/intents/types';
import { getPathDisplayName, isSupportedWorkspacePath } from '$lib/utils/paths';
// ── Types ───────────────────────────────────────────────────────
@@ -103,7 +104,7 @@ function createDefaultGroup(): EditorGroup {
}
function createDefaultWorkspace(path: string): WorkspaceState {
const name = path.split('/').filter(Boolean).pop() || path;
const name = getPathDisplayName(path);
return {
name,
path,
@@ -144,19 +145,16 @@ export const requestParams = writable<Record<string, unknown>>({});
export const appVersion = writable('');
export const lastSeenVersion = writable('');
export const latestVersion = writable('');
export const updateAvailable = derived(
[appVersion, latestVersion],
([$app, $latest]) => {
if (!$app || !$latest || $app === 'dev' || $app === '0.0.0') return false;
return (
$app.localeCompare($latest, undefined, {
numeric: true,
sensitivity: 'case',
caseFirst: 'upper'
}) < 0
);
}
);
export const updateAvailable = derived([appVersion, latestVersion], ([$app, $latest]) => {
if (!$app || !$latest || $app === 'dev' || $app === '0.0.0') return false;
return (
$app.localeCompare($latest, undefined, {
numeric: true,
sensitivity: 'case',
caseFirst: 'upper'
}) < 0
);
});
export const showChangelog = writable(false);
export const showUpdateToastPref = writable(true);
export const showSearch = writable(false);
@@ -386,7 +384,8 @@ export async function loadPreferences(): Promise<void> {
if (prefs.version) lastSeenVersion.set(prefs.version as string);
if (prefs.selectedModelId) selectedModelId.set(prefs.selectedModelId as string);
if (prefs.requestParams) requestParams.set(prefs.requestParams as Record<string, unknown>);
if (prefs.showUpdateToast !== undefined) showUpdateToastPref.set(prefs.showUpdateToast as boolean);
if (prefs.showUpdateToast !== undefined)
showUpdateToastPref.set(prefs.showUpdateToast as boolean);
const pwaPrefs = prefs.pwa;
if (pwaPrefs)
pwaPreferences.set({
@@ -418,8 +417,13 @@ export async function loadWorkspaceList(): Promise<void> {
// ── Load a specific workspace (called when URL changes) ─────────
export async function loadWorkspace(path: string): Promise<void> {
if (!isSupportedWorkspacePath(path)) {
currentWorkspace.set(null);
return;
}
try {
const wsData = await getWorkspaceState(path);
const canonicalWorkspacePath = typeof wsData.path === 'string' ? wsData.path : path;
if (wsData && wsData.groups && (wsData.groups as EditorGroup[]).length > 0) {
// Validate terminal sessions are still alive
@@ -456,20 +460,19 @@ export async function loadWorkspace(path: string): Promise<void> {
currentWorkspace.set({
...ws,
path,
path: canonicalWorkspacePath,
groups,
activeGroupId,
splitDirection: ws.splitDirection ?? 'horizontal',
splitRatio: ws.splitRatio ?? 0.5,
fileBrowserCwd: ws.fileBrowserCwd ?? path
fileBrowserCwd: ws.fileBrowserCwd ?? canonicalWorkspacePath
});
} else {
// First time opening this workspace, create defaults
currentWorkspace.set(createDefaultWorkspace(path));
currentWorkspace.set(createDefaultWorkspace(canonicalWorkspacePath));
}
} catch {
// Error loading, create fresh workspace
currentWorkspace.set(createDefaultWorkspace(path));
currentWorkspace.set(null);
}
}
@@ -556,7 +559,7 @@ if (typeof BroadcastChannel !== 'undefined') {
* The URL is the single source of truth for which workspace is active.
*/
export function addWorkspace(path: string): void {
const name = path.split('/').filter(Boolean).pop() || path;
const name = getPathDisplayName(path, path);
// Update workspace list for sidebar
workspaceList.update((list) => {
@@ -667,7 +670,7 @@ export function openFileTab(
return;
}
const name = filePath.split('/').pop() || filePath;
const name = getPathDisplayName(filePath, filePath);
const newTab: Tab = {
id: nextId(),
type: 'file',
@@ -914,7 +917,7 @@ export function markTabUnsaved(tabId: string, unsaved: boolean): void {
}
export function updateTabFilePath(tabId: string, newPath: string): void {
const name = newPath.split('/').pop() || newPath;
const name = getPathDisplayName(newPath, newPath);
currentWorkspace.update((ws) => {
if (!ws) return ws;
return {
@@ -966,7 +969,7 @@ export function openInSplit(filePath: string, direction?: SplitDirection): void
}
// Create a new group with this file
const name = filePath.split('/').pop() || filePath;
const name = getPathDisplayName(filePath, filePath);
const newTab: Tab = { id: nextId(), type: 'file', label: name, filePath };
const newGroup: EditorGroup = {
id: nextId(),
+20 -9
View File
@@ -6,6 +6,7 @@ import { toast } from 'svelte-sonner';
import { fetchJSON } from '$lib/apis';
import { socketStore } from '$lib/stores/socket.svelte';
import { activeTab } from '$lib/stores';
import { getPathDisplayName, isSupportedWorkspacePath } from '$lib/utils/paths';
export const chatEnabled = writable<boolean>(false);
@@ -63,6 +64,7 @@ export function bindGlobalChatListener() {
title?: string;
content?: string;
workspace?: string;
workspace_name?: string;
}) => {
if (!data.done) return;
@@ -84,23 +86,27 @@ export function bindGlobalChatListener() {
if (isViewingThisChat) return;
const wsLabel = data.workspace ? `[${data.workspace}] ` : '';
const title = `${wsLabel}${data.title || 'Chat'}`;
const workspacePath = isSupportedWorkspacePath(data.workspace) ? data.workspace : '';
const workspaceDisplayName = data.workspace_name || getPathDisplayName(workspacePath);
const workspaceTitlePrefix = workspaceDisplayName ? `[${workspaceDisplayName}] ` : '';
const title = `${workspaceTitlePrefix}${data.title || 'Chat'}`;
const body = data.content || '';
const openChat = async () => {
const { goto } = await import('$app/navigation');
const workspaceQuery = workspacePath
? `workspace=${encodeURIComponent(workspacePath)}&`
: '';
await goto(`/?${workspaceQuery}chatId=${encodeURIComponent(data.chat_id)}`);
};
// In-app toast
import('$lib/components/NotificationToast.svelte').then((mod) => {
const chatId = data.chat_id;
const toastId = toast.custom(mod.default, {
componentProps: {
title,
content: body,
onClick: async () => {
const { goto } = await import('$app/navigation');
const wsParam = data.workspace
? `workspace=${encodeURIComponent(data.workspace)}&`
: '';
await goto(`/?${wsParam}chatId=${encodeURIComponent(chatId)}`);
await openChat();
toast.dismiss(toastId);
},
onclose: () => {
@@ -115,10 +121,15 @@ export function bindGlobalChatListener() {
// Browser notification (only when tab is hidden)
if (document.hidden && get(notificationsEnabled)) {
try {
new Notification(`${title} • cptr`, {
const notification = new Notification(`${title} • cptr`, {
body: body.slice(0, 200),
icon: '/favicon.png'
});
notification.onclick = () => {
window.focus();
void openChat();
notification.close();
};
} catch {}
}
}
+17
View File
@@ -0,0 +1,17 @@
export function isSupportedWorkspacePath(path: string | null | undefined): path is string {
if (!path) return false;
return (
path.startsWith('/') ||
path.startsWith('~/') ||
path.startsWith('~\\') ||
/^[a-zA-Z]:[\\/]/.test(path) ||
path.startsWith('\\\\')
);
}
export function getPathDisplayName(path: string | null | undefined, fallback = ''): string {
if (!path) return fallback;
const trimmed = path.replace(/[\\/]+$/, '');
const parts = trimmed.split(/[\\/]+/).filter(Boolean);
return parts[parts.length - 1] || trimmed || path || fallback;
}
+28 -13
View File
@@ -40,6 +40,7 @@
import WorkspacePicker from '$lib/components/WorkspacePicker.svelte';
import SystemInfo from '$lib/components/SystemInfo.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import { isSupportedWorkspacePath } from '$lib/utils/paths';
let showPicker = $state(false);
let pendingIntent = $state<LaunchIntent | null>(null);
@@ -67,7 +68,9 @@
type LaunchQueueWindow = Window & {
__cptrLaunchQueueBound?: boolean;
launchQueue?: {
setConsumer: (consumer: (params: { files?: { getFile: () => Promise<File> }[] }) => void) => void;
setConsumer: (
consumer: (params: { files?: { getFile: () => Promise<File> }[] }) => void
) => void;
};
};
@@ -108,7 +111,9 @@
return null;
}
function webCptrIntent(raw: string | null): { intent: string | null; params: URLSearchParams } | null {
function webCptrIntent(
raw: string | null
): { intent: string | null; params: URLSearchParams } | null {
if (!raw) return null;
let decoded = raw;
try {
@@ -314,12 +319,27 @@
}
$effect(() => {
const wsPath = $page.url.searchParams.get('workspace');
if (wsPath && wsPath !== lastLoadedPath) {
const workspacePath = $page.url.searchParams.get('workspace');
if (workspacePath && !isSupportedWorkspacePath(workspacePath)) {
lastLoadedPath = null;
currentWorkspace.set(null);
goto('/', { replaceState: true });
return;
}
if (workspacePath && workspacePath !== lastLoadedPath) {
// New workspace — load then process intents
lastLoadedPath = wsPath;
loadWorkspace(wsPath).then(() => processIntentParams());
} else if (wsPath && wsPath === lastLoadedPath) {
lastLoadedPath = workspacePath;
loadWorkspace(workspacePath).then(async () => {
const canonicalWorkspacePath = get(currentWorkspace)?.path;
if (canonicalWorkspacePath && canonicalWorkspacePath !== workspacePath) {
const params = new URLSearchParams($page.url.searchParams);
params.set('workspace', canonicalWorkspacePath);
lastLoadedPath = canonicalWorkspacePath;
await goto(`/?${params.toString()}`, { replaceState: true });
}
processIntentParams();
});
} else if (workspacePath && workspacePath === lastLoadedPath) {
// Same workspace — process intents immediately
processIntentParams();
} else if (!wsPath) {
@@ -698,11 +718,7 @@
<!-- Persist all tab instances so state survives tab switches (like VS Code) -->
{#each group.tabs.filter((t) => t.type === 'file' && t.filePath) as tab (tab.id)}
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
<FileEditor
filePath={tab.filePath!}
tabId={tab.id}
edit={tab.edit === true}
/>
<FileEditor filePath={tab.filePath!} tabId={tab.id} edit={tab.edit === true} />
</div>
{/each}
@@ -730,7 +746,6 @@
</div>
{/each}
<!-- Fallback content for non-persisted states -->
{#if !groupTab || groupTab.type === 'files'}
<FileBrowser />
+15
View File
@@ -97,6 +97,21 @@ class Workspace(Base):
await db.commit()
return result.rowcount > 0
@staticmethod
async def delete_by_paths(user_id: str, paths: list[str]) -> int:
"""Delete workspaces by path. Returns the number of deleted rows."""
if not paths:
return 0
async with await get_db() as db:
result = await db.execute(
delete(Workspace).where(
Workspace.user_id == user_id,
Workspace.path.in_(paths),
)
)
await db.commit()
return result.rowcount or 0
@staticmethod
async def delete_by_user(user_id: str) -> None:
"""Delete all workspaces for a user."""
+24 -18
View File
@@ -214,7 +214,8 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
else:
log.warning(
"Model auto-discovery failed for %s: HTTP %d",
url, r.status_code,
url,
r.status_code,
)
elif provider == "openai":
@@ -235,7 +236,8 @@ async def _fetch_provider_models(conn: dict) -> list[str]:
else:
log.warning(
"Model auto-discovery failed for %s: HTTP %d",
url, r.status_code,
url,
r.status_code,
)
else:
@@ -428,10 +430,7 @@ async def send_message(body: SendMessageRequest, request: Request):
# Sync params into chat meta
if chat.meta is None:
chat.meta = {}
if (
chat.meta.get("params") != body.params
or chat.meta.get("last_model") != body.model_id
):
if chat.meta.get("params") != body.params or chat.meta.get("last_model") != body.model_id:
chat.meta["params"] = body.params
chat.meta["last_model"] = body.model_id
await Chat.update_meta(chat.id, chat.meta)
@@ -471,12 +470,16 @@ async def send_message(body: SendMessageRequest, request: Request):
assistant_msg = None
async with get_pending_input_lock(chat.id):
if body.chat_id and await _chat_has_active_generation(chat.id):
queued_meta = {"queued": True}
if body.files:
queued_meta["files"] = body.files
queued_msg = await ChatMessage.create(
chat_id=chat.id,
role="user",
content=body.content,
parent_id=body.parent_id,
meta={"queued": True},
model=body.model_id,
meta=queued_meta,
created_at=now_ms(),
)
else:
@@ -647,7 +650,8 @@ async def approve_tool(chat_id: str, message_id: str, body: ApproveRequest, requ
model_id = msg.model or ""
result = await execute_tool(
call["name"], call.get("arguments", {}),
call["name"],
call.get("arguments", {}),
{"workspace": chat.meta.get("workspace", ""), "user_id": user_id, "model_id": model_id},
)
call["status"] = "completed"
@@ -845,7 +849,12 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
if not (msg.meta and msg.meta.get("queued")):
raise HTTPException(400, "message is not queued")
from cptr.utils.chat_task import cancel_task, get_pending_input_lock, start_task
from cptr.utils.chat_task import (
cancel_task,
get_pending_input_lock,
select_pending_input_parent_id,
start_task,
)
async with get_pending_input_lock(chat_id):
# Cancel any active task
@@ -854,21 +863,18 @@ async def queue_send_now(chat_id: str, message_id: str, request: Request):
if m.role == "assistant" and not m.done:
await cancel_task(m.id)
await ChatMessage.update(m.id, done=True)
# Delete all OTHER queued user prompts, keep this one.
for m in all_msgs:
if not (m.role == "user" and m.meta and m.meta.get("queued") and m.id != message_id):
continue
await ChatMessage.delete(m.id)
m.done = True
# Clear queued flag on this message
meta = dict(msg.meta or {})
meta.pop("queued", None)
await ChatMessage.update(message_id, meta=meta or None)
# Find parent: latest done assistant message, or the queued message's parent
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
parent_id = done_assistants[-1].id if done_assistants else msg.parent_id
parent_id = select_pending_input_parent_id(
all_msgs,
chat.current_message_id,
msg.parent_id,
)
# Re-parent the user message to the correct leaf
if msg.parent_id != parent_id:
+110 -19
View File
@@ -9,9 +9,9 @@ Three layers:
from __future__ import annotations
import os
from pathlib import Path
from pathlib import Path, PureWindowsPath
from fastapi import APIRouter, Request, Query
from fastapi import APIRouter, HTTPException, Request, Query
from cptr.env import DATA_DIR
from cptr.models import UserStates, Workspace
from cptr.utils.config import get_or_create_user
@@ -30,6 +30,68 @@ async def _get_user_id(request: Request) -> str | None:
return await get_or_create_user(auth.username)
def _resolve_workspace_path(path: str) -> str:
"""Return the absolute, normalized workspace path."""
raw = (path or "").strip()
if not raw:
raise HTTPException(status_code=400, detail="workspace path is required")
expanded = Path(raw).expanduser()
if not expanded.is_absolute():
raise HTTPException(status_code=400, detail="workspace path must be absolute")
return str(expanded.resolve())
def _try_resolve_workspace_path(path: str) -> str | None:
try:
return _resolve_workspace_path(path)
except HTTPException:
return None
def _workspace_time(workspace: Workspace) -> int:
return workspace.updated_at or workspace.created_at or 0
def _dedupe_workspaces(workspaces: list[Workspace]) -> list[tuple[str, Workspace]]:
by_path: dict[str, Workspace] = {}
for workspace in workspaces:
path = _try_resolve_workspace_path(workspace.path)
if not path:
continue
current = by_path.get(path)
if current is None or _workspace_time(workspace) > _workspace_time(current):
by_path[path] = workspace
return list(by_path.items())
async def _workspaces_at_path(user_id: str, path: str) -> list[Workspace]:
workspaces = await Workspace.get_by_user(user_id)
return [
workspace for workspace in workspaces if _try_resolve_workspace_path(workspace.path) == path
]
def _newest_workspace(workspaces: list[Workspace]) -> Workspace | None:
if not workspaces:
return None
return max(workspaces, key=_workspace_time)
def _workspace_display_name(path: str) -> str:
name = Path(path).name
if name == path and "\\" in path:
name = PureWindowsPath(path).name
return name or path
async def _workspace_summaries(user_id: str) -> list[dict[str, str]]:
workspaces = await Workspace.get_by_user(user_id)
return [
{"path": path, "name": workspace.name or _workspace_display_name(path)}
for path, workspace in _dedupe_workspaces(workspaces)
]
# ── Preferences ──────────────────────────────────────────────────
@@ -62,8 +124,7 @@ async def get_workspace_list(request: Request):
user_id = await _get_user_id(request)
if not user_id:
return []
workspaces = await Workspace.get_by_user(user_id)
return [{"path": ws.path, "name": ws.name} for ws in workspaces]
return await _workspace_summaries(user_id)
# ── Single workspace CRUD ────────────────────────────────────────
@@ -75,13 +136,22 @@ async def get_workspace(request: Request, path: str = Query(...)):
user_id = await _get_user_id(request)
if not user_id:
return {}
ws = await Workspace.get_by_path(user_id, path)
if not ws:
return {}
workspace_path = _resolve_workspace_path(path)
workspace = _newest_workspace(await _workspaces_at_path(user_id, workspace_path))
if not workspace:
return {
"name": _workspace_display_name(workspace_path),
"path": workspace_path,
}
workspace_data = dict(workspace.data or {})
file_browser_cwd = workspace_data.get("fileBrowserCwd")
if isinstance(file_browser_cwd, str):
file_browser_path = _try_resolve_workspace_path(file_browser_cwd)
workspace_data["fileBrowserCwd"] = file_browser_path or workspace_path
return {
"name": ws.name,
"path": ws.path,
**ws.data,
**workspace_data,
"name": workspace.name or _workspace_display_name(workspace_path),
"path": workspace_path,
}
@@ -91,12 +161,21 @@ async def put_workspace(request: Request, path: str = Query(...)):
user_id = await _get_user_id(request)
if not user_id:
return {"status": "skipped"}
body = await request.json()
name = body.pop("name", path.rstrip("/").split("/")[-1] or path)
workspace_path = _resolve_workspace_path(path)
workspace_data = await request.json()
name = workspace_data.pop("name", _workspace_display_name(workspace_path))
workspace_data.pop("path", None)
# Everything else is workspace data (groups, tabs, etc.)
await Workspace.upsert(user_id, path, name, body)
await Workspace.upsert(user_id, workspace_path, name, workspace_data)
return {"status": "saved"}
old_paths = [
workspace.path
for workspace in await _workspaces_at_path(user_id, workspace_path)
if workspace.path != workspace_path
]
await Workspace.delete_by_paths(user_id, old_paths)
return {"status": "saved", "path": workspace_path}
@router.delete("/workspace")
@@ -105,7 +184,11 @@ async def delete_workspace(request: Request, path: str = Query(...)):
user_id = await _get_user_id(request)
if not user_id:
return {"status": "skipped"}
await Workspace.delete_by_path(user_id, path)
workspace_path = _resolve_workspace_path(path)
paths = [workspace.path for workspace in await _workspaces_at_path(user_id, workspace_path)]
if workspace_path not in paths:
paths.append(workspace_path)
await Workspace.delete_by_paths(user_id, paths)
return {"status": "deleted"}
@@ -123,10 +206,18 @@ async def get_welcome(request: Request):
user_id = await _get_user_id(request)
recent: list[dict] = []
if user_id:
workspaces = await Workspace.get_by_user(user_id)
# Sort by updated_at descending (most recent first)
workspaces.sort(key=lambda ws: ws.updated_at or 0, reverse=True)
recent = [{"name": ws.name, "path": ws.path} for ws in workspaces[:10]]
recents = sorted(
_dedupe_workspaces(await Workspace.get_by_user(user_id)),
key=lambda item: _workspace_time(item[1]),
reverse=True,
)
recent = [
{
"name": workspace.name or _workspace_display_name(path),
"path": path,
}
for path, workspace in recents[:10]
]
system_info["recent"] = recent
return system_info
+55 -17
View File
@@ -111,9 +111,7 @@ def _merge_async_subagent_result_meta(messages: list[ChatMessage]) -> dict | Non
if all((m.meta or {}).get("async_subagent_result") for m in messages):
delegation_ids = [
m.meta.get("delegation_id")
for m in messages
if m.meta and m.meta.get("delegation_id")
m.meta.get("delegation_id") for m in messages if m.meta and m.meta.get("delegation_id")
]
subagent_chat_ids = [
m.meta.get("subagent_chat_id")
@@ -156,6 +154,40 @@ def _first_pending_input_batch(messages: list[ChatMessage]) -> list[ChatMessage]
return batch
def _merge_pending_input_meta(messages: list[ChatMessage]) -> dict | None:
async_meta = _merge_async_subagent_result_meta(messages)
if async_meta:
return async_meta
files: list[dict] = []
for message in messages:
meta = message.meta or {}
message_files = meta.get("files")
if isinstance(message_files, list):
files.extend(message_files)
return {"files": files} if files else None
def select_pending_input_parent_id(
messages: list[ChatMessage],
current_message_id: str | None,
fallback_parent_id: str | None = None,
) -> str | None:
"""Choose the visible assistant leaf that pending input should follow."""
msg_map = {m.id: m for m in messages}
cur = msg_map.get(current_message_id) if current_message_id else None
seen: set[str] = set()
while cur and cur.id not in seen:
seen.add(cur.id)
if cur.role == "assistant" and cur.done:
return cur.id
cur = msg_map.get(cur.parent_id) if cur.parent_id else None
done_assistants = [m for m in messages if m.role == "assistant" and m.done]
return done_assistants[-1].id if done_assistants else fallback_parent_id
async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str):
"""Start the next task from user-queued prompts or internal subagent results.
@@ -170,19 +202,23 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
if any(m.role == "assistant" and not m.done for m in all_msgs):
return
pending_inputs = [
m for m in all_msgs if m.role == "user" and _is_pending_chat_input(m)
]
pending_inputs = [m for m in all_msgs if m.role == "user" and _is_pending_chat_input(m)]
if not pending_inputs:
return
input_batch = _first_pending_input_batch(pending_inputs)
combined_content = "\n\n".join(m.content for m in input_batch if m.content)
combined_meta = _merge_async_subagent_result_meta(input_batch)
combined_meta = _merge_pending_input_meta(input_batch)
# Find the current leaf (latest done assistant message)
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
parent_id = done_assistants[-1].id if done_assistants else input_batch[0].parent_id
chat = await Chat.get_by_id(chat_id)
if not chat:
return
parent_id = select_pending_input_parent_id(
all_msgs,
chat.current_message_id,
input_batch[0].parent_id,
)
for m in input_batch:
await ChatMessage.delete(m.id)
@@ -197,12 +233,10 @@ async def process_pending_chat_inputs(chat_id: str, user_id: str, workspace: str
)
# Resolve model from the chat's last used model
chat = await Chat.get_by_id(chat_id)
if not chat:
return
model_id = (chat.meta or {}).get("last_model", "")
if not model_id:
# Fall back to the model from the last assistant message
done_assistants = [m for m in all_msgs if m.role == "assistant" and m.done]
last_asst = done_assistants[-1] if done_assistants else None
model_id = (last_asst.model if last_asst else "") or ""
if not model_id:
@@ -1039,7 +1073,13 @@ async def run_chat_task(
title = "Chat"
preview = content[:300] if content else ""
ws_name = workspace.rstrip("/").rsplit("/", 1)[-1] if workspace else ""
await emit(done=True, title=title, content=preview, workspace=ws_name)
await emit(
done=True,
title=title,
content=preview,
workspace=workspace,
workspace_name=ws_name,
)
# Load existing state so continuations don't overwrite previous output
msg = await ChatMessage.get_by_id(message_id)
@@ -1397,9 +1437,7 @@ async def run_chat_task(
"workspace": workspace,
"user_id": user_id,
"model_id": model,
"full_model_id": (
(chat_obj.meta or {}).get("last_model") if chat_obj else None
)
"full_model_id": ((chat_obj.meta or {}).get("last_model") if chat_obj else None)
or model,
"chat_id": chat_id,
"message_id": message_id,
+67
View File
@@ -0,0 +1,67 @@
"""Firecrawl search provider.
https://docs.firecrawl.dev/api-reference/endpoint/search
Uses the v2 search endpoint and returns web results formatted for LLM context.
"""
from __future__ import annotations
import httpx
DEFAULT_BASE_URL = "https://api.firecrawl.dev"
async def search(
query: str,
api_key: str,
count: int = 5,
base_url: str = DEFAULT_BASE_URL,
) -> str:
"""Search using Firecrawl's search API."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.post(
f"{base_url.rstrip('/')}/v2/search",
json={
"query": query,
"limit": count,
"sources": ["web"],
},
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
)
resp.raise_for_status()
data = resp.json()
if not data.get("success", True):
error = data.get("error", "Unknown error")
return f"Firecrawl error: {error}"
results = []
for item in data.get("data", {}).get("web", [])[:count]:
title = item.get("title", "")
url = item.get("url", "")
description = item.get("description") or item.get("snippet", "")
markdown = item.get("markdown", "")
parts = []
if title:
parts.append(f"**{title}**")
if url:
parts.append(url)
if description:
parts.append(description)
if markdown:
if len(markdown) > 1500:
markdown = markdown[:1500] + "..."
parts.append(markdown)
if parts:
results.append("\n".join(parts))
warning = data.get("warning")
if warning and results:
results.append(f"Warning: {warning}")
return "\n\n".join(results) if results else "No results found."
+45 -13
View File
@@ -5,7 +5,8 @@ Priority in auto mode:
2. Perplexity (PERPLEXITY_API_KEY or web.perplexity_api_key, optional PERPLEXITY_BASE_URL or web.perplexity_base_url)
3. Tavily (TAVILY_API_KEY or web.tavily_api_key)
4. Brave (BRAVE_API_KEY or web.brave_api_key)
5. DuckDuckGo (zero-config fallback)
5. Firecrawl (FIRECRAWL_API_KEY or web.firecrawl_api_key)
6. DuckDuckGo (zero-config fallback)
"""
from __future__ import annotations
@@ -41,7 +42,15 @@ async def _get_config(key: str) -> str:
async def web_search_handler(query: str) -> str:
"""Search the web using the configured or best available provider."""
from cptr.utils.web import exa, perplexity, tavily, brave, duckduckgo, chat_completions
from cptr.utils.web import (
exa,
perplexity,
tavily,
brave,
duckduckgo,
chat_completions,
firecrawl,
)
# Check if web access is disabled by admin
enabled = await _get_config("web.enabled")
@@ -52,18 +61,26 @@ async def web_search_handler(query: str) -> str:
exa_key = await _get_key("EXA_API_KEY", "web.exa_api_key")
perplexity_key = await _get_key("PERPLEXITY_API_KEY", "web.perplexity_api_key")
perplexity_url = (
await _get_config("web.perplexity_base_url")
) or os.environ.get("PERPLEXITY_BASE_URL", "")
perplexity_url = (await _get_config("web.perplexity_base_url")) or os.environ.get(
"PERPLEXITY_BASE_URL", ""
)
tavily_key = await _get_key("TAVILY_API_KEY", "web.tavily_api_key")
brave_key = await _get_key("BRAVE_API_KEY", "web.brave_api_key")
firecrawl_key = await _get_key("FIRECRAWL_API_KEY", "web.firecrawl_api_key")
if not firecrawl_key:
firecrawl_key = await _get_config("browser.firecrawl_api_key")
firecrawl_url = (await _get_config("web.firecrawl_base_url")) or os.environ.get(
"FIRECRAWL_BASE_URL", ""
)
if not firecrawl_url:
firecrawl_url = await _get_config("browser.firecrawl_base_url")
cc_key = await _get_key("CHAT_COMPLETIONS_SEARCH_API_KEY", "web.chat_completions_api_key")
cc_url = (
await _get_config("web.chat_completions_base_url")
) or os.environ.get("CHAT_COMPLETIONS_SEARCH_BASE_URL", "")
cc_model = (
await _get_config("web.chat_completions_model")
) or os.environ.get("CHAT_COMPLETIONS_SEARCH_MODEL", "")
cc_url = (await _get_config("web.chat_completions_base_url")) or os.environ.get(
"CHAT_COMPLETIONS_SEARCH_BASE_URL", ""
)
cc_model = (await _get_config("web.chat_completions_model")) or os.environ.get(
"CHAT_COMPLETIONS_SEARCH_MODEL", ""
)
# Explicit provider mode
if provider != "auto":
@@ -75,7 +92,11 @@ async def web_search_handler(query: str) -> str:
elif provider == "perplexity":
if not perplexity_key:
return "Error: Perplexity API key not configured."
return await perplexity.search(query, perplexity_key, base_url=perplexity_url) if perplexity_url else await perplexity.search(query, perplexity_key)
return (
await perplexity.search(query, perplexity_key, base_url=perplexity_url)
if perplexity_url
else await perplexity.search(query, perplexity_key)
)
elif provider == "tavily":
if not tavily_key:
return "Error: Tavily API key not configured."
@@ -84,6 +105,12 @@ async def web_search_handler(query: str) -> str:
if not brave_key:
return "Error: Brave API key not configured."
return await brave.search(query, brave_key)
elif provider == "firecrawl":
if not firecrawl_key:
return "Error: Firecrawl API key not configured."
if firecrawl_url:
return await firecrawl.search(query, firecrawl_key, base_url=firecrawl_url)
return await firecrawl.search(query, firecrawl_key)
elif provider == "duckduckgo":
return await duckduckgo.search(query)
elif provider == "chat_completions":
@@ -102,11 +129,16 @@ async def web_search_handler(query: str) -> str:
providers.append(("exa", lambda: exa.search(query, exa_key)))
if perplexity_key:
_pplx_kw = {"base_url": perplexity_url} if perplexity_url else {}
providers.append(("perplexity", lambda: perplexity.search(query, perplexity_key, **_pplx_kw)))
providers.append(
("perplexity", lambda: perplexity.search(query, perplexity_key, **_pplx_kw))
)
if tavily_key:
providers.append(("tavily", lambda: tavily.search(query, tavily_key)))
if brave_key:
providers.append(("brave", lambda: brave.search(query, brave_key)))
if firecrawl_key:
_fc_kw = {"base_url": firecrawl_url} if firecrawl_url else {}
providers.append(("firecrawl", lambda: firecrawl.search(query, firecrawl_key, **_fc_kw)))
providers.append(("duckduckgo", lambda: duckduckgo.search(query)))
for name, fn in providers:
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "cptr"
version = "0.6.0"
version = "0.6.1"
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
license = {file = "LICENSE"}
readme = "README.md"