mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
22 files changed
+605
-90
No files matched your search
@@ -47,9 +47,23 @@ jobs:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-latest
|
||||
arch: amd64
|
||||
target: default
|
||||
flavor: default
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
target: default
|
||||
flavor: default
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-latest
|
||||
arch: amd64
|
||||
target: browser
|
||||
flavor: browser
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
target: browser
|
||||
flavor: browser
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -70,10 +84,11 @@ jobs:
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
target: ${{ matrix.target }}
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=gha,scope=dev-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=dev-${{ matrix.arch }}
|
||||
cache-from: type=gha,scope=dev-${{ matrix.flavor }}-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=dev-${{ matrix.flavor }}-${{ matrix.arch }}
|
||||
|
||||
- name: Export digest
|
||||
run: |
|
||||
@@ -84,7 +99,7 @@ jobs:
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-dev-${{ matrix.arch }}
|
||||
name: digests-dev-${{ matrix.flavor }}-${{ matrix.arch }}
|
||||
path: /tmp/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
@@ -92,13 +107,16 @@ jobs:
|
||||
merge-dev:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
needs: build-dev
|
||||
strategy:
|
||||
matrix:
|
||||
flavor: [default, browser]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: /tmp/digests
|
||||
pattern: digests-dev-*
|
||||
pattern: digests-dev-${{ matrix.flavor }}-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
@@ -115,9 +133,12 @@ jobs:
|
||||
working-directory: /tmp/digests
|
||||
run: |
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
docker buildx imagetools create \
|
||||
-t "${{ env.IMAGE }}:dev" \
|
||||
-t "${{ env.IMAGE }}:dev-${SHORT_SHA}" \
|
||||
if [ "${{ matrix.flavor }}" = default ]; then
|
||||
tags=("${{ env.IMAGE }}:dev" "${{ env.IMAGE }}:dev-${SHORT_SHA}")
|
||||
else
|
||||
tags=("${{ env.IMAGE }}:browser-dev" "${{ env.IMAGE }}:browser-dev-${SHORT_SHA}")
|
||||
fi
|
||||
docker buildx imagetools create $(printf -- '-t %s ' "${tags[@]}") \
|
||||
$(printf '${{ env.IMAGE }}@sha256:%s ' *)
|
||||
|
||||
# ── Release builds (release branch) ───────────────────────────────────────
|
||||
@@ -131,9 +152,23 @@ jobs:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-latest
|
||||
arch: amd64
|
||||
target: default
|
||||
flavor: default
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
target: default
|
||||
flavor: default
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-latest
|
||||
arch: amd64
|
||||
target: browser
|
||||
flavor: browser
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
target: browser
|
||||
flavor: browser
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -154,10 +189,11 @@ jobs:
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
target: ${{ matrix.target }}
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,name=${{ env.IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=gha,scope=release-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=release-${{ matrix.arch }}
|
||||
cache-from: type=gha,scope=release-${{ matrix.flavor }}-${{ matrix.arch }}
|
||||
cache-to: type=gha,mode=max,scope=release-${{ matrix.flavor }}-${{ matrix.arch }}
|
||||
|
||||
- name: Export digest
|
||||
run: |
|
||||
@@ -168,7 +204,7 @@ jobs:
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-release-${{ matrix.arch }}
|
||||
name: digests-release-${{ matrix.flavor }}-${{ matrix.arch }}
|
||||
path: /tmp/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
@@ -176,13 +212,16 @@ jobs:
|
||||
merge-release:
|
||||
needs: [read-version, build-release]
|
||||
if: github.ref == 'refs/heads/release'
|
||||
strategy:
|
||||
matrix:
|
||||
flavor: [default, browser]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: /tmp/digests
|
||||
pattern: digests-release-*
|
||||
pattern: digests-release-${{ matrix.flavor }}-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
@@ -200,8 +239,10 @@ jobs:
|
||||
run: |
|
||||
VERSION="${{ needs.read-version.outputs.version }}"
|
||||
MAJOR_MINOR="${VERSION%.*}"
|
||||
docker buildx imagetools create \
|
||||
-t "${{ env.IMAGE }}:latest" \
|
||||
-t "${{ env.IMAGE }}:${VERSION}" \
|
||||
-t "${{ env.IMAGE }}:${MAJOR_MINOR}" \
|
||||
if [ "${{ matrix.flavor }}" = default ]; then
|
||||
tags=("${{ env.IMAGE }}:latest" "${{ env.IMAGE }}:${VERSION}" "${{ env.IMAGE }}:${MAJOR_MINOR}")
|
||||
else
|
||||
tags=("${{ env.IMAGE }}:browser" "${{ env.IMAGE }}:${VERSION}-browser" "${{ env.IMAGE }}:${MAJOR_MINOR}-browser")
|
||||
fi
|
||||
docker buildx imagetools create $(printf -- '-t %s ' "${tags[@]}") \
|
||||
$(printf '${{ env.IMAGE }}@sha256:%s ' *)
|
||||
@@ -5,12 +5,20 @@ 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.9.5] - 2026-07-11
|
||||
|
||||
### Added
|
||||
|
||||
- 👀 **Never lose track of a finished chat.** Unread markers now appear in tabs and chat lists, with a count beside each workspace.
|
||||
- 🌐 **Browser tasks in Docker.** A browser-ready Docker option is now available when your chats need to use the web.
|
||||
|
||||
## [0.9.4] - 2026-07-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- ⚡ **Your model choices are ready sooner.** Computer now gets them ready as it opens and keeps the last working list if a check fails.
|
||||
- 👋 **More dependable restarts.** Computer now finishes its open work more reliably before it closes.
|
||||
|
||||
## [0.9.3] - 2026-07-11
|
||||
|
||||
### Changed
|
||||
|
||||
+18
-4
@@ -22,15 +22,15 @@ COPY --from=frontend-builder /build/frontend/build cptr/frontend/build
|
||||
RUN uv build --wheel --out-dir /dist
|
||||
|
||||
|
||||
# ── Stage 3: Minimal runtime image ─────────────────────────
|
||||
# ── Stage 3: Shared runtime ────────────────────────────────
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS runtime
|
||||
|
||||
LABEL org.opencontainers.image.source="https://github.com/open-webui/computer"
|
||||
LABEL org.opencontainers.image.description="cptr: your computer, from anywhere"
|
||||
LABEL org.opencontainers.image.description="Open WebUI Computer"
|
||||
|
||||
# Runtime deps: git for git operations, tini for PID 1
|
||||
# Runtime deps shared by default and browser images.
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends git tini && \
|
||||
apt-get install -y --no-install-recommends gh git tini && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Create non-root user and writable data directory
|
||||
@@ -55,3 +55,17 @@ VOLUME ["/data"]
|
||||
|
||||
ENTRYPOINT ["tini", "--"]
|
||||
CMD ["cptr", "run", "--host", "0.0.0.0", "--port", "8000", "--headless"]
|
||||
|
||||
|
||||
# ── Browser image: Chromium for agent browser automation ───
|
||||
FROM runtime AS browser
|
||||
|
||||
USER root
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends chromium && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
USER cptr
|
||||
|
||||
|
||||
# ── Default image ──────────────────────────────────────────
|
||||
FROM runtime AS default
|
||||
@@ -170,6 +170,7 @@ docker run --rm -it \
|
||||
Then open the URL printed in the logs, usually `http://localhost:8000/?token=...`.
|
||||
|
||||
Open WebUI Computer stores its state in `/data`. Mount your project into the container, like `-v "$PWD:/workspace"`, so Open WebUI Computer can access it.
|
||||
The default image includes Git and GitHub CLI (`gh`). Use `ghcr.io/open-webui/computer:browser` when agent browser automation needs Chromium.
|
||||
|
||||
If you bind-mount a host directory to `/data`, make sure that directory is writable by the container user. SQLite needs to create and update `/data/app.db`, and host directory permissions take precedence over the image's built-in `/data` ownership.
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface ChatInfo {
|
||||
current_message_id: string | null;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
last_read_at: number | null;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,8 +17,13 @@ export const savePreferences = (data: Record<string, unknown>) =>
|
||||
|
||||
// ── Workspace list (sidebar) ────────────────────────────────────
|
||||
|
||||
export const getWorkspaceList = () =>
|
||||
fetchJSON<{ path: string; name: string }[]>('/api/state/workspaces');
|
||||
export interface WorkspaceListItem {
|
||||
path: string;
|
||||
name: string;
|
||||
unread_count: number;
|
||||
}
|
||||
|
||||
export const getWorkspaceList = () => fetchJSON<WorkspaceListItem[]>('/api/state/workspaces');
|
||||
|
||||
// ── Single workspace CRUD ───────────────────────────────────────
|
||||
|
||||
|
||||
@@ -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' && !isActive && 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,7 +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 currentPath = $derived($currentWorkspace?.path ?? null);
|
||||
let currentChatId = $derived($activeTab?.type === 'chat' ? $activeTab.path : null);
|
||||
|
||||
function toggleWorkspaceExpand(path: string) {
|
||||
const next = new Set(expandedWorkspaces);
|
||||
@@ -58,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, []]]);
|
||||
@@ -126,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)}`);
|
||||
}
|
||||
}
|
||||
@@ -155,22 +163,61 @@
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
workspace_unread_count?: number;
|
||||
}) {
|
||||
const isNew = !seenChatIds.has(data.chat_id);
|
||||
seenChatIds.add(data.chat_id);
|
||||
if (!data.done && !data.title && !isNew) return;
|
||||
if (
|
||||
!data.title &&
|
||||
typeof data.active !== 'boolean' &&
|
||||
typeof data.updated_at !== 'number' &&
|
||||
typeof data.last_read_at !== 'number' &&
|
||||
typeof data.workspace_unread_count !== 'number'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const unreadCount = data.workspace_unread_count;
|
||||
if (data.workspace && typeof unreadCount === 'number') {
|
||||
workspaceList.update((workspaces) =>
|
||||
workspaces.map((workspace) =>
|
||||
workspace.path === data.workspace
|
||||
? { ...workspace, unread_count: unreadCount }
|
||||
: workspace
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
wsChatsCache = new Map();
|
||||
wsChatsHasMore = new Map();
|
||||
for (const path of expandedWorkspaces) fetchWorkspaceChats(path);
|
||||
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 } : {})
|
||||
};
|
||||
})
|
||||
])
|
||||
);
|
||||
|
||||
// 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 {
|
||||
@@ -275,9 +322,17 @@
|
||||
{:else}
|
||||
<Icon name="folder" size={14} />
|
||||
{/if}
|
||||
<span class="flex-1 text-left overflow-hidden text-ellipsis whitespace-nowrap"
|
||||
>{ws.name}</span
|
||||
>
|
||||
<span class="min-w-0 truncate text-left">{ws.name}</span>
|
||||
{#if ws.unread_count > 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 text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
|
||||
>
|
||||
{new Intl.NumberFormat(undefined, {
|
||||
notation: 'compact',
|
||||
compactDisplay: 'short'
|
||||
}).format(ws.unread_count)}
|
||||
</span>
|
||||
{/if}
|
||||
</a>
|
||||
<span
|
||||
class="flex items-center justify-center w-4 h-4 shrink-0 text-gray-400 opacity-0 group-hover:opacity-100 hover:text-gray-600 dark:hover:text-gray-300 transition-all duration-75"
|
||||
@@ -314,6 +369,7 @@
|
||||
{#each chats as chat (chat.id)}
|
||||
<ChatItem
|
||||
{chat}
|
||||
isSelected={chat.id === currentChatId}
|
||||
onclick={() => openChat(chat.id, ws.path)}
|
||||
onmenu={(e) => openChatMenu(e, chat.id, ws.path)}
|
||||
/>
|
||||
|
||||
@@ -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';
|
||||
@@ -383,10 +385,17 @@
|
||||
// ── Load chat from DB ───────────────────────────────────────
|
||||
|
||||
let loadGeneration = 0;
|
||||
let loadedChatId = $state<string | null>(null);
|
||||
|
||||
function markChatRead(id: string) {
|
||||
setChatReadAt(id);
|
||||
socketStore.getSocket()?.emit('chat:read', { chat_id: id });
|
||||
}
|
||||
|
||||
async function loadChat(id: string) {
|
||||
if (chatId && chatId !== id) stopTtsPlayback();
|
||||
chatId = id;
|
||||
loadedChatId = null;
|
||||
const gen = ++loadGeneration;
|
||||
// Only show loading spinner on initial load (no messages yet).
|
||||
// On reloads (e.g. after cancel/done), keep the DOM intact to preserve scroll position.
|
||||
@@ -416,6 +425,8 @@
|
||||
chatTitle = data.chat.title;
|
||||
updateTab(tabId, id, data.chat.title);
|
||||
}
|
||||
loadedChatId = id;
|
||||
updateChatStatuses([data.chat], workspace);
|
||||
} finally {
|
||||
if (isInitialLoad && gen === loadGeneration) loading = false;
|
||||
}
|
||||
@@ -753,7 +764,23 @@
|
||||
$effect(() => {
|
||||
if (!chatId || !tabId) return;
|
||||
registerStreamingChat(chatId, tabId);
|
||||
return () => unregisterStreamingChat(chatId!);
|
||||
return () => unregisterStreamingChat(chatId!, tabId!);
|
||||
});
|
||||
|
||||
// ── Persist read state separately from visibility tracking ──
|
||||
|
||||
$effect(() => {
|
||||
if (!chatId || loadedChatId !== chatId || !active) return;
|
||||
const id = chatId;
|
||||
const send = () => markChatRead(id);
|
||||
send();
|
||||
return socketStore.on('connect', send);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!chatId || !active) return;
|
||||
const id = chatId;
|
||||
return () => markChatRead(id);
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
|
||||
@@ -5,16 +5,26 @@
|
||||
* 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';
|
||||
|
||||
interface Props {
|
||||
chat: ChatInfo;
|
||||
isSelected?: boolean;
|
||||
onclick: () => void;
|
||||
/** Optional menu button click handler */
|
||||
onmenu?: (e: MouseEvent) => void;
|
||||
}
|
||||
let { chat, onclick, onmenu }: Props = $props();
|
||||
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 &&
|
||||
(status
|
||||
? isChatUnread(status)
|
||||
: !active && (chat.last_read_at === null || chat.updated_at > chat.last_read_at))
|
||||
);
|
||||
|
||||
function formatTime(ts: number): string {
|
||||
const now = Date.now();
|
||||
@@ -44,10 +54,17 @@
|
||||
}}
|
||||
title={chat.title}
|
||||
>
|
||||
{#if chat.is_active}
|
||||
{#if active}
|
||||
<Spinner size={10} borderWidth={1.5} class="opacity-50" />
|
||||
{/if}
|
||||
<span class="flex-1 text-xs text-gray-500 dark:text-gray-500 truncate min-w-0">{chat.title}</span>
|
||||
{#if unread}
|
||||
<span class="size-1.5 shrink-0 rounded-full bg-sky-500" aria-hidden="true"></span>
|
||||
{/if}
|
||||
<span
|
||||
class="flex-1 text-xs truncate min-w-0 {unread
|
||||
? 'font-medium text-gray-900 dark:text-gray-100'
|
||||
: 'text-gray-500 dark:text-gray-500'}">{chat.title}</span
|
||||
>
|
||||
<span class="text-[0.625rem] text-gray-300 dark:text-gray-700 shrink-0 tabular-nums"
|
||||
>{formatTime(chat.updated_at)}</span
|
||||
>
|
||||
|
||||
@@ -281,7 +281,7 @@ export const homeState = writable<HomeState>({
|
||||
});
|
||||
|
||||
/** List of all workspace summaries for the sidebar. */
|
||||
export const workspaceList = writable<{ path: string; name: string }[]>([]);
|
||||
export const workspaceList = writable<{ path: string; name: string; unread_count: number }[]>([]);
|
||||
|
||||
/** Global user preferences. */
|
||||
export const sidebarOpen = writable(
|
||||
@@ -825,7 +825,7 @@ export function addWorkspace(path: string): void {
|
||||
// Update workspace list for sidebar
|
||||
workspaceList.update((list) => {
|
||||
if (list.some((w) => w.path === path)) return list;
|
||||
return [...list, { path, name }];
|
||||
return [...list, { path, name, unread_count: 0 }];
|
||||
});
|
||||
|
||||
// Append to order
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1079,8 +1079,8 @@
|
||||
{/each}
|
||||
{#if homeTab?.type === 'home'}
|
||||
<div class="h-full overflow-y-auto px-6">
|
||||
<div class="mx-auto flex min-h-full w-full max-w-md flex-col justify-center py-6">
|
||||
<div class="mb-5">
|
||||
<div class="mx-auto flex min-h-full w-full max-w-md flex-col justify-center py-5">
|
||||
<div class="mb-4">
|
||||
<div class="flex items-baseline gap-2">
|
||||
<h1 class="text-lg font-medium tracking-tight text-gray-900 dark:text-white">
|
||||
{#if welcomeName}
|
||||
@@ -1112,18 +1112,18 @@
|
||||
</div>
|
||||
|
||||
<div class="mb-5">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
|
||||
<h2 class="mb-1.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('home.start')}
|
||||
</h2>
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
class="text-xs text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
onclick={() => (showPicker = true)}
|
||||
>
|
||||
{$t('home.openWorkspace')}
|
||||
</button>
|
||||
{#if $chatEnabled}
|
||||
<button
|
||||
class="mt-1.5 block text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
class="mt-1 block text-xs text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
onclick={() => openHomeChat(undefined, homePane.id)}
|
||||
>
|
||||
{$t('bar.newChat')}
|
||||
@@ -1132,19 +1132,34 @@
|
||||
</div>
|
||||
|
||||
{#if continuation}
|
||||
<div class="mb-5">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
|
||||
{@const unreadCount =
|
||||
$workspaceList.find((workspace) => workspace.path === continuation.path)
|
||||
?.unread_count ?? 0}
|
||||
<div class="mb-4">
|
||||
<h2 class="mb-1.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('home.continue')}
|
||||
</h2>
|
||||
<button
|
||||
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
|
||||
class="group w-full min-w-0 py-1 text-left transition-colors duration-100"
|
||||
onclick={() => quickOpen(continuation.path)}
|
||||
>
|
||||
<span class="flex min-w-0 items-baseline gap-2">
|
||||
<span
|
||||
class="truncate text-[0.8125rem] text-gray-800 group-hover:text-gray-950 dark:text-gray-200 dark:group-hover:text-white"
|
||||
>
|
||||
{continuation.name}
|
||||
<span class="flex min-w-0 items-center gap-1.5">
|
||||
<span
|
||||
class="truncate text-xs text-gray-800 group-hover:text-gray-950 dark:text-gray-200 dark:group-hover:text-white"
|
||||
>
|
||||
{continuation.name}
|
||||
</span>
|
||||
{#if unreadCount > 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 text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
|
||||
>
|
||||
{new Intl.NumberFormat(undefined, {
|
||||
notation: 'compact',
|
||||
compactDisplay: 'short'
|
||||
}).format(unreadCount)}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
<span
|
||||
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
@@ -1170,23 +1185,38 @@
|
||||
{/if}
|
||||
|
||||
{#if recent.length}
|
||||
<div class="mb-5">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
|
||||
<div class="mb-4">
|
||||
<h2 class="mb-1.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('home.recent')}
|
||||
</h2>
|
||||
<div class="flex flex-col">
|
||||
{#each recent as item}
|
||||
{@const resume = workspaceResumes.get(item.path)}
|
||||
{@const signals = resumeSignals(resume)}
|
||||
{@const unreadCount =
|
||||
$workspaceList.find((workspace) => workspace.path === item.path)
|
||||
?.unread_count ?? 0}
|
||||
<button
|
||||
class="group w-full min-w-0 py-1.5 text-left transition-colors duration-100"
|
||||
class="group w-full min-w-0 py-1 text-left transition-colors duration-100"
|
||||
onclick={() => quickOpen(item.path)}
|
||||
>
|
||||
<span class="flex min-w-0 items-baseline gap-2">
|
||||
<span
|
||||
class="truncate text-[0.8125rem] text-gray-700 group-hover:text-gray-900 dark:text-gray-300 dark:group-hover:text-white"
|
||||
>
|
||||
{item.name}
|
||||
<span class="flex min-w-0 items-center gap-1.5">
|
||||
<span
|
||||
class="truncate text-xs text-gray-700 group-hover:text-gray-900 dark:text-gray-300 dark:group-hover:text-white"
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
{#if unreadCount > 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 text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
|
||||
>
|
||||
{new Intl.NumberFormat(undefined, {
|
||||
notation: 'compact',
|
||||
compactDisplay: 'short'
|
||||
}).format(unreadCount)}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
<span
|
||||
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
@@ -1212,12 +1242,12 @@
|
||||
</div>
|
||||
</div>
|
||||
{:else if !continuation}
|
||||
<div class="mb-5">
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
|
||||
<div class="mb-4">
|
||||
<h2 class="mb-1.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('home.recent')}
|
||||
</h2>
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-500 transition-colors duration-100 hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
|
||||
class="text-xs text-gray-500 transition-colors duration-100 hover:text-gray-900 dark:text-gray-500 dark:hover:text-white"
|
||||
onclick={() => (showPicker = true)}
|
||||
>
|
||||
{$t('home.noWorkspaces')}
|
||||
@@ -1227,13 +1257,16 @@
|
||||
|
||||
{#if nearby.length && !welcomeData?.recent?.length}
|
||||
<div>
|
||||
<h2 class="mb-2 text-xs text-gray-400 dark:text-gray-600">
|
||||
<h2 class="mb-1.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('home.folders')}
|
||||
</h2>
|
||||
<div class="flex flex-col">
|
||||
{#each nearby as item}
|
||||
{@const unreadCount =
|
||||
$workspaceList.find((workspace) => workspace.path === item.path)
|
||||
?.unread_count ?? 0}
|
||||
<button
|
||||
class="flex min-w-0 items-center gap-2 py-1.5 text-left text-[0.8125rem] text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
class="flex min-w-0 items-center gap-2 py-1 text-left text-xs text-gray-600 transition-colors duration-100 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
|
||||
onclick={() => quickOpen(item.path)}
|
||||
>
|
||||
<Icon
|
||||
@@ -1242,7 +1275,19 @@
|
||||
strokeWidth={1.3}
|
||||
class="shrink-0 text-gray-400 dark:text-gray-600"
|
||||
/>
|
||||
<span class="truncate">{item.name}</span>
|
||||
<span class="flex min-w-0 items-center gap-1.5">
|
||||
<span class="truncate">{item.name}</span>
|
||||
{#if unreadCount > 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 text-sky-600 dark:bg-sky-400/10 dark:text-sky-300"
|
||||
>
|
||||
{new Intl.NumberFormat(undefined, {
|
||||
notation: 'compact',
|
||||
compactDisplay: 'short'
|
||||
}).format(unreadCount)}
|
||||
</span>
|
||||
{/if}
|
||||
</span>
|
||||
<span
|
||||
class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""add chat last read at
|
||||
|
||||
Revision ID: 0004
|
||||
Revises: 0003
|
||||
Create Date: 2026-07-11
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "0004"
|
||||
down_revision = "0003"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("chats", sa.Column("last_read_at", sa.BigInteger(), nullable=True))
|
||||
op.execute("UPDATE chats SET last_read_at = updated_at")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("chats", "last_read_at")
|
||||
+62
-1
@@ -5,7 +5,18 @@ from __future__ import annotations
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Column, ForeignKey, Text, delete, or_, select, update
|
||||
from sqlalchemy import (
|
||||
BigInteger,
|
||||
Boolean,
|
||||
Column,
|
||||
ForeignKey,
|
||||
Text,
|
||||
delete,
|
||||
func,
|
||||
or_,
|
||||
select,
|
||||
update,
|
||||
)
|
||||
from sqlalchemy.dialects.sqlite import JSON
|
||||
|
||||
from cptr.models.base import Base
|
||||
@@ -29,6 +40,7 @@ class Chat(Base):
|
||||
meta = Column(JSON, nullable=True) # {model_id, connection_id, pinned, archived, ...}
|
||||
created_at = Column(BigInteger, nullable=False)
|
||||
updated_at = Column(BigInteger, nullable=False)
|
||||
last_read_at = Column(BigInteger, nullable=True)
|
||||
|
||||
# ── Class methods ────────────────────────────────────────
|
||||
|
||||
@@ -61,6 +73,7 @@ class Chat(Base):
|
||||
meta=meta,
|
||||
created_at=created_at,
|
||||
updated_at=created_at,
|
||||
last_read_at=created_at,
|
||||
)
|
||||
db.add(chat)
|
||||
await db.commit()
|
||||
@@ -109,6 +122,54 @@ class Chat(Base):
|
||||
await db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
@staticmethod
|
||||
async def touch(chat_id: str, updated_at: int) -> bool:
|
||||
"""Record a completed background update without changing chat content."""
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(
|
||||
update(Chat).where(Chat.id == chat_id).values(updated_at=updated_at)
|
||||
)
|
||||
await db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
@staticmethod
|
||||
async def unread_counts_by_workspace(
|
||||
user_id: str, workspace_paths: list[str], active_chat_ids: set[str]
|
||||
) -> dict[str, int]:
|
||||
"""Derive unread counts from chats; do not persist a second read-state."""
|
||||
paths = list(dict.fromkeys(path for path in workspace_paths if path))
|
||||
if not paths:
|
||||
return {}
|
||||
|
||||
workspace = Chat.meta["workspace"].as_string()
|
||||
statement = (
|
||||
select(workspace, func.count(Chat.id))
|
||||
.where(
|
||||
Chat.user_id == user_id,
|
||||
workspace.in_(paths),
|
||||
Chat.updated_at > func.coalesce(Chat.last_read_at, 0),
|
||||
)
|
||||
.group_by(workspace)
|
||||
)
|
||||
if active_chat_ids:
|
||||
statement = statement.where(Chat.id.not_in(active_chat_ids))
|
||||
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(statement)
|
||||
return {workspace: count for workspace, count in result.all() if workspace}
|
||||
|
||||
@staticmethod
|
||||
async def update_last_read_at(chat_id: str, user_id: str, last_read_at: int) -> bool:
|
||||
"""Mark a chat read without changing its activity timestamp."""
|
||||
async with await get_db() as db:
|
||||
result = await db.execute(
|
||||
update(Chat)
|
||||
.where(Chat.id == chat_id, Chat.user_id == user_id)
|
||||
.values(last_read_at=last_read_at)
|
||||
)
|
||||
await db.commit()
|
||||
return result.rowcount > 0
|
||||
|
||||
@staticmethod
|
||||
async def delete(chat_id: str) -> bool:
|
||||
async with await get_db() as db:
|
||||
|
||||
+35
-2
@@ -180,6 +180,7 @@ async def list_chats(
|
||||
"current_message_id": chat.current_message_id,
|
||||
"created_at": chat.created_at,
|
||||
"updated_at": listing_updated_at,
|
||||
"last_read_at": chat.last_read_at,
|
||||
"is_active": chat.id in active_ids,
|
||||
}
|
||||
)
|
||||
@@ -390,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"))
|
||||
@@ -402,6 +404,8 @@ async def get_chat(
|
||||
"current_message_id": chat.current_message_id,
|
||||
"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,
|
||||
@@ -532,10 +536,25 @@ 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)
|
||||
workspace = (chat.meta or {}).get("workspace", "")
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
from cptr.socket.main import emit_to_user
|
||||
|
||||
await emit_to_user(user_id, {"chat_id": chat_id, "title": title})
|
||||
unread_counts = await Chat.unread_counts_by_workspace(
|
||||
user_id, [workspace], get_active_chat_ids()
|
||||
)
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"title": title,
|
||||
"workspace": workspace,
|
||||
"updated_at": updated_at,
|
||||
"workspace_unread_count": unread_counts.get(workspace, 0),
|
||||
},
|
||||
)
|
||||
return {"ok": True, "title": title}
|
||||
|
||||
|
||||
@@ -568,6 +587,20 @@ async def delete_chat(chat_id: str, request: Request):
|
||||
await asyncio.to_thread(chat_file.unlink, True) # missing_ok=True
|
||||
|
||||
await Chat.delete(chat_id)
|
||||
from cptr.socket.main import emit_to_user
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
|
||||
unread_counts = await Chat.unread_counts_by_workspace(
|
||||
user_id, [workspace or ""], get_active_chat_ids()
|
||||
)
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"workspace": workspace or "",
|
||||
"workspace_unread_count": unread_counts.get(workspace or "", 0),
|
||||
},
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
|
||||
+14
-4
@@ -13,7 +13,7 @@ from pathlib import Path, PureWindowsPath
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Query
|
||||
from cptr.env import DATA_DIR
|
||||
from cptr.models import UserStates, Workspace
|
||||
from cptr.models import Chat, UserStates, Workspace
|
||||
from cptr.utils.config import get_or_create_user
|
||||
|
||||
router = APIRouter(prefix="/api/state", tags=["state"])
|
||||
@@ -84,11 +84,21 @@ def _workspace_display_name(path: str) -> str:
|
||||
return name or path
|
||||
|
||||
|
||||
async def _workspace_summaries(user_id: str) -> list[dict[str, str]]:
|
||||
async def _workspace_summaries(user_id: str) -> list[dict[str, str | int]]:
|
||||
workspaces = await Workspace.get_by_user(user_id)
|
||||
summaries = _dedupe_workspaces(workspaces)
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
|
||||
unread_counts = await Chat.unread_counts_by_workspace(
|
||||
user_id, [path for path, _ in summaries], get_active_chat_ids()
|
||||
)
|
||||
return [
|
||||
{"path": path, "name": workspace.name or _workspace_display_name(path)}
|
||||
for path, workspace in _dedupe_workspaces(workspaces)
|
||||
{
|
||||
"path": path,
|
||||
"name": workspace.name or _workspace_display_name(path),
|
||||
"unread_count": unread_counts.get(path, 0),
|
||||
}
|
||||
for path, workspace in summaries
|
||||
]
|
||||
|
||||
|
||||
|
||||
+31
-1
@@ -9,7 +9,8 @@ from __future__ import annotations
|
||||
|
||||
import socketio
|
||||
|
||||
from cptr.utils.config import check_access
|
||||
from cptr.models import Chat
|
||||
from cptr.utils.config import check_access, now_ms
|
||||
from cptr.env import CORS_ALLOWED_ORIGINS
|
||||
|
||||
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=CORS_ALLOWED_ORIGINS)
|
||||
@@ -77,6 +78,35 @@ async def on_chat_view(sid, data):
|
||||
del _chat_view_sids[(user_id, chat_id)]
|
||||
|
||||
|
||||
@sio.on("chat:read")
|
||||
async def on_chat_read(sid, data):
|
||||
"""Persist a user's explicit read acknowledgement for a chat."""
|
||||
session = await sio.get_session(sid)
|
||||
user_id = session.get("user_id")
|
||||
chat_id = data.get("chat_id") if isinstance(data, dict) else None
|
||||
if not user_id or not isinstance(chat_id, str):
|
||||
return
|
||||
|
||||
last_read_at = now_ms()
|
||||
if await Chat.update_last_read_at(chat_id, user_id, last_read_at):
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
workspace = (chat.meta or {}).get("workspace", "") if chat else ""
|
||||
from cptr.utils.chat_task import get_active_chat_ids
|
||||
|
||||
unread_counts = await Chat.unread_counts_by_workspace(
|
||||
user_id, [workspace], get_active_chat_ids()
|
||||
)
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"chat_id": chat_id,
|
||||
"workspace": workspace,
|
||||
"last_read_at": last_read_at,
|
||||
"workspace_unread_count": unread_counts.get(workspace, 0),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def emit_to_user(user_id: str, data: dict):
|
||||
"""Send events:chat to all of a user's connected tabs/windows."""
|
||||
for sid in list(_user_sids.get(user_id, set())):
|
||||
|
||||
@@ -134,8 +134,10 @@ async def ensure_browser(port: int = 9222) -> str:
|
||||
"--disable-translate",
|
||||
"--disable-extensions",
|
||||
f"--user-data-dir={_user_data_dir}",
|
||||
"about:blank",
|
||||
]
|
||||
if Path("/.dockerenv").exists():
|
||||
args.append("--no-sandbox")
|
||||
args.append("about:blank")
|
||||
|
||||
logger.info("Launching Chrome: %s", " ".join(args[:3]))
|
||||
|
||||
|
||||
@@ -382,6 +382,23 @@ def start_task(
|
||||
_tasks[message_id] = task
|
||||
_task_chat[message_id] = chat_id
|
||||
|
||||
async def emit_active():
|
||||
unread_counts = await Chat.unread_counts_by_workspace(
|
||||
user_id, [workspace], get_active_chat_ids()
|
||||
)
|
||||
await emit_to_user(
|
||||
user_id,
|
||||
{
|
||||
"type": "chat:active",
|
||||
"chat_id": chat_id,
|
||||
"workspace": workspace,
|
||||
"active": True,
|
||||
"workspace_unread_count": unread_counts.get(workspace, 0),
|
||||
},
|
||||
)
|
||||
|
||||
asyncio.create_task(emit_active())
|
||||
|
||||
|
||||
async def cancel_task(message_id: str) -> bool:
|
||||
"""Cancel a running task. Returns True if found."""
|
||||
@@ -2625,6 +2642,26 @@ 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:
|
||||
await Chat.touch(chat_id, now_ms())
|
||||
chat = await Chat.get_by_id(chat_id)
|
||||
unread_counts = await Chat.unread_counts_by_workspace(
|
||||
user_id, [workspace], get_active_chat_ids()
|
||||
)
|
||||
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,
|
||||
"workspace_unread_count": unread_counts.get(workspace, 0),
|
||||
},
|
||||
)
|
||||
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:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.9.4"
|
||||
version = "0.9.5"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
|
||||
Reference in new issue
Block a user