This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-20 18:06:00 +02:00
1 parent 0fddcba26d
commit 07e7b7623b
13 files changed
+592 -209

No files matched your search

@@ -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"
@@ -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}
+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,