mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-26 07:11:00 -05:00
refac
This commit is contained in:
1 parent
1fbb42be97
commit
f10d244d05
9 files changed
+275
-3
No files matched your search
@@ -2214,6 +2214,31 @@ class ChatTable:
|
||||
counts[folder_id] = counts.get(folder_id, 0) + 1
|
||||
return counts
|
||||
|
||||
async def get_active_chats(
|
||||
self, user_id: str, folder_ids: list[str], db: AsyncSession | None = None
|
||||
) -> dict[str, tuple[str, bool, int]]:
|
||||
"""Chats with an unfinished reply: their folder, whether it waits for an approval or answer, and when they changed."""
|
||||
if not folder_ids:
|
||||
return {}
|
||||
async with get_async_db_context(db) as session:
|
||||
result = await session.execute(
|
||||
select(Chat.id, Chat.folder_id, Chat.updated_at, ChatMessage.output)
|
||||
.join(ChatMessage, ChatMessage.chat_id == Chat.id)
|
||||
.where(
|
||||
Chat.user_id == user_id,
|
||||
Chat.folder_id.in_(folder_ids),
|
||||
Chat.archived == False,
|
||||
Chat.meta['internal'].as_boolean().is_not(True),
|
||||
ChatMessage.role == 'assistant',
|
||||
ChatMessage.done.is_(False),
|
||||
)
|
||||
)
|
||||
active_chats: dict[str, tuple[str, bool, int]] = {}
|
||||
for chat_id, folder_id, updated_at, output in result.all():
|
||||
waiting = active_chats.get(chat_id, (folder_id, False, 0))[1]
|
||||
active_chats[chat_id] = (folder_id, waiting or has_pending_tool_approval(output), updated_at)
|
||||
return active_chats
|
||||
|
||||
async def get_chats(self, skip: int = 0, limit: int = 50, db: AsyncSession | None = None) -> list[ChatModel]:
|
||||
async with get_async_db_context(db) as session:
|
||||
stmt = select(Chat).where(Chat.meta['internal'].as_boolean().is_not(True))
|
||||
|
||||
@@ -4,7 +4,7 @@ import time
|
||||
|
||||
from open_webui.internal.db import Base
|
||||
from open_webui.models.chat_views import ChatViewData, ViewModel
|
||||
from sqlalchemy import JSON, BigInteger, Column, Text, delete, update
|
||||
from sqlalchemy import JSON, BigInteger, Column, Text, delete, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
|
||||
@@ -27,6 +27,14 @@ class FolderViewStatesTable:
|
||||
row = await db.get(FolderViewState, (user_id, folder_id), populate_existing=True)
|
||||
return {'state': row.state, 'revision': row.revision} if row else {'state': None, 'revision': 0}
|
||||
|
||||
async def get_by_folder_ids(self, user_id, folder_ids, db):
|
||||
result = await db.execute(
|
||||
select(FolderViewState).where(
|
||||
FolderViewState.user_id == user_id, FolderViewState.folder_id.in_(folder_ids)
|
||||
)
|
||||
)
|
||||
return {row.folder_id: row for row in result.scalars().all()}
|
||||
|
||||
async def save(self, user_id, folder_id, state, revision, db):
|
||||
"""Save over the given revision; None when another window saved first."""
|
||||
values = {'state': state, 'revision': revision + 1, 'updated_at': int(time.time())}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -150,6 +151,86 @@ async def get_folders(
|
||||
]
|
||||
|
||||
|
||||
# Folders to continue in: a chat running or waiting, or tabs left open.
|
||||
|
||||
|
||||
class ActiveFolderResponse(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
directory: str | None = None
|
||||
waiting: bool = False
|
||||
running: bool = False
|
||||
terminals: int = 0
|
||||
ports: list[int] = []
|
||||
tabs: list[str] = []
|
||||
updated_at: int = 0
|
||||
|
||||
|
||||
@router.get('/active', response_model=list[ActiveFolderResponse])
|
||||
async def get_active_folders(
|
||||
request: Request,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await check_folders_permission(request, user, db=db)
|
||||
|
||||
folders = await Folders.get_folders_by_user_id(user.id, db=db)
|
||||
folder_ids = [folder.id for folder in folders]
|
||||
active_chats = await Chats.get_active_chats(user.id, folder_ids, db=db)
|
||||
views = await FolderViewStates.get_by_folder_ids(user.id, folder_ids, db)
|
||||
|
||||
active = {
|
||||
folder.id: ActiveFolderResponse(
|
||||
id=folder.id, name=folder.name, directory=(folder.data or {}).get('working_directory')
|
||||
)
|
||||
for folder in folders
|
||||
}
|
||||
for chat_id, (folder_id, waiting, updated_at) in active_chats.items():
|
||||
if waiting:
|
||||
active[folder_id].waiting = True
|
||||
elif await has_active_tasks(request.app.state.redis, chat_id):
|
||||
active[folder_id].running = True
|
||||
else:
|
||||
continue
|
||||
active[folder_id].updated_at = max(active[folder_id].updated_at, updated_at)
|
||||
for folder_id, view in views.items():
|
||||
# These are tabs left open; whether the machine still runs them is not asked.
|
||||
tabs = ((view.state or {}).get('panels') or {}).get('tabs') or []
|
||||
# The main chat tab is the folder page itself.
|
||||
if not any(
|
||||
tab.get('id') != 'main-chat' and tab.get('kind') in ('chat', 'file', 'terminal', 'browser', 'desktop')
|
||||
for tab in tabs
|
||||
):
|
||||
continue
|
||||
active[folder_id].tabs = [
|
||||
tab['label']
|
||||
for tab in tabs
|
||||
if tab.get('id') != 'main-chat' and tab.get('kind') in ('chat', 'file') and tab.get('label')
|
||||
][:2]
|
||||
active[folder_id].terminals = sum(tab.get('kind') == 'terminal' for tab in tabs)
|
||||
active[folder_id].ports = sorted(
|
||||
{
|
||||
int(match[1])
|
||||
for tab in tabs
|
||||
if tab.get('kind') == 'browser'
|
||||
# The label becomes the page's title, so the port is read from the address.
|
||||
and (match := re.match(r'https?://(?:localhost|127\.0\.0\.1):(\d{1,5})(?:[/?#]|$)', tab.get('path') or ''))
|
||||
}
|
||||
)
|
||||
active[folder_id].updated_at = max(active[folder_id].updated_at, view.updated_at)
|
||||
|
||||
results = [folder for folder in active.values() if folder.updated_at]
|
||||
results.sort(
|
||||
key=lambda folder: (
|
||||
folder.waiting,
|
||||
folder.running,
|
||||
folder.updated_at,
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
return results[:3]
|
||||
|
||||
|
||||
# Create Folder
|
||||
|
||||
|
||||
|
||||
@@ -35,6 +35,29 @@ export const createNewFolder = async (token: string, folderForm: FolderForm) =>
|
||||
return res;
|
||||
};
|
||||
|
||||
export type ActiveFolder = {
|
||||
id: string;
|
||||
name: string;
|
||||
directory?: string | null;
|
||||
waiting: boolean;
|
||||
running: boolean;
|
||||
terminals: number;
|
||||
ports: number[];
|
||||
tabs: string[];
|
||||
updated_at: number;
|
||||
};
|
||||
|
||||
export const getActiveFolders = async (token: string = ''): Promise<ActiveFolder[]> => {
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/folders/active`, {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
authorization: `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
};
|
||||
|
||||
export const getFolders = async (token: string = '') => {
|
||||
let error = null;
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onMount } from 'svelte';
|
||||
import { activeFolders, folders, refreshActiveFolders } from '$lib/stores';
|
||||
import { formatDateDetails, formatElapsedShort, formatShortDate } from '$lib/utils';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
|
||||
const i18n: any = getContext('i18n');
|
||||
|
||||
// As in Recent: "45s", "12m", "3h", "5d" for the last week, then a short date.
|
||||
const formatTime = (seconds: number) =>
|
||||
Date.now() / 1000 - seconds < 7 * 86400
|
||||
? formatElapsedShort(seconds)
|
||||
: formatShortDate(seconds, $i18n.language);
|
||||
|
||||
// The machine's own home isn't known here, so shorten the usual ones.
|
||||
const shortenHome = (path: string) =>
|
||||
path.replace(/^(\/(home|Users)\/[^/]+|\/root)(?=\/|$)/, '~');
|
||||
|
||||
onMount(() => {
|
||||
refreshActiveFolders(localStorage.token);
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if $activeFolders.length}
|
||||
<div class="w-full px-1 mb-3 text-left">
|
||||
<h3 id="continue-folders-heading" class="mb-1 -mx-1 text-xs text-base-400 dark:text-base-500">
|
||||
{$i18n.t('Continue')}
|
||||
</h3>
|
||||
|
||||
<ul aria-labelledby="continue-folders-heading">
|
||||
{#each $activeFolders as folder (folder.id)}
|
||||
{@const unread = ($folders as any[]).find(({ id }) => id === folder.id)?.unread_count ?? 0}
|
||||
<li>
|
||||
<a
|
||||
href="/folders/{folder.id}"
|
||||
class="group flex items-center gap-2 h-7 -mx-2 px-2 rounded-lg text-sm transition-colors duration-75 hover:bg-base-50 dark:hover:bg-base-850"
|
||||
title={[
|
||||
folder.name,
|
||||
folder.directory,
|
||||
formatDateDetails(folder.updated_at, $i18n.language)
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n')}
|
||||
>
|
||||
{#if folder.waiting}
|
||||
<span
|
||||
class="size-1.5 shrink-0 rounded-full bg-yellow-500"
|
||||
role="status"
|
||||
aria-label={$i18n.t('Waiting for approval')}
|
||||
></span>
|
||||
{:else if folder.running}
|
||||
<span class="shrink-0"><Spinner className="size-3" /></span>
|
||||
{/if}
|
||||
<span
|
||||
dir="auto"
|
||||
class="min-w-0 truncate text-base-500 dark:text-base-400 transition-colors duration-75 group-hover:text-base-900 dark:group-hover:text-base-100"
|
||||
>
|
||||
{folder.name}
|
||||
</span>
|
||||
{#if unread > 0}
|
||||
<span
|
||||
class="inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-md bg-sky-500/10 px-1 text-[0.625rem] font-semibold leading-4 text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
|
||||
title={$i18n.t('Unread or waiting for approval')}
|
||||
>
|
||||
{unread.toLocaleString($i18n.language)}
|
||||
</span>
|
||||
{/if}
|
||||
<span
|
||||
class="flex-1 min-w-0 truncate font-mono text-[0.6875rem] text-base-400 dark:text-base-600"
|
||||
>
|
||||
{shortenHome(folder.directory ?? '')}
|
||||
</span>
|
||||
{#if folder.terminals}
|
||||
<span
|
||||
class="flex shrink-0 items-center gap-0.5 text-xs tabular-nums text-base-400 dark:text-base-600"
|
||||
role="img"
|
||||
aria-label="{$i18n.t('Terminal')}: {folder.terminals}"
|
||||
>
|
||||
<svg
|
||||
class="size-3"
|
||||
viewBox="0 0 16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.25"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"><path d="m3 4.5 3.5 3.5L3 11.5M8.5 12H13" /></svg
|
||||
>
|
||||
{folder.terminals}
|
||||
</span>
|
||||
{/if}
|
||||
{#if !folder.terminals && !folder.ports.length && folder.tabs.length}
|
||||
<span
|
||||
dir="auto"
|
||||
class="max-w-[40%] shrink-0 truncate text-xs text-base-400 dark:text-base-600"
|
||||
>
|
||||
{folder.tabs.join(' · ')}
|
||||
</span>
|
||||
{/if}
|
||||
{#if folder.ports.length}
|
||||
<span class="shrink-0 text-xs tabular-nums text-base-400 dark:text-base-600">
|
||||
{folder.ports.map((port) => `:${port}`).join(' ')}
|
||||
</span>
|
||||
{/if}
|
||||
<span class="shrink-0 text-xs tabular-nums text-base-400 dark:text-base-600">
|
||||
{formatTime(folder.updated_at)}
|
||||
</span>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -24,6 +24,7 @@
|
||||
import { firstNameOf, getGreeting } from '$lib/utils/greeting';
|
||||
|
||||
import Suggestions from './Suggestions.svelte';
|
||||
import ContinueFolders from './ContinueFolders.svelte';
|
||||
import RecentChats from './RecentChats.svelte';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import EyeSlash from '$lib/components/icons/EyeSlash.svelte';
|
||||
@@ -388,6 +389,9 @@
|
||||
<div class="mx-auto max-w-2xl mt-3" in:fade={{ duration: 200, delay: 200 }}>
|
||||
<!-- Held at the height of either list, so the centred composer doesn't jump when it arrives. -->
|
||||
<div class="mx-5 min-h-[10.5rem]">
|
||||
{#if !$temporary}
|
||||
<ContinueFolders />
|
||||
{/if}
|
||||
{#if showRecentChats}
|
||||
<div in:fade={{ duration: 150 }}>
|
||||
<RecentChats chats={$recentChats} showIdentifier={!selectedSuggestionPrompts?.length} />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { get, readonly, writable } from 'svelte/store';
|
||||
import { getChatList, getPinnedChatList } from '$lib/apis/chats';
|
||||
import { getActiveFolders, type ActiveFolder } from '$lib/apis/folders';
|
||||
import { markFolderChatsDirty, updateFolderChatLists } from './folderStates';
|
||||
import { renameChatTabs } from './chatViewStates';
|
||||
|
||||
@@ -31,6 +32,14 @@ export const refreshRecentChats = async (token: string = '') => {
|
||||
recentChatsStore.set((list ?? []).slice(0, RECENT_CHATS_LIMIT));
|
||||
};
|
||||
|
||||
// Folders with something running, waiting or left open, for the same landing.
|
||||
const activeFoldersStore = writable<ActiveFolder[]>([]);
|
||||
export const activeFolders = readonly(activeFoldersStore);
|
||||
|
||||
export const refreshActiveFolders = async (token: string = '') => {
|
||||
activeFoldersStore.set(await getActiveFolders(token).catch(() => []));
|
||||
};
|
||||
|
||||
// How the sidebar's chat list is filtered and sorted; remembered per browser.
|
||||
export type ChatListView = {
|
||||
status: 'active' | 'archived' | 'all';
|
||||
|
||||
@@ -84,7 +84,14 @@ type ChannelListItem = {
|
||||
export const channels = writable<ChannelListItem[]>([]);
|
||||
export const channelId = writable(null);
|
||||
|
||||
export { chats, pinnedChats, recentChats, refreshRecentChats } from './chatList';
|
||||
export {
|
||||
chats,
|
||||
pinnedChats,
|
||||
recentChats,
|
||||
refreshRecentChats,
|
||||
activeFolders,
|
||||
refreshActiveFolders
|
||||
} from './chatList';
|
||||
export const pinnedNotes = writable([]);
|
||||
export const tags = writable([]);
|
||||
export const folders = writable([]);
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
chatId,
|
||||
chats,
|
||||
folders,
|
||||
refreshRecentChats
|
||||
refreshRecentChats,
|
||||
refreshActiveFolders
|
||||
} from '$lib/stores';
|
||||
|
||||
import Sidebar from '$lib/components/layout/Sidebar.svelte';
|
||||
@@ -261,6 +262,7 @@
|
||||
void setBanners().catch((e) => console.error('Failed to load banners:', e));
|
||||
// The new-chat page lists these under the composer; started now so they're in before it draws.
|
||||
void refreshRecentChats(localStorage.token);
|
||||
void refreshActiveFolders(localStorage.token);
|
||||
const lists = Promise.all([
|
||||
setTools().catch((e) => console.error('Failed to load tools:', e)),
|
||||
refreshMachines().catch((e) => console.error('Failed to load machines:', e)),
|
||||
|
||||
Reference in new issue
Block a user