mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
57d7a66679
commit
9f7a28fc22
6 files changed
+809
No files matched your search
@@ -78,6 +78,40 @@ export interface CompactChatResult {
|
||||
context_usage?: ContextUsage | null;
|
||||
}
|
||||
|
||||
export interface UsageHeatmapEntry {
|
||||
date: string;
|
||||
tokens: number;
|
||||
messages: number;
|
||||
chats: number;
|
||||
models: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface UsageResponse {
|
||||
totals: {
|
||||
lifetime_tokens: number;
|
||||
peak_daily_tokens: number;
|
||||
longest_chat_seconds: number;
|
||||
current_streak: number;
|
||||
longest_streak: number;
|
||||
models_used: number;
|
||||
user_messages: number;
|
||||
assistant_messages: number;
|
||||
messages: number;
|
||||
total_chats: number;
|
||||
};
|
||||
insights: {
|
||||
average_tokens_per_chat: number;
|
||||
average_messages_per_active_day: number;
|
||||
user_message_share: number;
|
||||
assistant_message_share: number;
|
||||
};
|
||||
heatmap: UsageHeatmapEntry[];
|
||||
weekly_heatmap: UsageHeatmapEntry[];
|
||||
cumulative_heatmap: UsageHeatmapEntry[];
|
||||
top_models: { model_id: string; messages: number; total_tokens: number }[];
|
||||
top_tools: { name: string; count: number }[];
|
||||
}
|
||||
|
||||
// ── Queries ─────────────────────────────────────────────────
|
||||
|
||||
export const getChats = (
|
||||
@@ -96,6 +130,8 @@ export const getChat = (chatId: string, modelId?: string) => {
|
||||
return fetchJSON<ChatDetail>(`/api/chats/${chatId}${suffix}`);
|
||||
};
|
||||
|
||||
export const getUsage = () => fetchJSON<UsageResponse>('/api/chats/usage');
|
||||
|
||||
export const deleteChat = (chatId: string) =>
|
||||
fetchJSON<{ ok: boolean }>(`/api/chats/${chatId}`, { method: 'DELETE' });
|
||||
|
||||
|
||||
@@ -121,6 +121,13 @@
|
||||
<path
|
||||
d="M19.6224 10.3954L18.5247 7.7448L20 6L18 4L16.2647 5.48295L13.5578 4.36974L12.9353 2H10.981L10.3491 4.40113L7.70441 5.51596L6 4L4 6L5.45337 7.78885L4.3725 10.4463L2 11V13L4.40111 13.6555L5.51575 16.2997L4 18L6 20L7.79116 18.5403L10.397 19.6123L11 22H13L13.6045 19.6132L16.2551 18.5155C16.6969 18.8313 18 20 18 20L20 18L18.5159 16.2494L19.6139 13.598L21.9999 12.9772L22 11L19.6224 10.3954Z"
|
||||
/>
|
||||
{:else if name === 'usage'}
|
||||
<path d="M4 19V5" />
|
||||
<path d="M4 19H20" />
|
||||
<path d="M8 16V12" />
|
||||
<path d="M12 16V8" />
|
||||
<path d="M16 16V10" />
|
||||
<path d="M20 16V6" />
|
||||
{:else if name === 'half-moon'}
|
||||
<path
|
||||
d="M3 11.5066C3 16.7497 7.25034 21 12.4934 21C16.2209 21 19.4466 18.8518 21 15.7259C12.4934 15.7259 8.27411 11.5066 8.27411 3C5.14821 4.55344 3 7.77915 3 11.5066Z"
|
||||
|
||||
@@ -0,0 +1,512 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { getUsage, type UsageHeatmapEntry, type UsageResponse } from '$lib/apis/chat';
|
||||
import { i18next } from '$lib/i18n';
|
||||
import { chatModels } from '$lib/stores/chat';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
|
||||
type HeatmapMode = 'daily' | 'weekly' | 'cumulative';
|
||||
type HeatmapCell = UsageHeatmapEntry | null;
|
||||
type MonthLabel = { label: string; column: number; span: number };
|
||||
|
||||
let usage = $state<UsageResponse | null>(null);
|
||||
let loading = $state(true);
|
||||
let heatmapMode = $state<HeatmapMode>('daily');
|
||||
let heatmapContainerWidth = $state(0);
|
||||
|
||||
const HEATMAP_MIN_CELL_PX = 8;
|
||||
const HEATMAP_MAX_CELL_PX = 10;
|
||||
const HEATMAP_GAP_PX = 4;
|
||||
const MIN_HEATMAP_COLUMNS = 26;
|
||||
const DEFAULT_HEATMAP_COLUMNS = 26;
|
||||
const MIN_MONTH_LABEL_GAP = 6;
|
||||
const tr = (key: string, opts?: Record<string, unknown>) => i18next.t(key, opts) as string;
|
||||
|
||||
const heatmapModes: Array<{ value: HeatmapMode; label: string }> = [
|
||||
{ value: 'daily', label: 'usage.daily' },
|
||||
{ value: 'weekly', label: 'usage.weekly' },
|
||||
{ value: 'cumulative', label: 'usage.cumulative' }
|
||||
];
|
||||
|
||||
const palettes = [
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-green-100 dark:bg-green-900/40',
|
||||
'bg-green-300 dark:bg-green-700/60',
|
||||
'bg-green-500 dark:bg-green-600/80',
|
||||
'bg-green-700 dark:bg-green-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-blue-100 dark:bg-blue-900/40',
|
||||
'bg-blue-300 dark:bg-blue-700/60',
|
||||
'bg-blue-500 dark:bg-blue-600/80',
|
||||
'bg-blue-700 dark:bg-blue-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-purple-100 dark:bg-purple-900/40',
|
||||
'bg-purple-300 dark:bg-purple-700/60',
|
||||
'bg-purple-500 dark:bg-purple-600/80',
|
||||
'bg-purple-700 dark:bg-purple-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-orange-100 dark:bg-orange-900/40',
|
||||
'bg-orange-300 dark:bg-orange-700/60',
|
||||
'bg-orange-500 dark:bg-orange-600/80',
|
||||
'bg-orange-700 dark:bg-orange-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-rose-100 dark:bg-rose-900/40',
|
||||
'bg-rose-300 dark:bg-rose-700/60',
|
||||
'bg-rose-500 dark:bg-rose-600/80',
|
||||
'bg-rose-700 dark:bg-rose-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-yellow-100 dark:bg-yellow-900/40',
|
||||
'bg-yellow-300 dark:bg-yellow-700/60',
|
||||
'bg-yellow-500 dark:bg-yellow-600/80',
|
||||
'bg-yellow-700 dark:bg-yellow-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-cyan-100 dark:bg-cyan-900/40',
|
||||
'bg-cyan-300 dark:bg-cyan-700/60',
|
||||
'bg-cyan-500 dark:bg-cyan-600/80',
|
||||
'bg-cyan-700 dark:bg-cyan-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-red-100 dark:bg-red-900/40',
|
||||
'bg-red-300 dark:bg-red-700/60',
|
||||
'bg-red-500 dark:bg-red-600/80',
|
||||
'bg-red-700 dark:bg-red-500'
|
||||
],
|
||||
[
|
||||
'bg-gray-100 dark:bg-gray-800',
|
||||
'bg-neutral-200 dark:bg-neutral-800',
|
||||
'bg-neutral-400 dark:bg-neutral-600',
|
||||
'bg-neutral-600 dark:bg-neutral-400',
|
||||
'bg-neutral-800 dark:bg-neutral-200'
|
||||
]
|
||||
];
|
||||
|
||||
const modelNames = $derived(
|
||||
new Map($chatModels.map((model) => [model.id, model.name || model.id]))
|
||||
);
|
||||
const dailyHeatmap = $derived(usage?.heatmap ?? []);
|
||||
const weeklyHeatmap = $derived(
|
||||
new Map((usage?.weekly_heatmap ?? []).map((entry) => [entry.date, entry]))
|
||||
);
|
||||
const cumulativeHeatmap = $derived(
|
||||
new Map((usage?.cumulative_heatmap ?? []).map((entry) => [entry.date, entry]))
|
||||
);
|
||||
const heatmapData = $derived(
|
||||
buildDisplayHeatmap(dailyHeatmap, heatmapMode, weeklyHeatmap, cumulativeHeatmap)
|
||||
);
|
||||
const totalHeatmapColumns = $derived(Math.max(Math.ceil(heatmapData.length / 7), 1));
|
||||
const maxHeatmapColumns = $derived(
|
||||
heatmapContainerWidth
|
||||
? Math.max(
|
||||
Math.min(totalHeatmapColumns, MIN_HEATMAP_COLUMNS),
|
||||
Math.floor(
|
||||
(heatmapContainerWidth + HEATMAP_GAP_PX) / (HEATMAP_MIN_CELL_PX + HEATMAP_GAP_PX)
|
||||
)
|
||||
)
|
||||
: Math.min(totalHeatmapColumns, DEFAULT_HEATMAP_COLUMNS)
|
||||
);
|
||||
const visibleHeatmapColumns = $derived(Math.min(totalHeatmapColumns, maxHeatmapColumns));
|
||||
const heatmapCells = $derived(buildHeatmapCells(heatmapData, visibleHeatmapColumns));
|
||||
const heatmapColumns = $derived(Math.max(Math.ceil(heatmapCells.length / 7), 1));
|
||||
const heatmapGridWidth = $derived(
|
||||
`${heatmapColumns * HEATMAP_MAX_CELL_PX + (heatmapColumns - 1) * HEATMAP_GAP_PX}px`
|
||||
);
|
||||
const monthLabels = $derived(buildMonthLabels(heatmapCells, heatmapColumns));
|
||||
const hasUsage = $derived(
|
||||
(usage?.totals.messages ?? 0) > 0 || (usage?.totals.lifetime_tokens ?? 0) > 0
|
||||
);
|
||||
|
||||
onMount(loadUsage);
|
||||
|
||||
async function loadUsage() {
|
||||
loading = true;
|
||||
try {
|
||||
usage = await getUsage();
|
||||
} catch {
|
||||
usage = null;
|
||||
toast.error(tr('usage.failedToLoad'));
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function weekStart(dateString: string) {
|
||||
const date = new Date(`${dateString}T00:00:00`);
|
||||
const daysSinceMonday = (date.getDay() + 6) % 7;
|
||||
date.setDate(date.getDate() - daysSinceMonday);
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0');
|
||||
const day = `${date.getDate()}`.padStart(2, '0');
|
||||
return `${date.getFullYear()}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function buildDisplayHeatmap(
|
||||
data: UsageHeatmapEntry[],
|
||||
mode: HeatmapMode,
|
||||
weekly: Map<string, UsageHeatmapEntry>,
|
||||
cumulative: Map<string, UsageHeatmapEntry>
|
||||
) {
|
||||
if (mode === 'daily') return data;
|
||||
return data.map((day) => {
|
||||
const aggregate =
|
||||
mode === 'weekly' ? weekly.get(weekStart(day.date)) : cumulative.get(day.date);
|
||||
return aggregate ? { ...aggregate, date: day.date } : day;
|
||||
});
|
||||
}
|
||||
|
||||
function buildHeatmapCells(data: UsageHeatmapEntry[], visibleColumns: number) {
|
||||
if (data.length === 0) return [];
|
||||
const cells = data.slice(-Math.max(7, visibleColumns * 7));
|
||||
const trailingBlanks = Array.from({ length: (7 - (cells.length % 7)) % 7 }, () => null);
|
||||
return [...cells, ...trailingBlanks];
|
||||
}
|
||||
|
||||
function buildMonthLabels(cells: HeatmapCell[], columns: number): MonthLabel[] {
|
||||
const labels: MonthLabel[] = [];
|
||||
let currentMonth = '';
|
||||
let lastLabelColumn = -MIN_MONTH_LABEL_GAP;
|
||||
|
||||
cells.forEach((entry, index) => {
|
||||
if (!entry) return;
|
||||
const month = entry.date.slice(0, 7);
|
||||
if (month === currentMonth) return;
|
||||
|
||||
const column = Math.floor(index / 7) + 1;
|
||||
if (column - lastLabelColumn < MIN_MONTH_LABEL_GAP) {
|
||||
currentMonth = month;
|
||||
return;
|
||||
}
|
||||
|
||||
labels.push({
|
||||
label: new Date(`${entry.date}T00:00:00`).toLocaleString(undefined, { month: 'short' }),
|
||||
column,
|
||||
span: Math.min(MIN_MONTH_LABEL_GAP, columns - column + 1)
|
||||
});
|
||||
lastLabelColumn = column;
|
||||
currentMonth = month;
|
||||
});
|
||||
|
||||
return labels;
|
||||
}
|
||||
|
||||
function topItem(entry: UsageHeatmapEntry) {
|
||||
return Object.entries(entry.models ?? {}).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
|
||||
}
|
||||
|
||||
function modelPalette(modelId: string | null) {
|
||||
if (!modelId) return palettes[0];
|
||||
const index = Math.max(0, modelId.toLowerCase().charCodeAt(0) - 97) % palettes.length;
|
||||
return palettes[index];
|
||||
}
|
||||
|
||||
function intensity(entry: UsageHeatmapEntry) {
|
||||
if (entry.messages >= 20) return 4;
|
||||
if (entry.messages >= 10) return 3;
|
||||
if (entry.messages >= 5) return 2;
|
||||
if (entry.messages > 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function tooltipFor(entry: UsageHeatmapEntry) {
|
||||
const label =
|
||||
heatmapMode === 'weekly'
|
||||
? `${tr('usage.weekOf')} ${weekStart(entry.date)}`
|
||||
: heatmapMode === 'cumulative'
|
||||
? `${tr('usage.through')} ${entry.date}`
|
||||
: entry.date;
|
||||
const model = topItem(entry);
|
||||
const models = Object.entries(entry.models ?? {}).sort((a, b) => b[1] - a[1]);
|
||||
const modelSummary =
|
||||
models.length > 0
|
||||
? models
|
||||
.slice(0, 3)
|
||||
.map(([id, count]) => `${modelName(id)} ${count}`)
|
||||
.join(', ')
|
||||
: tr('usage.noModelData');
|
||||
|
||||
return `${label}: ${formatNumber(entry.tokens)} ${tr('usage.tokens')}, ${entry.messages.toLocaleString()} ${tr('usage.messages')}, ${entry.chats.toLocaleString()} ${tr('usage.chats')}${model ? ` (${modelName(model)})` : ''}. ${modelSummary}`;
|
||||
}
|
||||
|
||||
function formatDuration(seconds: number) {
|
||||
if (!seconds) return '0m';
|
||||
const days = Math.floor(seconds / 86400);
|
||||
const hours = Math.floor((seconds % 86400) / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
|
||||
if (days > 0) return `${days}d ${hours}h`;
|
||||
if (hours > 0) return `${hours}h ${minutes}m`;
|
||||
return `${minutes}m`;
|
||||
}
|
||||
|
||||
function formatNumber(value: number) {
|
||||
return new Intl.NumberFormat(undefined, {
|
||||
notation: 'compact',
|
||||
maximumFractionDigits: 1
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
function modelName(id: string | null) {
|
||||
return id ? (modelNames.get(id) ?? id) : '-';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{tr('usage.title')}</h2>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="flex flex-1 items-center justify-center">
|
||||
<Spinner size={20} />
|
||||
</div>
|
||||
{:else if !usage}
|
||||
<div class="flex flex-1 items-center justify-center text-xs text-gray-500">
|
||||
{tr('usage.failedToLoad')}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="scrollbar-hover min-h-0 flex-1 overflow-y-auto pr-1.5">
|
||||
<section class="border-t border-gray-100 pt-3 dark:border-white/6">
|
||||
<h3 class="mb-3 text-xs text-gray-400 dark:text-gray-600">{tr('usage.overview')}</h3>
|
||||
<div class="grid grid-cols-2 gap-x-6 gap-y-3 md:grid-cols-5">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{formatNumber(usage.totals.lifetime_tokens)}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.lifetimeTokens')}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{formatNumber(usage.totals.peak_daily_tokens)}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.peakTokens')}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{formatDuration(usage.totals.longest_chat_seconds)}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.longestActiveChat')}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{usage.totals.current_streak.toLocaleString()}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.currentStreak')}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{usage.totals.longest_streak.toLocaleString()}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.longestStreak')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-4 w-full">
|
||||
<div class="mb-2 flex min-w-0 items-center justify-between gap-3">
|
||||
<h3 class="min-w-0 shrink truncate text-xs text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.tokenActivity')}
|
||||
</h3>
|
||||
<div
|
||||
class="flex min-w-0 max-w-[70%] shrink items-center gap-3 overflow-hidden whitespace-nowrap"
|
||||
>
|
||||
{#each heatmapModes as mode}
|
||||
<button
|
||||
type="button"
|
||||
class="min-w-0 shrink truncate whitespace-nowrap text-xs transition-colors {heatmapMode ===
|
||||
mode.value
|
||||
? 'text-gray-900 dark:text-white'
|
||||
: 'text-gray-400 hover:text-gray-700 dark:hover:text-gray-200'}"
|
||||
onclick={() => (heatmapMode = mode.value)}
|
||||
>
|
||||
{tr(mode.label)}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pb-1">
|
||||
<div class="w-full min-w-0 overflow-hidden" bind:clientWidth={heatmapContainerWidth}>
|
||||
<div
|
||||
class="mx-auto grid grid-flow-col"
|
||||
style="width: min(100%, {heatmapGridWidth}); gap: {HEATMAP_GAP_PX}px; aspect-ratio: {heatmapColumns} / 7; grid-template-columns: repeat({heatmapColumns}, minmax(0, 1fr)); grid-template-rows: repeat(7, minmax(0, 1fr));"
|
||||
>
|
||||
{#each heatmapCells as entry}
|
||||
{#if entry}
|
||||
<div
|
||||
class="h-full w-full rounded-[2px] {modelPalette(topItem(entry))[
|
||||
intensity(entry)
|
||||
]}"
|
||||
aria-label={tooltipFor(entry)}
|
||||
use:tooltip={tooltipFor(entry)}
|
||||
></div>
|
||||
{:else}
|
||||
<div class="h-full w-full"></div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="mx-auto mt-2 grid text-[0.6875rem] leading-none text-gray-400 dark:text-gray-600"
|
||||
style="width: min(100%, {heatmapGridWidth}); column-gap: {HEATMAP_GAP_PX}px; grid-template-columns: repeat({heatmapColumns}, minmax(0, 1fr));"
|
||||
>
|
||||
{#each monthLabels as month}
|
||||
<div class="truncate" style="grid-column: {month.column} / span {month.span};">
|
||||
{month.label}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if usage.top_models.length > 0}
|
||||
<div
|
||||
class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[0.6875rem] text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
{#each usage.top_models.slice(0, 6) as model}
|
||||
<div class="flex min-w-0 items-center gap-1.5">
|
||||
<span class="size-2 shrink-0 rounded-[2px] {modelPalette(model.model_id)[3]}"
|
||||
></span>
|
||||
<span class="max-w-28 truncate">{modelName(model.model_id)}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{#if !hasUsage}
|
||||
<section class="mt-5 border-t border-gray-100 pt-3 dark:border-white/6">
|
||||
<h3 class="mb-2 text-xs text-gray-400 dark:text-gray-600">{tr('usage.activity')}</h3>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">{tr('usage.noData')}</div>
|
||||
</section>
|
||||
{:else}
|
||||
<section class="mt-5 border-t border-gray-100 pt-3 dark:border-white/6">
|
||||
<h3 class="mb-1 text-xs text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.activityInsights')}
|
||||
</h3>
|
||||
<div class="divide-y divide-gray-100 dark:divide-white/6">
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tr('usage.models')}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-900 dark:text-white"
|
||||
>{usage.totals.models_used.toLocaleString()}</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tr('usage.averageTokensPerChat')}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-900 dark:text-white"
|
||||
>{formatNumber(usage.insights.average_tokens_per_chat)}</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tr('usage.averageMessagesPerActiveDay')}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-900 dark:text-white"
|
||||
>{usage.insights.average_messages_per_active_day.toLocaleString()}</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tr('usage.userMessages')}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-900 dark:text-white"
|
||||
>{usage.totals.user_messages.toLocaleString()} · {usage.insights
|
||||
.user_message_share}%</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tr('usage.assistantMessages')}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-900 dark:text-white"
|
||||
>{usage.totals.assistant_messages.toLocaleString()} · {usage.insights
|
||||
.assistant_message_share}%</span
|
||||
>
|
||||
</div>
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tr('usage.totalChats')}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-900 dark:text-white"
|
||||
>{usage.totals.total_chats.toLocaleString()}</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-5 border-t border-gray-100 pt-3 dark:border-white/6">
|
||||
<h3 class="mb-1 text-xs text-gray-400 dark:text-gray-600">{tr('usage.topModels')}</h3>
|
||||
{#if usage.top_models.length === 0}
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">{tr('usage.noModelUsage')}</div>
|
||||
{:else}
|
||||
<div class="divide-y divide-gray-100 dark:divide-white/6">
|
||||
{#each usage.top_models as model}
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{modelName(model.model_id)}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-500 dark:text-gray-400">
|
||||
{model.messages.toLocaleString()}
|
||||
{tr('usage.messages')} · {formatNumber(model.total_tokens)}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
{#if usage.top_tools.length > 0}
|
||||
<section class="mt-5 border-t border-gray-100 pt-3 dark:border-white/6">
|
||||
<h3 class="mb-1 text-xs text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.mostUsedTools')}
|
||||
</h3>
|
||||
<div class="divide-y divide-gray-100 dark:divide-white/6">
|
||||
{#each usage.top_tools as tool}
|
||||
<div class="flex min-h-9 items-center justify-between gap-3">
|
||||
<span class="min-w-0 truncate text-xs text-gray-600 dark:text-gray-400"
|
||||
>{tool.name}</span
|
||||
>
|
||||
<span class="shrink-0 text-xs text-gray-500 dark:text-gray-400">
|
||||
{tool.count.toLocaleString()}
|
||||
{tr('usage.runs')}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<div class="mt-4 text-right text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{tr('usage.estimateNote')}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -5,6 +5,7 @@
|
||||
import General from './Settings/General.svelte';
|
||||
import Notifications from './Settings/Notifications.svelte';
|
||||
import Appearance from './Settings/Appearance.svelte';
|
||||
import Usage from './Settings/Usage.svelte';
|
||||
import Memory from './Settings/Memory.svelte';
|
||||
import PWA from './Settings/PWA.svelte';
|
||||
import Account from './Settings/Account.svelte';
|
||||
@@ -32,6 +33,7 @@
|
||||
| 'general'
|
||||
| 'notifications'
|
||||
| 'appearance'
|
||||
| 'usage'
|
||||
| 'memory'
|
||||
| 'pwa'
|
||||
| 'keyboard'
|
||||
@@ -91,6 +93,7 @@
|
||||
const tabs: SettingsTab[] = [
|
||||
{ id: 'general', label: $t('settings.general'), icon: 'settings' },
|
||||
{ id: 'appearance', label: $t('settings.appearance'), icon: 'sun-light' },
|
||||
{ id: 'usage', label: 'Usage', icon: 'usage' },
|
||||
{ id: 'notifications', label: $t('general.notifications'), icon: 'chat-bubble' },
|
||||
{ id: 'keyboard', label: $t('settings.keyboard'), icon: 'terminal' },
|
||||
{ id: 'account', label: $t('settings.account'), icon: 'user' }
|
||||
@@ -202,6 +205,8 @@
|
||||
<Notifications />
|
||||
{:else if activeTab === 'appearance'}
|
||||
<Appearance />
|
||||
{:else if activeTab === 'usage'}
|
||||
<Usage />
|
||||
{:else if activeTab === 'memory'}
|
||||
<Memory />
|
||||
{:else if activeTab === 'pwa' && showPwaSettings}
|
||||
|
||||
@@ -122,6 +122,7 @@
|
||||
"settings.back": "Back",
|
||||
"settings.general": "General",
|
||||
"settings.appearance": "Appearance",
|
||||
"settings.usage": "Usage",
|
||||
"settings.memory": "Memory",
|
||||
"pwa.settingsTitle": "Progressive Web App",
|
||||
"intent.chooseWorkspace": "Workspace",
|
||||
@@ -152,6 +153,38 @@
|
||||
"settings.save": "Save",
|
||||
"settings.saved": "Saved",
|
||||
"settings.saving": "Saving…",
|
||||
"usage.title": "Usage",
|
||||
"usage.failedToLoad": "Failed to load usage",
|
||||
"usage.overview": "Overview",
|
||||
"usage.lifetimeTokens": "Lifetime tokens",
|
||||
"usage.peakTokens": "Peak tokens",
|
||||
"usage.longestActiveChat": "Longest active chat",
|
||||
"usage.currentStreak": "Current streak",
|
||||
"usage.longestStreak": "Longest streak",
|
||||
"usage.tokenActivity": "Token activity",
|
||||
"usage.daily": "Daily",
|
||||
"usage.weekly": "Weekly",
|
||||
"usage.cumulative": "Cumulative",
|
||||
"usage.weekOf": "Week of",
|
||||
"usage.through": "Through",
|
||||
"usage.tokens": "tokens",
|
||||
"usage.messages": "messages",
|
||||
"usage.chats": "chats",
|
||||
"usage.runs": "runs",
|
||||
"usage.noModelData": "No model data",
|
||||
"usage.activity": "Activity",
|
||||
"usage.noData": "No usage data found",
|
||||
"usage.activityInsights": "Activity insights",
|
||||
"usage.models": "Models",
|
||||
"usage.averageTokensPerChat": "Average tokens per chat",
|
||||
"usage.averageMessagesPerActiveDay": "Average messages per active day",
|
||||
"usage.userMessages": "User messages",
|
||||
"usage.assistantMessages": "Assistant messages",
|
||||
"usage.totalChats": "Total chats",
|
||||
"usage.topModels": "Top models",
|
||||
"usage.noModelUsage": "No model usage found",
|
||||
"usage.mostUsedTools": "Most used tools",
|
||||
"usage.estimateNote": "Token counts are estimates and may not reflect actual API usage",
|
||||
"memory.failedToLoad": "Failed to load memory",
|
||||
"memory.failedToSaveSettings": "Failed to save memory settings",
|
||||
"memory.failedToUpdate": "Failed to update memory",
|
||||
|
||||
@@ -3,17 +3,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict
|
||||
from copy import deepcopy
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import json
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from cptr.models import Chat, ChatMessage, Config, is_internal_chat
|
||||
from cptr.utils.config import check_access, now_ms, _get_jwt_secret
|
||||
from cptr.utils.crypto import decrypt_key
|
||||
from cptr.utils.db import get_db
|
||||
from cptr.utils.workspace import ensure_cptr_gitignored
|
||||
from cptr.utils.chat_export import chat_directory
|
||||
|
||||
@@ -324,6 +328,218 @@ async def get_models(request: Request):
|
||||
return {"models": models, "default": default_model}
|
||||
|
||||
|
||||
@router.get("/usage")
|
||||
async def get_usage(request: Request):
|
||||
"""Aggregate personal chat usage for the settings Usage tab."""
|
||||
user_id = _get_user(request)
|
||||
|
||||
async with await get_db() as db:
|
||||
chat_result = await db.execute(select(Chat).where(Chat.user_id == user_id))
|
||||
chats = [
|
||||
chat
|
||||
for chat in chat_result.scalars().all()
|
||||
if not is_internal_chat(chat.meta if isinstance(chat.meta, dict) else None)
|
||||
]
|
||||
|
||||
messages = []
|
||||
if chats:
|
||||
message_result = await db.execute(
|
||||
select(ChatMessage)
|
||||
.where(ChatMessage.chat_id.in_([chat.id for chat in chats]))
|
||||
.order_by(ChatMessage.created_at)
|
||||
)
|
||||
messages = list(message_result.scalars().all())
|
||||
|
||||
chat_ids_by_day: dict[str, set[str]] = defaultdict(set)
|
||||
day_stats: dict[str, dict] = defaultdict(lambda: {"tokens": 0, "messages": 0, "models": {}})
|
||||
chat_bounds: dict[str, list[int]] = {}
|
||||
model_stats: dict[str, dict] = defaultdict(lambda: {"messages": 0, "total_tokens": 0})
|
||||
tool_counts: dict[str, int] = defaultdict(int)
|
||||
models_used: set[str] = set()
|
||||
user_messages = 0
|
||||
assistant_messages = 0
|
||||
lifetime_tokens = 0
|
||||
|
||||
for message in messages:
|
||||
created_at = int(message.created_at or 0)
|
||||
created_seconds = created_at / (
|
||||
1_000_000_000
|
||||
if created_at > 10_000_000_000_000
|
||||
else 1000
|
||||
if created_at > 10_000_000_000
|
||||
else 1
|
||||
)
|
||||
day = datetime.fromtimestamp(created_seconds, tz=timezone.utc).date().isoformat()
|
||||
day_stats[day]["messages"] += 1
|
||||
chat_ids_by_day[day].add(message.chat_id)
|
||||
|
||||
bounds = chat_bounds.setdefault(message.chat_id, [message.created_at, message.created_at])
|
||||
bounds[0] = min(bounds[0], message.created_at)
|
||||
bounds[1] = max(bounds[1], message.created_at)
|
||||
|
||||
if message.role == "user":
|
||||
user_messages += 1
|
||||
elif message.role == "assistant":
|
||||
assistant_messages += 1
|
||||
|
||||
model_id = message.model or None
|
||||
usage = message.usage if isinstance(message.usage, dict) else {}
|
||||
try:
|
||||
tokens = max(
|
||||
0,
|
||||
int(
|
||||
usage.get("total_tokens")
|
||||
or (usage.get("input_tokens") or usage.get("prompt_tokens") or 0)
|
||||
+ (usage.get("output_tokens") or usage.get("completion_tokens") or 0)
|
||||
or 0
|
||||
),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
tokens = 0
|
||||
if tokens:
|
||||
lifetime_tokens += tokens
|
||||
day_stats[day]["tokens"] += tokens
|
||||
|
||||
if message.role == "assistant" and model_id:
|
||||
models_used.add(model_id)
|
||||
day_models = day_stats[day]["models"]
|
||||
day_models[model_id] = day_models.get(model_id, 0) + 1
|
||||
model_stats[model_id]["messages"] += 1
|
||||
model_stats[model_id]["total_tokens"] += tokens
|
||||
|
||||
if isinstance(message.output, list):
|
||||
for item in message.output:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
item_type = str(item.get("type") or "")
|
||||
if "tool" not in item_type and "function_call" not in item_type:
|
||||
continue
|
||||
name = item.get("name")
|
||||
if not name and isinstance(item.get("function"), dict):
|
||||
name = item["function"].get("name")
|
||||
if isinstance(name, str) and name:
|
||||
tool_counts[name] += 1
|
||||
|
||||
today = datetime.now(timezone.utc).date()
|
||||
start = today - timedelta(days=364)
|
||||
heatmap = []
|
||||
cumulative_tokens = 0
|
||||
cumulative_messages = 0
|
||||
cumulative_chats: set[str] = set()
|
||||
weekly: dict[str, dict] = defaultdict(
|
||||
lambda: {"tokens": 0, "messages": 0, "chats": set(), "models": {}}
|
||||
)
|
||||
cumulative = []
|
||||
|
||||
for offset in range(365):
|
||||
current = start + timedelta(days=offset)
|
||||
key = current.isoformat()
|
||||
stats = day_stats.get(key, {"tokens": 0, "messages": 0, "models": {}})
|
||||
chats_for_day = chat_ids_by_day.get(key, set())
|
||||
entry = {
|
||||
"date": key,
|
||||
"tokens": stats["tokens"],
|
||||
"messages": stats["messages"],
|
||||
"chats": len(chats_for_day),
|
||||
"models": stats["models"],
|
||||
}
|
||||
heatmap.append(entry)
|
||||
|
||||
week_key = (current - timedelta(days=current.weekday())).isoformat()
|
||||
weekly_entry = weekly[week_key]
|
||||
weekly_entry["tokens"] += stats["tokens"]
|
||||
weekly_entry["messages"] += stats["messages"]
|
||||
weekly_entry["chats"].update(chats_for_day)
|
||||
for model_id, count in stats["models"].items():
|
||||
weekly_entry["models"][model_id] = weekly_entry["models"].get(model_id, 0) + count
|
||||
|
||||
cumulative_tokens += stats["tokens"]
|
||||
cumulative_messages += stats["messages"]
|
||||
cumulative_chats.update(chats_for_day)
|
||||
cumulative.append(
|
||||
{
|
||||
"date": key,
|
||||
"tokens": cumulative_tokens,
|
||||
"messages": cumulative_messages,
|
||||
"chats": len(cumulative_chats),
|
||||
"models": dict(stats["models"]),
|
||||
}
|
||||
)
|
||||
|
||||
active_days = [day for day, stats in day_stats.items() if stats["messages"] > 0]
|
||||
active_dates = {date.fromisoformat(day) for day in active_days}
|
||||
current_streak = 0
|
||||
cursor = today
|
||||
while cursor in active_dates:
|
||||
current_streak += 1
|
||||
cursor -= timedelta(days=1)
|
||||
|
||||
longest_streak = 0
|
||||
run = 0
|
||||
previous = None
|
||||
for active_date in sorted(active_dates):
|
||||
run = run + 1 if previous and active_date == previous + timedelta(days=1) else 1
|
||||
previous = active_date
|
||||
longest_streak = max(longest_streak, run)
|
||||
|
||||
total_chats = len(chats)
|
||||
longest_chat_seconds = 0
|
||||
for first, last in chat_bounds.values():
|
||||
longest_chat_seconds = max(longest_chat_seconds, max(0, (last - first) // 1000))
|
||||
|
||||
weekly_heatmap = [
|
||||
{
|
||||
"date": week,
|
||||
"tokens": stats["tokens"],
|
||||
"messages": stats["messages"],
|
||||
"chats": len(stats["chats"]),
|
||||
"models": stats["models"],
|
||||
}
|
||||
for week, stats in sorted(weekly.items())
|
||||
]
|
||||
total_messages = user_messages + assistant_messages
|
||||
|
||||
return {
|
||||
"totals": {
|
||||
"lifetime_tokens": lifetime_tokens,
|
||||
"peak_daily_tokens": max((entry["tokens"] for entry in heatmap), default=0),
|
||||
"longest_chat_seconds": longest_chat_seconds,
|
||||
"current_streak": current_streak,
|
||||
"longest_streak": longest_streak,
|
||||
"models_used": len(models_used),
|
||||
"user_messages": user_messages,
|
||||
"assistant_messages": assistant_messages,
|
||||
"messages": total_messages,
|
||||
"total_chats": total_chats,
|
||||
},
|
||||
"insights": {
|
||||
"average_tokens_per_chat": round(lifetime_tokens / total_chats) if total_chats else 0,
|
||||
"average_messages_per_active_day": round(total_messages / len(active_days))
|
||||
if active_days
|
||||
else 0,
|
||||
"user_message_share": round((user_messages / total_messages) * 100)
|
||||
if total_messages
|
||||
else 0,
|
||||
"assistant_message_share": round((assistant_messages / total_messages) * 100)
|
||||
if total_messages
|
||||
else 0,
|
||||
},
|
||||
"heatmap": heatmap,
|
||||
"weekly_heatmap": weekly_heatmap,
|
||||
"cumulative_heatmap": cumulative,
|
||||
"top_models": [
|
||||
{"model_id": model_id, **stats}
|
||||
for model_id, stats in sorted(
|
||||
model_stats.items(), key=lambda item: item[1]["messages"], reverse=True
|
||||
)
|
||||
],
|
||||
"top_tools": [
|
||||
{"name": name, "count": count}
|
||||
for name, count in sorted(tool_counts.items(), key=lambda item: item[1], reverse=True)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def _fetch_provider_models(conn: dict) -> list[str] | None:
|
||||
"""Discover models from a provider's /models endpoint."""
|
||||
import httpx
|
||||
|
||||
Reference in new issue
Block a user