mirror of
https://github.com/open-webui/computer.git
synced 2026-11-28 16:11:44 -05:00
refac
This commit is contained in:
1 parent
10ecaae589
commit
ba32b68412
7 files changed
+201
-40
No files matched your search
@@ -21,7 +21,7 @@
|
||||
type Tab
|
||||
} from '$lib/stores';
|
||||
import { openChatTab } from '$lib/stores';
|
||||
import { chatEnabled, streamingChatTabs } from '$lib/stores/chat';
|
||||
import { chatEnabled, chatStatuses, isChatUnread, streamingChatTabs } from '$lib/stores/chat';
|
||||
import { voiceMemosEnabled, showVoiceMemo } from '$lib/stores/audio';
|
||||
import { keybindings, formatChord } from '$lib/stores/keybindings';
|
||||
import Icon from './Icon.svelte';
|
||||
@@ -407,6 +407,8 @@
|
||||
<div bind:this={tabsEl} class="flex items-center gap-0.5 shrink-0">
|
||||
{#each displayTabs as tab (tab.id)}
|
||||
{@const isActive = tab.id === group.activeTabId}
|
||||
{@const chatStatus =
|
||||
tab.type === 'chat' && tab.path ? $chatStatuses.get(tab.path) : undefined}
|
||||
<button
|
||||
class="flex items-center gap-1.5 px-2.5 h-7 rounded-lg text-xs font-medium whitespace-nowrap shrink-0 transition-all duration-100
|
||||
{isActive
|
||||
@@ -417,7 +419,7 @@
|
||||
onclick={() => handleTabClick(tab)}
|
||||
oncontextmenu={(e) => handleContextMenu(e, tab)}
|
||||
>
|
||||
{#if tab.type === 'chat' && $streamingChatTabs.has(tab.id)}
|
||||
{#if tab.type === 'chat' && (chatStatus?.active || $streamingChatTabs.has(tab.id))}
|
||||
<Spinner size={14} />
|
||||
{:else}
|
||||
<Icon name={tabIconName(tab)} size={14} />
|
||||
@@ -425,6 +427,9 @@
|
||||
<span class="max-w-30 overflow-hidden text-ellipsis">
|
||||
{tab.type === 'files' ? ($activeWorkspace?.name ?? $t('bar.files')) : tab.label}
|
||||
</span>
|
||||
{#if tab.type === 'chat' && isChatUnread(chatStatus)}
|
||||
<span class="size-1.5 shrink-0 rounded-full bg-sky-500" aria-hidden="true"></span>
|
||||
{/if}
|
||||
{#if tab.unsaved}<span class="w-1.5 h-1.5 rounded-full bg-gray-400 shrink-0"></span>{/if}
|
||||
{#if !tab.permanent}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/stores';
|
||||
import { workspaceList, removeWorkspace, reorderWorkspaces, sidebarOpen } from '$lib/stores';
|
||||
import { chatEnabled } from '$lib/stores/chat';
|
||||
import {
|
||||
workspaceList,
|
||||
removeWorkspace,
|
||||
reorderWorkspaces,
|
||||
sidebarOpen,
|
||||
activeTab,
|
||||
currentWorkspace
|
||||
} from '$lib/stores';
|
||||
import { chatEnabled, updateChatStatuses } from '$lib/stores/chat';
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import {
|
||||
deleteChat as apiDeleteChat,
|
||||
@@ -35,8 +41,8 @@
|
||||
let wsChatsCache = $state<Map<string, ChatInfo[]>>(new Map());
|
||||
let wsChatsHasMore = $state<Map<string, boolean>>(new Map());
|
||||
let wsChatsLoading = $state<Set<string>>(new Set());
|
||||
let currentPath = $derived($page.url.searchParams.get('workspace'));
|
||||
let currentChatId = $derived($page.url.searchParams.get('chatId'));
|
||||
let currentPath = $derived($currentWorkspace?.path ?? null);
|
||||
let currentChatId = $derived($activeTab?.type === 'chat' ? $activeTab.path : null);
|
||||
|
||||
function toggleWorkspaceExpand(path: string) {
|
||||
const next = new Set(expandedWorkspaces);
|
||||
@@ -59,6 +65,7 @@
|
||||
...wsChatsCache,
|
||||
[path, append ? [...existing, ...(data.chats || [])] : data.chats || []]
|
||||
]);
|
||||
updateChatStatuses(data.chats || [], path);
|
||||
wsChatsHasMore = new Map([...wsChatsHasMore, [path, data.has_more]]);
|
||||
} catch {
|
||||
wsChatsCache = new Map([...wsChatsCache, [path, []]]);
|
||||
@@ -127,7 +134,7 @@
|
||||
await apiDeleteChat(chatId);
|
||||
const chats = wsChatsCache.get(wsPath) ?? [];
|
||||
wsChatsCache = new Map([...wsChatsCache, [wsPath, chats.filter((chat) => chat.id !== chatId)]]);
|
||||
if (currentPath === wsPath && $page.url.searchParams.get('chatId') === chatId) {
|
||||
if (currentPath === wsPath && currentChatId === chatId) {
|
||||
goto(`/?workspace=${encodeURIComponent(wsPath)}`);
|
||||
}
|
||||
}
|
||||
@@ -156,35 +163,49 @@
|
||||
);
|
||||
}
|
||||
|
||||
const seenChatIds = new Set<string>();
|
||||
|
||||
function handleChatEvent(data: {
|
||||
type?: string;
|
||||
chat_id: string;
|
||||
done?: boolean;
|
||||
title?: string;
|
||||
delta?: string;
|
||||
workspace?: string;
|
||||
active?: boolean;
|
||||
updated_at?: number;
|
||||
last_read_at?: number;
|
||||
}) {
|
||||
if (typeof data.last_read_at === 'number') {
|
||||
wsChatsCache = new Map(
|
||||
[...wsChatsCache].map(([path, chats]) => [
|
||||
path,
|
||||
chats.map((chat) =>
|
||||
chat.id === data.chat_id ? { ...chat, last_read_at: data.last_read_at! } : chat
|
||||
)
|
||||
])
|
||||
);
|
||||
if (
|
||||
!data.title &&
|
||||
typeof data.active !== 'boolean' &&
|
||||
typeof data.updated_at !== 'number' &&
|
||||
typeof data.last_read_at !== 'number'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isNew = !seenChatIds.has(data.chat_id);
|
||||
seenChatIds.add(data.chat_id);
|
||||
if (!data.done && !data.title && !isNew) return;
|
||||
let known = false;
|
||||
wsChatsCache = new Map(
|
||||
[...wsChatsCache].map(([path, chats]) => [
|
||||
path,
|
||||
chats.map((chat) => {
|
||||
if (chat.id !== data.chat_id) return chat;
|
||||
known = true;
|
||||
return {
|
||||
...chat,
|
||||
...(data.title ? { title: data.title } : {}),
|
||||
...(typeof data.updated_at === 'number' ? { updated_at: data.updated_at } : {}),
|
||||
...(typeof data.last_read_at === 'number' ? { last_read_at: data.last_read_at } : {}),
|
||||
...(typeof data.active === 'boolean' ? { is_active: data.active } : {})
|
||||
};
|
||||
})
|
||||
])
|
||||
);
|
||||
|
||||
wsChatsCache = new Map();
|
||||
wsChatsHasMore = new Map();
|
||||
for (const path of expandedWorkspaces) fetchWorkspaceChats(path);
|
||||
// A chat created in another session is not yet in this sidebar's page.
|
||||
// Refresh only that expanded workspace; all known rows update in place.
|
||||
if (!known && data.workspace && expandedWorkspaces.has(data.workspace)) {
|
||||
void fetchWorkspaceChats(data.workspace);
|
||||
}
|
||||
}
|
||||
|
||||
function isTouchDevice(): boolean {
|
||||
|
||||
@@ -26,9 +26,11 @@
|
||||
import {
|
||||
chatModels,
|
||||
defaultModel,
|
||||
setChatReadAt,
|
||||
streamingChatTabs,
|
||||
registerStreamingChat,
|
||||
unregisterStreamingChat
|
||||
unregisterStreamingChat,
|
||||
updateChatStatuses
|
||||
} from '$lib/stores/chat';
|
||||
import { socketStore } from '$lib/stores/socket.svelte';
|
||||
import { onMount, onDestroy, tick } from 'svelte';
|
||||
@@ -386,6 +388,7 @@
|
||||
let loadedChatId = $state<string | null>(null);
|
||||
|
||||
function markChatRead(id: string) {
|
||||
setChatReadAt(id);
|
||||
socketStore.getSocket()?.emit('chat:read', { chat_id: id });
|
||||
}
|
||||
|
||||
@@ -423,6 +426,7 @@
|
||||
updateTab(tabId, id, data.chat.title);
|
||||
}
|
||||
loadedChatId = id;
|
||||
updateChatStatuses([data.chat], workspace);
|
||||
} finally {
|
||||
if (isInitialLoad && gen === loadGeneration) loading = false;
|
||||
}
|
||||
@@ -760,7 +764,7 @@
|
||||
$effect(() => {
|
||||
if (!chatId || !tabId) return;
|
||||
registerStreamingChat(chatId, tabId);
|
||||
return () => unregisterStreamingChat(chatId!);
|
||||
return () => unregisterStreamingChat(chatId!, tabId!);
|
||||
});
|
||||
|
||||
// ── Persist read state separately from visibility tracking ──
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* and an optional context menu button.
|
||||
*/
|
||||
import type { ChatInfo } from '$lib/apis/chat';
|
||||
import { chatStatuses, isChatUnread } from '$lib/stores/chat';
|
||||
import Spinner from './Spinner.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -16,10 +17,13 @@
|
||||
onmenu?: (e: MouseEvent) => void;
|
||||
}
|
||||
let { chat, isSelected = false, onclick, onmenu }: Props = $props();
|
||||
let status = $derived($chatStatuses.get(chat.id));
|
||||
let active = $derived(status?.active ?? chat.is_active ?? false);
|
||||
let unread = $derived(
|
||||
!isSelected &&
|
||||
!chat.is_active &&
|
||||
(chat.last_read_at === null || chat.updated_at > chat.last_read_at)
|
||||
(status
|
||||
? isChatUnread(status)
|
||||
: !active && (chat.last_read_at === null || chat.updated_at > chat.last_read_at))
|
||||
);
|
||||
|
||||
function formatTime(ts: number): string {
|
||||
@@ -50,7 +54,7 @@
|
||||
}}
|
||||
title={chat.title}
|
||||
>
|
||||
{#if chat.is_active}
|
||||
{#if active}
|
||||
<Spinner size={10} borderWidth={1.5} class="opacity-50" />
|
||||
{/if}
|
||||
{#if unread}
|
||||
|
||||
@@ -10,21 +10,99 @@ import { getPathDisplayName, isSupportedWorkspacePath } from '$lib/utils/paths';
|
||||
|
||||
export const chatEnabled = writable<boolean>(false);
|
||||
|
||||
export interface ChatStatus {
|
||||
workspace: string;
|
||||
updatedAt: number | null;
|
||||
lastReadAt: number | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
type ChatStatusSource = {
|
||||
id: string;
|
||||
workspace?: string;
|
||||
updated_at: number;
|
||||
last_read_at: number | null;
|
||||
is_active?: boolean;
|
||||
};
|
||||
|
||||
/** Shared chat state for sidebar rows, workspace summaries, and chat tabs. */
|
||||
export const chatStatuses = writable<Map<string, ChatStatus>>(new Map());
|
||||
|
||||
function statusFrom(
|
||||
source: ChatStatusSource,
|
||||
current?: ChatStatus,
|
||||
workspace?: string
|
||||
): ChatStatus {
|
||||
return {
|
||||
workspace: workspace ?? source.workspace ?? current?.workspace ?? '',
|
||||
updatedAt: source.updated_at,
|
||||
lastReadAt: source.last_read_at,
|
||||
active: source.is_active ?? current?.active ?? false
|
||||
};
|
||||
}
|
||||
|
||||
export function updateChatStatuses(sources: ChatStatusSource[], workspace?: string) {
|
||||
chatStatuses.update((statuses) => {
|
||||
const next = new Map(statuses);
|
||||
for (const source of sources)
|
||||
next.set(source.id, statusFrom(source, next.get(source.id), workspace));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
export function setChatActive(chatId: string, active: boolean, workspace = '') {
|
||||
chatStatuses.update((statuses) => {
|
||||
const current = statuses.get(chatId);
|
||||
const next = new Map(statuses);
|
||||
next.set(chatId, {
|
||||
workspace: workspace || current?.workspace || '',
|
||||
updatedAt: current?.updatedAt ?? null,
|
||||
lastReadAt: current?.lastReadAt ?? null,
|
||||
active
|
||||
});
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
export function setChatReadAt(chatId: string, lastReadAt = Date.now()) {
|
||||
chatStatuses.update((statuses) => {
|
||||
const current = statuses.get(chatId);
|
||||
if (!current) return statuses;
|
||||
const next = new Map(statuses);
|
||||
next.set(chatId, { ...current, lastReadAt });
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
export function isChatUnread(status: ChatStatus | undefined): boolean {
|
||||
return (
|
||||
!!status &&
|
||||
!status.active &&
|
||||
status.updatedAt !== null &&
|
||||
(status.lastReadAt === null || status.updatedAt > status.lastReadAt)
|
||||
);
|
||||
}
|
||||
|
||||
/** Set of tab IDs whose chat is currently streaming (assistant message not done). */
|
||||
export const streamingChatTabs = writable<Set<string>>(new Set());
|
||||
|
||||
/**
|
||||
* Maps chatId -> tabId so we can clear streamingChatTabs from a global
|
||||
* Maps chatId -> tab IDs so we can clear streamingChatTabs from a global
|
||||
* socket listener even when the ChatPanel component is unmounted.
|
||||
*/
|
||||
const chatToTab = new Map<string, string>();
|
||||
const chatToTabs = new Map<string, Set<string>>();
|
||||
|
||||
export function registerStreamingChat(chatId: string, tabId: string) {
|
||||
chatToTab.set(chatId, tabId);
|
||||
const tabIds = chatToTabs.get(chatId) ?? new Set<string>();
|
||||
tabIds.add(tabId);
|
||||
chatToTabs.set(chatId, tabIds);
|
||||
}
|
||||
|
||||
export function unregisterStreamingChat(chatId: string) {
|
||||
chatToTab.delete(chatId);
|
||||
export function unregisterStreamingChat(chatId: string, tabId: string) {
|
||||
const tabIds = chatToTabs.get(chatId);
|
||||
if (!tabIds) return;
|
||||
tabIds.delete(tabId);
|
||||
if (tabIds.size === 0) chatToTabs.delete(chatId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,21 +137,41 @@ export function bindGlobalChatListener() {
|
||||
socketStore.on(
|
||||
'events:chat',
|
||||
(data: {
|
||||
type?: string;
|
||||
chat_id: string;
|
||||
done?: boolean;
|
||||
title?: string;
|
||||
content?: string;
|
||||
workspace?: string;
|
||||
workspace_name?: string;
|
||||
active?: boolean;
|
||||
updated_at?: number;
|
||||
last_read_at?: number;
|
||||
}) => {
|
||||
if (data.type === 'chat:active' && typeof data.active === 'boolean') {
|
||||
setChatActive(data.chat_id, data.active, data.workspace);
|
||||
}
|
||||
if (typeof data.updated_at === 'number') {
|
||||
const updatedAt = data.updated_at;
|
||||
chatStatuses.update((statuses) => {
|
||||
const current = statuses.get(data.chat_id);
|
||||
if (!current) return statuses;
|
||||
const next = new Map(statuses);
|
||||
next.set(data.chat_id, { ...current, updatedAt });
|
||||
return next;
|
||||
});
|
||||
}
|
||||
if (typeof data.last_read_at === 'number') {
|
||||
setChatReadAt(data.chat_id, data.last_read_at);
|
||||
}
|
||||
if (!data.done) return;
|
||||
|
||||
// Clear streaming indicator for the tab
|
||||
const tabId = chatToTab.get(data.chat_id);
|
||||
if (tabId) {
|
||||
const tabIds = chatToTabs.get(data.chat_id);
|
||||
if (tabIds) {
|
||||
streamingChatTabs.update((s) => {
|
||||
const next = new Set(s);
|
||||
next.delete(tabId);
|
||||
for (const tabId of tabIds) next.delete(tabId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -391,6 +391,7 @@ async def get_chat(
|
||||
|
||||
messages = await ChatMessage.get_all_by_chat(chat_id)
|
||||
context_usage = await _get_chat_context_usage(chat, model_id)
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
from cptr.utils.tools import _normalize_tasks
|
||||
|
||||
tasks = _normalize_tasks((chat.meta or {}).get("tasks"))
|
||||
@@ -404,6 +405,7 @@ async def get_chat(
|
||||
"created_at": chat.created_at,
|
||||
"updated_at": chat.updated_at,
|
||||
"last_read_at": chat.last_read_at,
|
||||
"is_active": chat_id in get_active_chat_ids(),
|
||||
},
|
||||
"messages": [_message_dict(m) for m in messages],
|
||||
"tasks": tasks,
|
||||
@@ -534,10 +536,11 @@ async def update_chat(chat_id: str, body: UpdateChatRequest, request: Request):
|
||||
if not title:
|
||||
raise HTTPException(422, "title cannot be empty")
|
||||
|
||||
await Chat.update_title(chat_id, title, now_ms())
|
||||
updated_at = now_ms()
|
||||
await Chat.update_title(chat_id, title, updated_at)
|
||||
from cptr.socket.main import emit_to_user
|
||||
|
||||
await emit_to_user(user_id, {"chat_id": chat_id, "title": title})
|
||||
await emit_to_user(user_id, {"chat_id": chat_id, "title": title, "updated_at": updated_at})
|
||||
return {"ok": True, "title": title}
|
||||
|
||||
|
||||
|
||||
@@ -381,6 +381,17 @@ def start_task(
|
||||
)
|
||||
_tasks[message_id] = task
|
||||
_task_chat[message_id] = chat_id
|
||||
asyncio.create_task(
|
||||
emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:active",
|
||||
"chat_id": chat_id,
|
||||
"workspace": workspace,
|
||||
"active": True,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def cancel_task(message_id: str) -> bool:
|
||||
@@ -2625,6 +2636,21 @@ async def run_chat_task(
|
||||
_tasks.pop(message_id, None)
|
||||
_task_state.pop(message_id, None)
|
||||
_task_chat.pop(message_id, None)
|
||||
if chat_id not in get_active_chat_ids():
|
||||
try:
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:active",
|
||||
"chat_id": chat_id,
|
||||
"workspace": workspace,
|
||||
"active": False,
|
||||
"updated_at": chat.updated_at if chat else None,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("[task %s] active-state emit failed", message_id[:8], exc_info=True)
|
||||
try:
|
||||
await export_chat_to_file(chat_id)
|
||||
except Exception:
|
||||
|
||||
Reference in new issue
Block a user