refac
Some checks are pending
Python CI / Ruff Format (3.11) (push) Waiting to run
Python CI / Ruff Format (3.12) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/amd64 runner:ubuntu-latest], map[build_args:USE_SLIM=true free_disk:false name:slim suffix:-slim]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/arm64 runner:ubuntu-24.04-arm], map[build_args: free_disk:false name:main suffix:]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/arm64 runner:ubuntu-24.04-arm], map[build_args:USE_CUDA=true USE_CUDA_VER=cu126 free_disk:true name:cuda126 suffix:-cuda126]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/arm64 runner:ubuntu-24.04-arm], map[build_args:USE_CUDA=true free_disk:true name:cuda suffix:-cuda]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/arm64 runner:ubuntu-24.04-arm], map[build_args:USE_OLLAMA=true free_disk:false name:ollama suffix:-ollama]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/arm64 runner:ubuntu-24.04-arm], map[build_args:USE_SLIM=true free_disk:false name:slim suffix:-slim]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/amd64 runner:ubuntu-latest], map[build_args: free_disk:false name:main suffix:]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/amd64 runner:ubuntu-latest], map[build_args:USE_CUDA=true USE_CUDA_VER=cu126 free_disk:true name:cuda126 suffix:-cuda126]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/amd64 runner:ubuntu-latest], map[build_args:USE_CUDA=true free_disk:true name:cuda suffix:-cuda]) (push) Waiting to run
Create and publish Docker images with specific build args / build (map[arch:linux/amd64 runner:ubuntu-latest], map[build_args:USE_OLLAMA=true free_disk:false name:ollama suffix:-ollama]) (push) Waiting to run
Create and publish Docker images with specific build args / merge (map[name:cuda suffix:-cuda]) (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge (map[name:cuda126 suffix:-cuda126]) (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge (map[name:main suffix:]) (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge (map[name:ollama suffix:-ollama]) (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge (map[name:slim suffix:-slim]) (push) Blocked by required conditions
Create and publish Docker images with specific build args / notify-helm-charts (push) Blocked by required conditions
Create and publish Docker images with specific build args / copy-to-dockerhub (, main) (push) Blocked by required conditions
Create and publish Docker images with specific build args / copy-to-dockerhub (-cuda, cuda) (push) Blocked by required conditions
Create and publish Docker images with specific build args / copy-to-dockerhub (-cuda126, cuda126) (push) Blocked by required conditions
Create and publish Docker images with specific build args / copy-to-dockerhub (-ollama, ollama) (push) Blocked by required conditions
Create and publish Docker images with specific build args / copy-to-dockerhub (-slim, slim) (push) Blocked by required conditions
Frontend Build / Unit Tests (push) Waiting to run
Frontend Build / Format & Build (push) Waiting to run

This commit is contained in:
Timothy Jaeryang Baek 2026-10-26 07:24:36 +09:00
parent 22dd3e2be1
commit 7b303cf496
17 changed files with 3045 additions and 599 deletions

View file

@ -1645,6 +1645,17 @@ async def chat_completion(
error_detail = None
try:
try:
if is_saved_chat_id(metadata.get('chat_id')) and metadata.get('message_id'):
async with Chats.edit_message_output(metadata['chat_id'], metadata['message_id']) as message:
if message is not None:
response_meta = dict(message.get('meta') or {})
# Continuations retain the original start, including approval pauses.
# A historical response without a recorded start remains unknown.
if not metadata.get('assistant_message_id'):
response_meta['response_started_at'] = time.time()
response_meta.pop('response_ended_at', None)
message['meta'] = response_meta
message['done'] = False
if not metadata.get('direct'):
target = (
model_info
@ -1686,6 +1697,13 @@ async def chat_completion(
try:
async def emit_cancel_event():
if is_saved_chat_id(metadata.get('chat_id')) and metadata.get('message_id'):
async with Chats.edit_message_output(metadata['chat_id'], metadata['message_id']) as message:
if message is not None:
response_meta = dict(message.get('meta') or {})
response_meta.setdefault('response_ended_at', time.time())
message['meta'] = response_meta
message['done'] = True
event_emitter = await get_event_emitter(metadata)
if event_emitter:
await event_emitter({'type': 'chat:tasks:cancel'})
@ -1711,6 +1729,7 @@ async def chat_completion(
'parentId': metadata.get('user_message_id'),
'error': {'content': error_detail},
'done': True,
'meta': {'response_ended_at': time.time()},
},
)
except Exception:

View file

@ -0,0 +1,604 @@
"""Read-only session analytics over existing chats and saved messages."""
import math
from open_webui.models.chat_messages import ChatMessage, _token_columns
from open_webui.models.chats import Chat
from open_webui.models.folders import Folder
from open_webui.models.groups import group_user_memberships
from open_webui.models.users import User
from open_webui.utils.session_records import safe_snippet
from sqlalchemy import (
ARRAY,
JSON,
Float,
Integer,
Text,
case,
cast,
distinct,
func,
literal,
or_,
select,
true,
union_all,
)
from sqlalchemy.ext.asyncio import AsyncSession
def json_text(db, column, *path):
if db.get_bind().dialect.name == 'sqlite':
return func.json_extract(column, '$' + ''.join(f'.{key}' for key in path))
return (
func.json_extract_path_text(column, *path)
if path
else column.op('#>>', return_type=Text)(cast(literal('{}'), ARRAY(Text)))
)
def json_type(db, column):
return func.json_type(column) if db.get_bind().dialect.name == 'sqlite' else func.json_typeof(column)
def message_filters(start_date=None, end_date=None):
conditions = []
if start_date is not None:
conditions.append(ChatMessage.created_at >= start_date)
if end_date is not None:
conditions.append(ChatMessage.created_at <= end_date)
return conditions
def chat_filters(db, group_id=None, query='', hide_subagents=False, model_id=None, start_date=None, end_date=None):
conditions = []
if group_id:
members = group_user_memberships([group_id], True)
conditions.append(Chat.user_id.in_(select(members.c.user_id)))
if query.strip():
# Literal search: '%' and '_' in titles are not wildcard operators.
term = '%' + query.strip().replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%'
conditions.append(
or_(
Chat.title.ilike(term, escape='\\'),
User.name.ilike(term, escape='\\'),
Folder.name.ilike(term, escape='\\'),
)
)
if hide_subagents:
conditions.append(func.coalesce(json_text(db, Chat.meta, 'type'), '') != 'subagent')
if model_id:
conditions.append(
select(ChatMessage.id)
.where(
ChatMessage.chat_id == Chat.id,
ChatMessage.model_id == model_id,
*message_filters(start_date, end_date),
)
.exists()
)
return conditions
def session_query(
db, *, start_date=None, end_date=None, group_id=None, query='', hide_subagents=False, model_id=None, chat_id=None
):
input_tokens, output_tokens = _token_columns(db.get_bind().dialect.name)
assistant = ChatMessage.role == 'assistant'
human = (ChatMessage.role == 'user') & (
func.coalesce(cast(json_text(db, ChatMessage.meta, 'internal'), Text), 'false').notin_(['true', '1'])
)
timestamp = case((ChatMessage.created_at > 0, ChatMessage.created_at))
recorded = assistant & (input_tokens.isnot(None) | output_tokens.isnot(None))
error = func.coalesce(cast(ChatMessage.error, Text), 'null').notin_(['null', '""', '{}', 'false'])
filters = message_filters(start_date, end_date)
if chat_id:
filters.append(ChatMessage.chat_id == chat_id)
# No transcript/output columns enter the list query, even when sorting by tokens.
cache_fields = {
'cache_read': func.coalesce(
json_text(db, ChatMessage.usage, 'cache_read_input_tokens'),
json_text(db, ChatMessage.usage, 'input_tokens_details', 'cached_tokens'),
json_text(db, ChatMessage.usage, 'prompt_tokens_details', 'cached_tokens'),
),
'cache_write': func.coalesce(
json_text(db, ChatMessage.usage, 'cache_creation_input_tokens'),
json_text(db, ChatMessage.usage, 'input_tokens_details', 'cache_write_tokens'),
json_text(db, ChatMessage.usage, 'prompt_tokens_details', 'cache_write_tokens'),
),
}
stats = (
select(
ChatMessage.chat_id.label('chat_id'),
*[func.sum(case((assistant, cast(field, Integer)))).label(key) for key, field in cache_fields.items()],
*[
func.sum(case((assistant & field.isnot(None), 1), else_=0)).label(key + '_responses')
for key, field in cache_fields.items()
],
func.count().label('messages'),
func.sum(case((assistant, 1), else_=0)).label('responses'),
func.sum(case((human, 1), else_=0)).label('prompts'),
func.sum(case((recorded, 1), else_=0)).label('recorded_responses'),
func.sum(
case(
(
assistant
& input_tokens.isnot(None)
& output_tokens.isnot(None)
& func.coalesce(ChatMessage.usage['incomplete'].as_boolean(), False).is_(False),
1,
),
else_=0,
)
).label('complete_responses'),
func.sum(
case((assistant, func.coalesce(input_tokens, 0) + func.coalesce(output_tokens, 0)), else_=0)
).label('tokens'),
func.sum(case((assistant & error, 1), else_=0)).label('errors'),
func.min(timestamp).label('started_at'),
func.max(timestamp).label('last_active'),
case((func.count(timestamp) == func.count(), func.max(timestamp) - func.min(timestamp))).label(
'span_seconds'
),
func.min(case((assistant, ChatMessage.model_id))).label('model_id'),
func.count(distinct(case((assistant, ChatMessage.model_id)))).label('model_count'),
)
.where(*filters)
.group_by(ChatMessage.chat_id)
.subquery()
)
statement = (
select(
Chat.id,
func.substr(Chat.title, 1, 200).label('title'),
User.name.label('user_name'),
Folder.name.label('folder_name'),
json_text(db, Chat.meta, 'type').label('kind'),
json_text(db, Chat.meta, 'forked_from').label('forked_from'),
*[column for column in stats.c if column.name != 'chat_id'],
)
.join(stats, stats.c.chat_id == Chat.id)
.outerjoin(User, User.id == Chat.user_id)
.outerjoin(Folder, Folder.id == Chat.folder_id)
)
return statement.where(*chat_filters(db, group_id, query, hide_subagents, model_id, start_date, end_date)), stats
def page_result(rows, limit):
items = [dict(row) for row in rows[:limit]]
for item in items:
if 'title' in item:
item['title'] = safe_snippet(item['title']) or ''
return {'items': items, 'has_more': len(rows) > limit}
TOKEN_RANGES = [(0, 1), (1, 1000), (1000, 10000), (10000, 100000), (100000, 1000000), (1000000, None)]
async def list_sessions(
db: AsyncSession,
*,
skip=0,
limit=25,
order_by='recent',
direction='desc',
include_summary=False,
token_min=None,
token_max=None,
**filters,
):
statement, stats = session_query(db, **filters)
order = {
'title': func.lower(Chat.title),
'user': func.lower(User.name),
'recent': stats.c.last_active,
'tokens': case((stats.c.recorded_responses > 0, stats.c.tokens)),
'responses': stats.c.responses,
'errors': stats.c.errors,
'duration': stats.c.span_seconds,
}[order_by]
order = order.asc() if direction == 'asc' else order.desc()
# The overview stays on the full search scope while its bars filter the table.
page_statement = statement
if token_min is not None or token_max is not None:
page_statement = page_statement.where(stats.c.recorded_responses > 0)
if token_min is not None:
page_statement = page_statement.where(stats.c.tokens >= token_min)
if token_max is not None:
page_statement = page_statement.where(stats.c.tokens < token_max)
rows = (
(await db.execute(page_statement.order_by(order.nulls_last(), Chat.id).offset(skip).limit(limit + 1)))
.mappings()
.all()
)
result = page_result(rows, limit)
if include_summary:
eligible = statement.subquery()
totals = (
(
await db.execute(
select(
func.count().label('sessions'),
func.coalesce(func.max(eligible.c.tokens), 0).label('max_tokens'),
func.count(case((eligible.c.recorded_responses == 0, 1))).label('unrecorded_sessions'),
*[
func.count(
case(
(
(eligible.c.recorded_responses > 0)
& (eligible.c.tokens >= low)
& ((eligible.c.tokens < high) if high is not None else true()),
1,
)
)
).label(f'token_range_{index}')
for index, (low, high) in enumerate(TOKEN_RANGES)
],
*[
func.coalesce(func.sum(eligible.c[key]), 0).label(key)
for key in (
'tokens',
'prompts',
'responses',
'errors',
'recorded_responses',
'complete_responses',
)
],
func.min(eligible.c.started_at).label('start'),
func.max(eligible.c.last_active).label('end'),
)
)
)
.mappings()
.one()
)
result['overview'] = dict(totals)
result['overview']['token_distribution'] = [
result['overview'].pop(f'token_range_{index}') for index in range(len(TOKEN_RANGES))
]
return result
async def session_messages(
db: AsyncSession, chat_id: str, *, start_date=None, end_date=None, group_id=None, skip=0, limit=25
):
statement, _ = session_query(db, chat_id=chat_id, start_date=start_date, end_date=end_date, group_id=group_id)
session = (await db.execute(statement)).mappings().first()
if session is None:
return None
input_tokens, output_tokens = _token_columns(db.get_bind().dialect.name)
content = case(
(json_type(db, ChatMessage.content).in_(['text', 'string']), json_text(db, ChatMessage.content)), else_=None
)
output_count = func.json_array_length(ChatMessage.output)
output_count = case((json_type(db, ChatMessage.output) == 'array', output_count), else_=0)
rows = (
(
await db.execute(
select(
ChatMessage.id,
ChatMessage.role,
ChatMessage.model_id,
ChatMessage.created_at,
ChatMessage.parent_id,
ChatMessage.done,
func.substr(content, 1, 320).label('preview'),
(func.length(content) > 320).label('preview_truncated'),
func.substr(json_text(db, ChatMessage.error), 1, 500).label('error'),
case(
(
input_tokens.isnot(None) | output_tokens.isnot(None),
func.coalesce(input_tokens, 0) + func.coalesce(output_tokens, 0),
)
).label('tokens'),
output_count.label('output_count'),
)
.where(ChatMessage.chat_id == chat_id, *message_filters(start_date, end_date))
.order_by(ChatMessage.created_at, ChatMessage.id)
.offset(skip)
.limit(limit + 1)
)
)
.mappings()
.all()
)
session = {**dict(session), 'title': safe_snippet(session['title']) or ''}
result = {'session': session, **page_result(rows, limit)}
for item in result['items']:
item['preview'] = safe_snippet(item['preview'])
item['error'] = safe_snippet(item['error'])
return result
def finite_number(value):
if isinstance(value, bool):
return None
try:
result = float(value)
return result if math.isfinite(result) and result >= 0 else None
except (ValueError, TypeError):
return None
def output_items(db):
empty = literal('[]') if db.get_bind().dialect.name == 'sqlite' else cast(literal('[]'), JSON)
output = case((json_type(db, ChatMessage.output) == 'array', ChatMessage.output), else_=empty)
if db.get_bind().dialect.name == 'sqlite':
items = func.json_each(output).table_valued('key', 'value', 'type', joins_implicitly=True)
index = cast(items.c.key, Integer)
value = case((items.c.type == 'object', items.c.value), else_=literal('{}'))
else:
items = func.json_array_elements(output).table_valued('value', with_ordinality='ordinality').render_derived()
index = items.c.ordinality - 1
value = items.c.value
def field(key):
return json_text(db, value, key)
return items, index, field
async def message_events(
db: AsyncSession, chat_id: str, message_id: str, *, group_id=None, start_date=None, end_date=None, skip=0, limit=20
):
# Guard the detail independently; IDs must not bypass the active group/date scope.
allowed = (
select(ChatMessage.id)
.join(Chat, Chat.id == ChatMessage.chat_id)
.where(
Chat.id == chat_id,
ChatMessage.id == message_id,
*message_filters(start_date, end_date),
*chat_filters(db, group_id=group_id),
)
)
if (await db.execute(allowed)).scalar_one_or_none() is None:
return None
items, index, field = output_items(db)
details = func.coalesce(
field('arguments'),
field('output'),
field('content'),
field('summary'),
field('text'),
field('code'),
field('error'),
)
statement = (
select(
index.label('index'),
func.substr(cast(field('type'), Text), 1, 80).label('type'),
func.substr(cast(field('name'), Text), 1, 160).label('name'),
func.substr(cast(field('call_id'), Text), 1, 200).label('call_id'),
func.substr(cast(field('status'), Text), 1, 64).label('status'),
func.substr(cast(field('error_type'), Text), 1, 80).label('error_type'),
func.substr(cast(field('started_at'), Text), 1, 64).label('started_at'),
func.substr(cast(field('ended_at'), Text), 1, 64).label('ended_at'),
func.substr(cast(field('duration'), Text), 1, 64).label('duration_seconds'),
func.substr(cast(details, Text), 1, 2000).label('details'),
(func.length(cast(details, Text)) > 2000).label('truncated'),
)
.select_from(ChatMessage)
.join(items, true())
.where(ChatMessage.id == message_id, ChatMessage.chat_id == chat_id)
)
rows = (await db.execute(statement.order_by(index).offset(skip).limit(limit + 1))).mappings().all()
result = page_result(rows, limit)
normalize_durations(result['items'])
for item in result['items']:
item['details'] = safe_snippet(item['details'])
item['truncated'] = True
return result
def normalize_durations(items):
for item in items:
for key in ('started_at', 'ended_at', 'duration_seconds'):
item[key] = finite_number(item[key])
if (
item['duration_seconds'] is None
and item['started_at'] is not None
and item['ended_at'] is not None
and item['ended_at'] >= item['started_at']
):
item['duration_seconds'] = item['ended_at'] - item['started_at']
async def session_trace(
db: AsyncSession,
chat_id: str,
*,
start_date=None,
end_date=None,
group_id=None,
skip=0,
limit=50,
view='all',
include_chart=False,
):
statement, _ = session_query(db, chat_id=chat_id, start_date=start_date, end_date=end_date, group_id=group_id)
session = (await db.execute(statement)).mappings().first()
if session is None:
return None
items, index, field = output_items(db)
filters = [ChatMessage.chat_id == chat_id, *message_filters(start_date, end_date)]
error = func.coalesce(cast(ChatMessage.error, Text), 'null').notin_(['null', '""', '{}', 'false'])
# Metadata only. Tool arguments/results are fetched separately when an item is selected.
messages = select(
ChatMessage.id.label('message_id'),
literal(-1).label('index'),
literal(None, Integer).label('result_index'),
ChatMessage.created_at,
ChatMessage.model_id,
literal('response').label('type'),
ChatMessage.role.label('name'),
literal(None, Text).label('call_id'),
case((error, 'failed'), (ChatMessage.done.is_(True), 'completed'), else_='in_progress').label('status'),
literal(None, Text).label('error_type'),
json_text(db, ChatMessage.meta, 'response_started_at').label('started_at'),
json_text(db, ChatMessage.meta, 'response_ended_at').label('ended_at'),
literal(None, Text).label('duration_seconds'),
).where(*filters, ChatMessage.role == 'assistant')
outputs = (
select(
ChatMessage.id.label('message_id'),
index.label('index'),
ChatMessage.created_at,
ChatMessage.model_id,
*[
func.substr(cast(field(key), Text), 1, size).label(key)
for key, size in [
('type', 80),
('name', 160),
('call_id', 200),
('status', 64),
('error_type', 80),
('started_at', 64),
('ended_at', 64),
]
],
func.substr(cast(field('duration'), Text), 1, 64).label('duration_seconds'),
)
.select_from(ChatMessage)
.join(items, true())
.where(*filters)
)
# Pair by saved message/call identity before pagination, never by adjacent rows.
saved = outputs.cte('saved_outputs')
pairs = (
select(
saved.c.message_id,
saved.c.call_id,
func.max(case((saved.c.type == 'function_call', saved.c.index))).label('call_index'),
func.max(case((saved.c.type == 'function_call_output', saved.c.index))).label('result_index'),
)
.where(saved.c.call_id.isnot(None), saved.c.call_id != '')
.group_by(saved.c.message_id, saved.c.call_id)
.subquery()
)
returned = saved.alias('saved_result')
is_call = saved.c.type == 'function_call'
outputs = (
select(
saved.c.message_id,
saved.c.index,
case((is_call, pairs.c.result_index)).label('result_index'),
*[
case((is_call, func.coalesce(returned.c[key], saved.c[key])), else_=saved.c[key]).label(key)
if key in {'status', 'error_type'}
else saved.c[key]
for key in saved.c.keys()
if key not in {'message_id', 'index'}
],
)
.select_from(saved)
.outerjoin(pairs, (pairs.c.message_id == saved.c.message_id) & (pairs.c.call_id == saved.c.call_id))
.outerjoin(returned, (returned.c.message_id == saved.c.message_id) & (returned.c.index == pairs.c.result_index))
.where(saved.c.type.isnot(None), or_(saved.c.type != 'function_call_output', pairs.c.call_index.is_(None)))
)
trace = union_all(messages, outputs).subquery()
query = select(trace)
if view == 'tools':
query = query.where(trace.c.type.in_(['function_call', 'function_call_output', 'open_webui:code_interpreter']))
elif view == 'errors':
query = query.where(trace.c.status == 'failed')
rows = (
(
await db.execute(
query.order_by(trace.c.created_at, trace.c.message_id, trace.c.index).offset(skip).limit(limit + 1)
)
)
.mappings()
.all()
)
session = {**dict(session), 'title': safe_snippet(session['title']) or ''}
result = {'session': session, **page_result(rows, limit)}
if include_chart:
result['chart'] = await trace_chart(db, trace, session['responses'])
normalize_durations(result['items'])
return result
async def trace_chart(db, trace, responses):
# Keep the full session's order and page offsets, but return at most 128 bars.
ordered = select(
trace,
(func.row_number().over(order_by=[trace.c.created_at, trace.c.message_id, trace.c.index]) - 1).label('offset'),
).cte('ordered_trace')
input_tokens, output_tokens = _token_columns(db.get_bind().dialect.name)
usage = (
select(
ordered.c.offset,
ordered.c.model_id,
ordered.c.status,
input_tokens.label('input_tokens'),
output_tokens.label('output_tokens'),
func.coalesce(ChatMessage.usage['incomplete'].as_boolean(), False).label('incomplete'),
func.row_number().over(order_by=ordered.c.offset).label('ordinal'),
)
.join(ChatMessage, ChatMessage.id == ordered.c.message_id)
.where(ordered.c.index == -1, ChatMessage.role == 'assistant')
.subquery()
)
group_size = max(1, math.ceil(responses / 128))
position = usage.c.ordinal - 1
bucket = cast((position - position % group_size) / group_size, Integer)
recorded = usage.c.input_tokens.isnot(None) | usage.c.output_tokens.isnot(None)
complete = usage.c.input_tokens.isnot(None) & usage.c.output_tokens.isnot(None) & usage.c.incomplete.is_(False)
bars = (
(
await db.execute(
select(
func.min(usage.c.ordinal).label('first'),
func.max(usage.c.ordinal).label('last'),
func.min(usage.c.offset).label('offset'),
func.sum(usage.c.input_tokens).label('input_tokens'),
func.sum(usage.c.output_tokens).label('output_tokens'),
func.sum(case((recorded, 1), else_=0)).label('recorded'),
func.sum(case((complete, 1), else_=0)).label('complete'),
func.sum(case((usage.c.status == 'failed', 1), else_=0)).label('errors'),
case(
(
func.count(usage.c.model_id) == func.count(),
case((func.count(distinct(usage.c.model_id)) == 1, func.min(usage.c.model_id))),
)
).label('model_id'),
)
.group_by(bucket)
.order_by(bucket)
)
)
.mappings()
.all()
)
# Validate numeric text before casting, including on PostgreSQL. Malformed saved values are unknown.
def number(column):
if db.get_bind().dialect.name == 'sqlite':
valid_json = case((func.json_valid(column), column), else_='null')
valid = func.json_type(valid_json).in_(['integer', 'real'])
else:
valid = column.op('~')(r'^[0-9]+([.][0-9]+)?([eE][+-]?[0-9]{1,2})?$')
value = cast(case((valid & (func.length(column) <= 100), column)), Float)
return case(((value >= 0) & (value < 1e100), value))
start, end, duration = [number(ordered.c[key]) for key in ('started_at', 'ended_at', 'duration_seconds')]
timed = start.isnot(None) & end.isnot(None) & (end >= start)
timing = (
(
await db.execute(
select(
func.min(case((timed, start))).label('start'),
func.max(case((timed, end))).label('end'),
func.max(func.coalesce(duration, case((timed, end - start)))).label('max_duration'),
func.sum(case((timed, 1), else_=0)).label('timed_operations'),
func.sum(case((duration.isnot(None) | timed, 1), else_=0)).label('duration_operations'),
)
)
)
.mappings()
.one()
)
return {'usage': [dict(bar) for bar in bars], **dict(timing)}

View file

@ -1,31 +1,31 @@
from contextlib import nullcontext
import os
import time
import uuid
from collections import Counter
from contextlib import nullcontext
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Optional
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from sqlalchemy import select, delete, func, cast, Integer, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from open_webui.internal.db import Base, get_async_db_context
from open_webui.utils.response import merge_usage, normalize_usage
from open_webui.utils.response import normalize_usage
from open_webui.utils.session_records import normalize_tool_output, recorded_timestamp
from pydantic import BaseModel, ConfigDict
from sqlalchemy import (
JSON,
BigInteger,
Boolean,
Column,
ForeignKey,
Float,
ForeignKey,
Index,
Integer,
Text,
cast,
case,
cast,
delete,
distinct,
func,
literal,
select,
@ -255,7 +255,7 @@ class ChatMessageTable:
if 'content' in data:
message.content = data.get('content')
if 'output' in data:
message.output = data.get('output')
message.output = normalize_tool_output(data.get('output'))
if 'model_id' in data or 'model' in data:
message.model_id = data.get('model_id') or data.get('model')
if 'files' in data:
@ -277,8 +277,8 @@ class ChatMessageTable:
usage = get_usage(data)
if usage:
existing_usage = normalize_usage(message.usage)
message.usage = existing_usage if usage == existing_usage else merge_usage(existing_usage, usage)
# The caller saves a cumulative message snapshot; accumulation belongs to the model-call loop.
message.usage = usage
message.updated_at = now
@staticmethod
@ -290,7 +290,7 @@ class ChatMessageTable:
role=data.get('role', 'user'),
parent_id=data.get('parent_id') or data.get('parentId'),
content=data.get('content'),
output=data.get('output'),
output=normalize_tool_output(data.get('output')),
model_id=data.get('model_id') or data.get('model'),
files=data.get('files'),
sources=data.get('sources'),
@ -301,7 +301,7 @@ class ChatMessageTable:
error=data.get('error'),
usage=get_usage(data),
context_summary=data.get('context_summary') or data.get('contextSummary'),
created_at=data.get('timestamp') or now,
created_at=(recorded_timestamp(data.get('timestamp')) or 0) if 'timestamp' in data else now,
updated_at=now,
)
@ -336,15 +336,21 @@ class ChatMessageTable:
self, chat_id: str, user_id: str, messages: dict[str, dict], db: AsyncSession | None = None
) -> None:
"""Backfill missing rows without overwriting newer message data."""
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
if not messages:
return
async with get_async_db_context(db) as db:
insert = sqlite_insert if db.bind.dialect.name == 'sqlite' else pg_insert
rows = [
self._build_message(f'{chat_id}-{mid}', chat_id, data.get('user_id') or user_id, data, int(time.time()))
self._build_message(
f'{chat_id}-{mid}',
chat_id,
data.get('user_id') or user_id,
{**data, 'timestamp': data.get('timestamp')},
int(time.time()),
)
for mid, data in messages.items()
]
await db.execute(
@ -805,7 +811,7 @@ class ChatMessageTable:
day_stmt = day_stmt.filter(ChatMessage.created_at >= start_date)
if end_date:
day_stmt = day_stmt.filter(ChatMessage.created_at <= end_date)
day_result = await db.execute(day_stmt)
day_result = await db.execute(day_stmt.where(ChatMessage.created_at > 0))
active_days = {_date_key(row.created_at, tz) for row in day_result.all()}
input_total = int(token_result.input_tokens or 0)
@ -831,7 +837,7 @@ class ChatMessageTable:
result = await db.execute(
select(func.min(ChatMessage.created_at)).filter(
ChatMessage.user_id == user_id,
ChatMessage.created_at.isnot(None),
ChatMessage.created_at > 0,
)
)
value = result.scalar()
@ -865,7 +871,7 @@ class ChatMessageTable:
ChatMessage.created_at <= end_date,
)
result = await db.execute(stmt)
result = await db.execute(stmt.where(ChatMessage.created_at > 0))
daily: dict[str, dict] = {}
for row in result.all():
date = _date_key(row.created_at, tz)
@ -1082,7 +1088,7 @@ class ChatMessageTable:
if day is not None:
stmt = stmt.group_by(day, ChatMessage.model_id)
result = await db.execute(stmt)
result = await db.execute(stmt.where(ChatMessage.created_at > 0))
counts: dict[str, dict[str, int]] = {}
for timestamp, model_id, value in result.all():
date_str = timestamp if day is not None else bucket_start(timestamp).strftime(date_format)

View file

@ -791,7 +791,7 @@ class ChatTable:
user_id=message.get('user_id')
or (message['user'].get('id') if isinstance(message.get('user'), dict) else None)
or user_id,
data=message,
data={**message, 'timestamp': message.get('timestamp')},
)
except Exception as e:
log.warning(
@ -1087,18 +1087,22 @@ class ChatTable:
if message_id in messages:
# Voice updates must not replace approval-resume metadata, and approval
# pauses must retain the generated speech already attached to this turn.
# pauses must retain speech and response timing already attached to this turn.
existing_meta = messages[message_id].get('meta')
existing_meta = existing_meta if isinstance(existing_meta, dict) else {}
incoming_meta = message.get('meta')
if isinstance(incoming_meta, dict):
if set(incoming_meta) <= {'voice', 'task_id'}:
if set(incoming_meta) <= {'voice', 'task_id', 'response_started_at', 'response_ended_at'}:
message = {**message, 'meta': {**existing_meta, **incoming_meta}}
else:
message = {
**message,
'meta': {
**{key: existing_meta[key] for key in ('voice', 'task_id') if key in existing_meta},
**{
key: existing_meta[key]
for key in ('voice', 'task_id', 'response_started_at', 'response_ended_at')
if key in existing_meta
},
**incoming_meta,
},
}

View file

@ -438,3 +438,139 @@ async def get_model_overview(
tags = [TagEntry(tag=tag, count=count) for tag, count in sorted(tag_counts.items(), key=lambda x: -x[1])[:10]]
return ModelOverviewResponse(history=history, tags=tags)
####################
# Session Explorer
####################
def require_session_access(user=Depends(get_admin_user)):
from open_webui.config import ENABLE_ADMIN_CHAT_ACCESS
if not ENABLE_ADMIN_CHAT_ACCESS:
raise HTTPException(403, detail='Admin chat access is disabled')
return user
def validate_session_range(start_date, end_date):
if start_date is not None and end_date is not None and start_date > end_date:
raise HTTPException(400, detail='Start date must be before end date')
@router.get('/sessions')
async def get_sessions(
start_date: int | None = Query(None, ge=0),
end_date: int | None = Query(None, ge=0),
group_id: str | None = None,
query: str = Query('', max_length=200),
model_id: str | None = None,
hide_subagents: bool = False,
order_by: Literal['title', 'user', 'recent', 'tokens', 'responses', 'errors', 'duration'] = 'recent',
direction: Literal['asc', 'desc'] = 'desc',
include_summary: bool = False,
token_min: int | None = Query(None, ge=0),
token_max: int | None = Query(None, ge=1),
skip: int = Query(0, ge=0),
limit: int = Query(25, ge=1, le=50),
user=Depends(require_session_access),
db: AsyncSession = Depends(get_async_session),
):
from open_webui.models.analytics_sessions import list_sessions
validate_session_range(start_date, end_date)
if token_min is not None and token_max is not None and token_min >= token_max:
raise HTTPException(400, detail='Minimum tokens must be below maximum tokens')
return await list_sessions(
db,
start_date=start_date,
end_date=end_date,
group_id=group_id,
query=query,
model_id=model_id,
hide_subagents=hide_subagents,
order_by=order_by,
direction=direction,
include_summary=include_summary,
token_min=token_min,
token_max=token_max,
skip=skip,
limit=limit,
)
@router.get('/sessions/{chat_id}')
async def get_session_messages(
chat_id: str,
start_date: int | None = Query(None, ge=0),
end_date: int | None = Query(None, ge=0),
group_id: str | None = None,
skip: int = Query(0, ge=0),
limit: int = Query(25, ge=1, le=50),
user=Depends(require_session_access),
db: AsyncSession = Depends(get_async_session),
):
from open_webui.models.analytics_sessions import session_messages
validate_session_range(start_date, end_date)
result = await session_messages(
db, chat_id, start_date=start_date, end_date=end_date, group_id=group_id, skip=skip, limit=limit
)
if result is None:
raise HTTPException(404, detail='Session not found in this range')
return result
@router.get('/sessions/{chat_id}/messages/{message_id}/events')
async def get_session_events(
chat_id: str,
message_id: str,
start_date: int | None = Query(None, ge=0),
end_date: int | None = Query(None, ge=0),
group_id: str | None = None,
skip: int = Query(0, ge=0),
limit: int = Query(20, ge=1, le=50),
user=Depends(require_session_access),
db: AsyncSession = Depends(get_async_session),
):
from open_webui.models.analytics_sessions import message_events
validate_session_range(start_date, end_date)
result = await message_events(
db, chat_id, message_id, start_date=start_date, end_date=end_date, group_id=group_id, skip=skip, limit=limit
)
if result is None:
raise HTTPException(404, detail='Message not found in this session')
return result
@router.get('/sessions/{chat_id}/trace')
async def get_session_trace(
chat_id: str,
start_date: int | None = Query(None, ge=0),
end_date: int | None = Query(None, ge=0),
group_id: str | None = None,
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=50),
view: Literal['all', 'tools', 'errors'] = 'all',
include_chart: bool = False,
user=Depends(require_session_access),
db: AsyncSession = Depends(get_async_session),
):
from open_webui.models.analytics_sessions import session_trace
validate_session_range(start_date, end_date)
result = await session_trace(
db,
chat_id,
start_date=start_date,
end_date=end_date,
group_id=group_id,
skip=skip,
limit=limit,
view=view,
include_chart=include_chart,
)
if result is None:
raise HTTPException(404, detail='Session not found in this range')
return result

View file

@ -133,7 +133,7 @@ def log_model_usage(request: Request, user: UserModel, model_id: str, usage: Opt
source_ip=request.client.host if request.client else None,
user_agent=request.headers.get('user-agent'),
model_id=model_id,
usage={key: usage[key] for key in ('input_tokens', 'output_tokens', 'total_tokens')},
usage={key: usage[key] for key in ('input_tokens', 'output_tokens', 'total_tokens') if key in usage},
),
extra={'event': 'model_usage', 'request_id': request_id},
)

View file

@ -135,6 +135,7 @@ from open_webui.utils.response import (
handle_responses_streaming_event,
merge_usage,
normalize_usage,
update_usage_snapshot,
)
from open_webui.utils.sanitize import sanitize_code
from open_webui.utils.skills import (
@ -3069,11 +3070,9 @@ async def build_chat_response_context(request, form_data, user, model, metadata,
async def execute_tool_call(form_data, metadata, event_caller, tool_call):
error = resolve_tool_call(tool_call, metadata.get('tools', {}))
if error:
return {}, error, None, None, False
name = tool_call.get('function', {}).get('name', '')
tool_args = tool_call.get('function', {}).get('arguments', '{}')
"""Execute the saved function_call item, already resolved before approval staging."""
name = tool_call.get('name', '')
tool_args = tool_call.get('arguments', '{}')
params = {}
if tool_args and tool_args.strip():
try:
@ -3083,7 +3082,7 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call):
params = ast.literal_eval(tool_args)
except Exception as e:
log.debug(e)
return {}, None, None, None, False
return {}, 'Error: Tool arguments are not valid JSON.', None, None, False
if not isinstance(params, dict):
return (
{},
@ -3092,7 +3091,7 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call):
None,
False,
)
tool_call.setdefault('function', {})['arguments'] = JSONCodec.dumps(params)
tool_call['arguments'] = JSONCodec.dumps(params)
tool = metadata.get('tools', {}).get(name)
if not tool:
@ -3114,7 +3113,7 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call):
or await event_caller(
{
'type': 'confirmation',
'data': {'tool_call': {'id': tool_call.get('id'), 'name': name, 'arguments': params}},
'data': {'tool_call': {'id': tool_call.get('call_id'), 'name': name, 'arguments': params}},
}
)
is not True # Disconnection and timeout replies are error objects, not approval.
@ -3122,31 +3121,37 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call):
):
return params, 'Error: tool call was not approved.', tool, tool_type, direct_tool
if direct_tool:
if not event_caller:
result = 'Error: Browser session is not connected for this direct tool.'
tool_call['started_at'] = time.time()
started = time.perf_counter()
try:
if direct_tool:
if not event_caller:
result = 'Error: Browser session is not connected for this direct tool.'
else:
result = await event_caller(
{
'type': 'execute:tool',
'data': {
'id': str(uuid4()),
'name': name,
'params': params,
'server': tool.get('server', {}),
'session_id': metadata.get('session_id'),
},
}
)
else:
result = await event_caller(
{
'type': 'execute:tool',
'data': {
'id': str(uuid4()),
'name': name,
'params': params,
'server': tool.get('server', {}),
'session_id': metadata.get('session_id'),
},
}
function = await get_updated_tool_function(
function=tool['callable'],
extra_params={
'__messages__': form_data.get('messages', []),
'__files__': metadata.get('files') or [],
},
)
else:
function = await get_updated_tool_function(
function=tool['callable'],
extra_params={
'__messages__': form_data.get('messages', []),
'__files__': metadata.get('files') or [],
},
)
result = await function(**params)
result = await function(**params)
finally:
tool_call['ended_at'] = time.time()
tool_call['duration'] = time.perf_counter() - started
except Exception as e:
result = {'error': str(e)}
return params, result, tool, tool_type, direct_tool
@ -3229,17 +3234,9 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message)
saved['done'] = False
item = copy.deepcopy(item)
tool_call = {
'id': item.get('call_id', ''),
'type': 'function',
'function': {
'name': item.get('name', ''),
'arguments': item.get('arguments', '{}'),
},
}
try:
params, result, tool, tool_type, direct_tool = await execute_tool_call(
form_data, metadata, event_caller, tool_call
form_data, metadata, event_caller, item
)
files, embeds = [], []
if result is None and tool is None:
@ -3264,7 +3261,6 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message)
):
await event_emitter({'type': 'source', 'data': source})
content = tool_result_content(result)
item['arguments'] = tool_call.get('function', {}).get('arguments', '{}')
output_parts = [{'type': 'input_text', 'text': content}]
item['status'] = 'failed' if _is_tool_result_error(content) else 'completed'
display_files = []
@ -3280,7 +3276,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message)
result_item = {
'type': 'function_call_output',
'id': output_id('fco'),
'call_id': tool_call['id'],
'call_id': item['call_id'],
'output': output_parts,
'status': item['status'],
**({'files': display_files} if display_files else {}),
@ -3297,7 +3293,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message)
{
'type': 'function_call_output',
'id': output_id('fco'),
'call_id': tool_call['id'],
'call_id': item['call_id'],
'status': 'incomplete',
'output': [
{
@ -3450,13 +3446,13 @@ def update_assistant_message_from_stream(assistant_message, raw) -> bool:
if output:
assistant_message['output'] = output
if meta and meta.get('usage'):
assistant_message['usage'] = merge_usage(assistant_message.get('usage'), meta['usage'])
assistant_message['usage'] = update_usage_snapshot(assistant_message.get('usage'), meta['usage'])
continue
raw_usage = data.get('usage', {}) or {}
raw_usage.update(data.get('timings', {}))
if raw_usage:
assistant_message['usage'] = merge_usage(assistant_message.get('usage'), raw_usage)
assistant_message['usage'] = update_usage_snapshot(assistant_message.get('usage'), raw_usage)
for choice in data.get('choices', []):
if choice.get('finish_reason'):
@ -3948,6 +3944,7 @@ async def non_streaming_chat_response_handler(response, ctx):
{
'error': {'content': error},
'done': True,
'meta': {'response_ended_at': time.time()},
},
)
if isinstance(error, str) or isinstance(error, dict):
@ -4067,6 +4064,8 @@ async def non_streaming_chat_response_handler(response, ctx):
# Save message in the database
usage = normalize_usage(response_data.get('usage', {}) or {})
if continuing:
usage = merge_usage((ctx.get('assistant_message') or {}).get('usage'), usage or {'incomplete': True})
finish_reason = choices[0].get('finish_reason') if choices else None
if save_to_chat:
@ -4075,6 +4074,7 @@ async def non_streaming_chat_response_handler(response, ctx):
metadata['message_id'],
{
'done': True,
'meta': {'response_ended_at': time.time()},
'role': 'assistant',
'output': response_output,
**({'usage': usage} if usage else {}),
@ -4512,7 +4512,7 @@ async def streaming_chat_response_handler(response, ctx):
prior_output, output = output, []
content_parts = []
usage = None
usage = normalize_usage((message or {}).get('usage') or {}) if existing_output else None
finish_reason = None
last_response_id = None
@ -4655,6 +4655,7 @@ async def streaming_chat_response_handler(response, ctx):
nonlocal stream_size
response_tool_calls = []
prior_usage = usage
current_usage = {}
form_data['model'] = current_form_data['model']
@ -4881,8 +4882,8 @@ async def streaming_chat_response_handler(response, ctx):
# Normalize and capture usage for DB persistence
if response_metadata.get('usage'):
current_usage = response_metadata['usage']
usage = merge_usage(usage, response_metadata['usage'])
current_usage = update_usage_snapshot(current_usage, response_metadata['usage'])
usage = merge_usage(prior_usage, current_usage)
response_metadata['usage'] = usage
if response_metadata.get('error'):
@ -4924,8 +4925,8 @@ async def streaming_chat_response_handler(response, ctx):
raw_usage = data.get('usage', {}) or {}
raw_usage.update(data.get('timings', {})) # llama.cpp
if raw_usage:
current_usage = raw_usage
usage = merge_usage(usage, raw_usage)
current_usage = update_usage_snapshot(current_usage, raw_usage)
usage = merge_usage(prior_usage, current_usage)
await event_emitter(
{
'type': 'chat:completion',
@ -5567,6 +5568,8 @@ async def streaming_chat_response_handler(response, ctx):
tool_calls.append(_split_tool_calls(responses_api_tool_calls))
await save_current_response_stream()
if not current_usage:
usage = {**(usage or {}), 'incomplete': True}
return normalize_usage(current_usage)
output_start = len(prior_output)
@ -5728,20 +5731,18 @@ async def streaming_chat_response_handler(response, ctx):
results = []
delegate_calls = [
tool_call
for tool_call in response_tool_calls
if tool_call.get('function', {}).get('name') == 'delegate_task'
]
# Provider calls have been resolved and staged; execute their saved items directly.
response_tool_calls = [output_by_call_id[call['id']] for call in response_tool_calls]
delegate_calls = [call for call in response_tool_calls if call.get('name') == 'delegate_task']
tool_results = {}
for tool_call in response_tool_calls:
if tool_call.get('function', {}).get('name') != 'delegate_task':
tool_results[id(tool_call)] = await execute_tool_call(
if tool_call.get('name') != 'delegate_task':
tool_results[tool_call['call_id']] = await execute_tool_call(
form_data, metadata, event_caller, tool_call
)
tool_results.update(
zip(
[id(tool_call) for tool_call in delegate_calls],
[tool_call['call_id'] for tool_call in delegate_calls],
await asyncio.gather(
*(
execute_tool_call(form_data, metadata, event_caller, tool_call)
@ -5752,9 +5753,9 @@ async def streaming_chat_response_handler(response, ctx):
)
for tool_call in response_tool_calls:
tool_call_id = tool_call.get('id', '')
tool_function_name = tool_call.get('function', {}).get('name', '')
tool_function_params, tool_result, tool, tool_type, direct_tool = tool_results[id(tool_call)]
tool_call_id = tool_call['call_id']
tool_function_name = tool_call.get('name', '')
tool_function_params, tool_result, tool, tool_type, direct_tool = tool_results[tool_call['call_id']]
if tool_result is None:
results.append(
{
@ -5848,14 +5849,8 @@ async def streaming_chat_response_handler(response, ctx):
}
)
# Update function_call statuses and parsed/sanitized arguments.
for tc in response_tool_calls:
call_id = tc.get('id', '')
for item in output:
if item.get('type') == 'function_call' and item.get('call_id') == call_id:
item['status'] = result_status_by_call_id.get(call_id, 'completed')
item['arguments'] = tc.get('function', {}).get('arguments', '{}')
break
for item in response_tool_calls:
item['status'] = result_status_by_call_id.get(item['call_id'], 'completed')
# Emit citation sources to the frontend for display
if citations_enabled:
@ -6324,6 +6319,7 @@ async def streaming_chat_response_handler(response, ctx):
metadata['message_id'],
{
'done': True,
'meta': {'response_ended_at': time.time()},
'output': current_output,
**({'usage': usage} if usage else {}),
},

View file

@ -8,42 +8,42 @@ from open_webui.utils.misc import (
)
# An honest ledger is worth more than a flattering one.
# Let every cost here be counted true.
def normalize_usage(usage: dict) -> dict:
"""
Normalize usage statistics to standard format.
Handles OpenAI, Ollama, and llama.cpp formats.
def usage_counter(value):
if value is None or isinstance(value, bool):
return None
try:
value = int(value)
return value if value >= 0 else None
except (ValueError, TypeError, OverflowError):
return None
Adds standardized token fields to the original data:
- input_tokens: Number of tokens in the prompt
- output_tokens: Number of tokens generated
- total_tokens: Sum of input and output tokens
"""
def normalize_usage(usage: dict) -> dict:
"""Keep measured zero distinct from missing usage across provider formats."""
if not usage:
return {}
# Map various field names to standard names
input_tokens = usage.get('input_tokens') or usage.get('prompt_tokens') or usage.get('prompt_eval_count')
if input_tokens is None:
input_tokens = int(usage.get('prompt_n') or 0) + int(usage.get('cache_n') or 0)
output_tokens = (
usage.get('output_tokens') # Already standard
or usage.get('completion_tokens') # OpenAI
or usage.get('eval_count') # Ollama
or usage.get('predicted_n') # llama.cpp
or 0
)
total_tokens = usage.get('total_tokens') or (input_tokens + output_tokens)
# Add standardized fields to original data
result = dict(usage)
result['input_tokens'] = int(input_tokens)
result['output_tokens'] = int(output_tokens)
result['total_tokens'] = int(total_tokens)
aliases = {
'input_tokens': ('input_tokens', 'prompt_tokens', 'prompt_eval_count'),
'output_tokens': ('output_tokens', 'completion_tokens', 'eval_count', 'predicted_n'),
'total_tokens': ('total_tokens',),
}
for target, keys in aliases.items():
value = next((n for key in keys if (n := usage_counter(usage.get(key))) is not None), None)
result.pop(target, None)
if value is not None:
result[target] = value
prompt = usage_counter(usage.get('prompt_n'))
if 'input_tokens' not in result and prompt is not None:
result['input_tokens'] = prompt + (usage_counter(usage.get('cache_n')) or 0)
if 'total_tokens' not in result and all(key in result for key in ('input_tokens', 'output_tokens')):
result['total_tokens'] = result['input_tokens'] + result['output_tokens']
# SQL fallback readers must not turn invalid aliases into zero or fail a cast.
for key in ('prompt_tokens', 'completion_tokens'):
value = usage_counter(usage.get(key))
result.pop(key, None)
if value is not None:
result[key] = value
return result
@ -51,6 +51,8 @@ USAGE_TOKEN_KEYS = {
'input_tokens',
'output_tokens',
'total_tokens',
'cache_read_input_tokens',
'cache_creation_input_tokens',
}
USAGE_COST_KEYS = {
@ -112,6 +114,13 @@ def merge_usage(current: dict | None, incoming: dict | None) -> dict:
return incoming_usage
result = {**current_usage, **incoming_usage}
result['incomplete'] = bool(
current_usage.get('incomplete')
or incoming_usage.get('incomplete')
or any(
key not in record for record in (current_usage, incoming_usage) for key in ('input_tokens', 'output_tokens')
)
)
for key in USAGE_SUMMABLE_KEYS:
if key in current_usage or key in incoming_usage:
@ -129,20 +138,25 @@ def merge_usage(current: dict | None, incoming: dict | None) -> dict:
incoming_usage.get(key) if isinstance(incoming_usage.get(key), dict) else {},
)
result['prompt_tokens'] = (
incoming_usage.get('prompt_tokens')
or incoming_usage.get('input_tokens')
or current_usage.get('prompt_tokens', 0)
)
result['completion_tokens'] = (
incoming_usage.get('completion_tokens')
or incoming_usage.get('output_tokens')
or current_usage.get('completion_tokens', 0)
)
# Aliases mirror the cumulative canonical values, including a measured zero.
for alias, canonical in (('prompt_tokens', 'input_tokens'), ('completion_tokens', 'output_tokens')):
if canonical in result:
result[alias] = result[canonical]
return result
def update_usage_snapshot(current: dict | None, incoming: dict | None) -> dict:
"""Usage events within one provider call are snapshots, not extra model calls."""
result = {**(current or {}), **normalize_usage(incoming or {})}
for key in USAGE_DETAIL_KEYS:
if isinstance((current or {}).get(key), dict) and isinstance((incoming or {}).get(key), dict):
result[key] = {**current[key], **incoming[key]}
if all(key in result for key in ('input_tokens', 'output_tokens')):
result['total_tokens'] = result['input_tokens'] + result['output_tokens']
return result
def convert_ollama_tool_call_to_openai(tool_calls: list) -> list:
openai_tool_calls = []
for tool_call in tool_calls:
@ -161,11 +175,11 @@ def convert_ollama_tool_call_to_openai(tool_calls: list) -> list:
def convert_ollama_usage_to_openai(data: dict) -> dict:
input_tokens = int(data.get('prompt_eval_count', 0))
output_tokens = int(data.get('eval_count', 0))
input_tokens = usage_counter(data.get('prompt_eval_count')) or 0
output_tokens = usage_counter(data.get('eval_count')) or 0
total_tokens = input_tokens + output_tokens
return {
result = {
# Standardized fields
'input_tokens': input_tokens,
'output_tokens': output_tokens,
@ -199,13 +213,23 @@ def convert_ollama_usage_to_openai(data: dict) -> dict:
'approximate_total': (lambda s: f'{s // 3600}h{(s % 3600) // 60}m{s % 60}s')(
(data.get('total_duration', 0) or 0) // 1_000_000_000
),
'completion_tokens_details': {
'reasoning_tokens': 0,
'accepted_prediction_tokens': 0,
'rejected_prediction_tokens': 0,
},
}
for source, fields in (
('prompt_eval_count', ('input_tokens', 'prompt_tokens', 'prompt_eval_count')),
('eval_count', ('output_tokens', 'completion_tokens', 'eval_count')),
):
if usage_counter(data.get(source)) is None:
for field in fields:
result.pop(field, None)
result.pop('total_tokens', None)
for key in ('total_duration', 'load_duration', 'prompt_eval_duration', 'eval_duration'):
if key not in data:
result.pop(key, None)
if 'total_duration' not in data:
result.pop('approximate_total', None)
return result
def convert_response_ollama_to_openai(ollama_response: dict) -> dict:
model = ollama_response.get('model', 'ollama')

View file

@ -0,0 +1,65 @@
"""Interpret saved records without inventing missing measurements."""
import json
import math
import re
import time
def recorded_timestamp(value):
try:
value = float(value)
if value > 10_000_000_000:
value /= 1000
return int(value) if math.isfinite(value) and 1577836800 <= value <= time.time() + 86400 else None
except (ValueError, TypeError, OverflowError):
return None
def safe_snippet(value):
"""Analytics previews deliberately exclude raw payloads and identifiers."""
if not value:
return None
text = value if isinstance(value, str) else json.dumps(value)
text = re.sub(r'<[^>]*>', ' ', text)
text = re.sub(r'https?://\S+|(?:[\w.-]+/)+[\w./~-]*|\b[\w-]{24,}\b', ' ', text)
text = re.sub(r'(?i)\b(?:api[_-]?key|token|password|secret|authorization)\b[\"\x27]?\s*[:=]?\s*\S+', ' ', text)
return ' '.join(text.split()[:10])
def normalize_tool_output(output):
"""Deduplicate recorded call/result snapshots; never construct calls from prose."""
if not isinstance(output, list):
return output
items = [dict(item) for item in output if isinstance(item, dict)]
deduped = []
positions = {}
for item in items:
kind = item.get('type')
call_id = item.get('call_id') or item.get('id')
if kind in {'function_call', 'function_call_output'} and call_id:
key = (kind, call_id)
if key in positions:
deduped[positions[key]] = {**deduped[positions[key]], **item}
continue
positions[key] = len(deduped)
deduped.append(item)
return pair_results(deduped)
def pair_results(deduped):
results = {item.get('call_id'): item for item in deduped if item.get('type') == 'function_call_output'}
for item in deduped:
if item.get('type') != 'function_call':
continue
result = results.get(item.get('call_id'))
if result:
if result.get('status'):
item['status'] = result['status']
for key in ('started_at', 'ended_at', 'duration', 'error_type'):
if key in result and key not in item:
item[key] = result[key]
elif item.get('status') == 'completed':
item['status'] = 'unknown'
return deduped

View file

@ -0,0 +1,200 @@
import { WEBUI_API_BASE_URL } from '$lib/constants';
export type SessionScope = {
startDate: number | null;
endDate: number | null;
groupId: string | null;
};
export type Session = {
id: string;
title: string;
user_name: string | null;
folder_name: string | null;
kind: string | null;
forked_from?: string | null;
messages: number;
responses: number;
prompts: number;
recorded_responses: number;
complete_responses: number;
tokens: number;
cache_read?: number | null;
cache_write?: number | null;
cache_read_responses?: number;
cache_write_responses?: number;
errors: number;
started_at: number | null;
last_active: number | null;
span_seconds: number | null;
model_id: string | null;
model_count: number;
};
export type SessionMessage = {
id: string;
role: string;
model_id: string | null;
parent_id: string | null;
created_at: number;
done: boolean;
preview: string | null;
preview_truncated: boolean | null;
error: string | null;
tokens: number | null;
output_count: number;
};
export type SessionEvent = {
index: number;
type: string | null;
name: string | null;
call_id: string | null;
status: string | null;
error_type?: string | null;
started_at: number | null;
ended_at: number | null;
duration_seconds: number | null;
details: string | null;
truncated: boolean | null;
};
export const SESSION_TOKEN_RANGES = [
{ min: 0, max: 1, label: '0' },
{ min: 1, max: 1000, label: '<1K' },
{ min: 1000, max: 10000, label: '1K–<10K' },
{ min: 10000, max: 100000, label: '10K–<100K' },
{ min: 100000, max: 1000000, label: '100K–<1M' },
{ min: 1000000, max: null, label: '≥1M' }
];
export type SessionOverview = {
token_distribution: number[];
unrecorded_sessions: number;
max_tokens: number;
sessions: number;
tokens: number;
prompts: number;
responses: number;
errors: number;
recorded_responses: number;
complete_responses: number;
start: number | null;
end: number | null;
};
export type SessionOrder =
| 'title'
| 'user'
| 'recent'
| 'tokens'
| 'responses'
| 'errors'
| 'duration';
export type Page<T> = { items: T[]; has_more: boolean };
async function request<T>(
token: string,
path: string,
scope: SessionScope,
params: Record<string, string | number | boolean>,
signal: AbortSignal
): Promise<T> {
const query = new URLSearchParams();
if (scope.startDate !== null) query.set('start_date', String(scope.startDate));
if (scope.endDate !== null) query.set('end_date', String(scope.endDate));
if (scope.groupId) query.set('group_id', scope.groupId);
for (const [key, value] of Object.entries(params))
if (value !== '') query.set(key, String(value));
const response = await fetch(`${WEBUI_API_BASE_URL}/analytics/sessions${path}?${query}`, {
headers: { authorization: `Bearer ${token}` },
signal
});
if (!response.ok) throw new Error(`Unable to load session analytics (${response.status})`);
return response.json();
}
export const getSessions = (
token: string,
scope: SessionScope,
params: {
query: string;
model_id: string;
hide_subagents: boolean;
order_by: SessionOrder;
direction: 'asc' | 'desc';
include_summary: boolean;
token_min?: number;
token_max?: number;
skip: number;
limit: number;
},
signal: AbortSignal
) => request<Page<Session> & { overview?: SessionOverview }>(token, '', scope, params, signal);
export const getSessionMessages = (
token: string,
id: string,
scope: SessionScope,
skip: number,
signal: AbortSignal
) =>
request<Page<SessionMessage> & { session: Session }>(
token,
`/${encodeURIComponent(id)}`,
scope,
{ skip, limit: 25 },
signal
);
export const getSessionEvents = (
token: string,
id: string,
messageId: string,
scope: SessionScope,
skip: number,
signal: AbortSignal,
limit = 20
) =>
request<Page<SessionEvent>>(
token,
`/${encodeURIComponent(id)}/messages/${encodeURIComponent(messageId)}/events`,
scope,
{ skip, limit },
signal
);
export type TraceItem = Omit<SessionEvent, 'details' | 'truncated'> & {
message_id: string;
result_index: number | null;
created_at: number;
model_id: string | null;
};
export type UsageBar = {
first: number;
last: number;
offset: number;
input_tokens: number | null;
output_tokens: number | null;
recorded: number;
complete: number;
errors: number;
model_id: string | null;
};
export type SessionChart = {
timed_operations: number;
duration_operations: number;
usage: UsageBar[];
start: number | null;
end: number | null;
max_duration: number | null;
};
export type TraceView = 'all' | 'tools' | 'errors';
export const getSessionTrace = (
token: string,
id: string,
scope: SessionScope,
skip: number,
view: TraceView,
signal: AbortSignal,
includeChart = false
) =>
request<Page<TraceItem> & { session: Session; chart?: SessionChart }>(
token,
`/${encodeURIComponent(id)}/trace`,
scope,
{ skip, limit: 50, view, include_chart: includeChart },
signal
);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,411 @@
<script lang="ts">
import { getContext, onMount, onDestroy, tick } from 'svelte';
import dayjs from 'dayjs';
import Spinner from '$lib/components/common/Spinner.svelte';
import ChevronLeft from '$lib/components/icons/ChevronLeft.svelte';
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
import SessionUsageChart from './SessionUsageChart.svelte';
import SessionWaterfall from './SessionWaterfall.svelte';
import { modelColor } from './UsageChart.svelte';
import {
getSessionTrace,
type Session,
type SessionScope,
type SessionChart,
type TraceItem,
type TraceView
} from '$lib/apis/analytics/sessions';
export let session: Session;
export let scope: SessionScope;
export let modelNames: Record<string, string>;
export let onClose: () => void;
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
let items: TraceItem[] = [];
let expanded = new Set<string>();
type Row = { item: TraceItem; offset: number; expandable?: boolean; failed?: boolean };
$: groups = groupItems(items, page);
$: rows =
view === 'all'
? groups.flatMap((group) => [
group.header,
...(expanded.has(group.id) ? group.operations : [])
])
: items.map((item, index): Row => ({ item, offset: page * 50 + index }));
function groupItems(items: TraceItem[], page: number) {
const grouped = new Map<string, { id: string; header: Row; operations: Row[] }>();
items.forEach((item, index) => {
let group = grouped.get(item.message_id);
if (!group) {
group = {
id: item.message_id,
header: {
item:
item.index < 0
? item
: {
...item,
index: -1,
type: 'response',
status: null,
started_at: null,
ended_at: null,
duration_seconds: null
},
offset: page * 50 + index,
failed: false
},
operations: []
};
grouped.set(item.message_id, group);
}
group.header.failed ||= item.status === 'failed';
if (item.index >= 0) group.operations.push({ item, offset: page * 50 + index });
group.header.expandable = group.operations.length > 0;
});
return [...grouped.values()];
}
function toggleGroup(id: string) {
const next = new Set(expanded);
if (next.has(id)) next.delete(id);
else next.add(id);
expanded = next;
}
let view: TraceView = 'all';
let visualization: 'tokens' | 'timeline' = 'tokens';
let chart: SessionChart | null = null;
let targetOffset: number | null = null;
let page = 0;
let hasMore = false;
let loading = true;
let error = false;
let mounted = false;
let controller: AbortController;
let content: HTMLElement;
$: formatter = new Intl.NumberFormat($i18n.language, {
notation: 'compact',
maximumFractionDigits: 1
});
$: if (mounted && view && page >= 0) load();
async function load() {
controller?.abort();
expanded = new Set();
const current = new AbortController();
controller = current;
loading = true;
error = false;
try {
const result = await getSessionTrace(
localStorage.token,
session.id,
scope,
page * 50,
view,
current.signal,
chart === null
);
if (!current.signal.aborted) {
items = result.items;
hasMore = result.has_more;
session = result.session;
if (result.chart) chart = result.chart;
}
} catch {
if (!current.signal.aborted) error = true;
} finally {
if (!current.signal.aborted) {
loading = false;
await tick();
if (targetOffset !== null && !error) revealResponse();
else if (content) content.scrollTop = 0;
}
}
}
async function revealResponse() {
const group = groups.find((group) => group.header.offset === targetOffset);
if (group) expanded = new Set([...expanded, group.id]);
await tick();
const row = content?.querySelector<HTMLElement>(`[data-trace-offset="${targetOffset}"]`);
row?.scrollIntoView({ block: 'nearest' });
row?.focus({ preventScroll: true });
}
async function jumpToResponse(offset: number) {
targetOffset = offset;
view = 'all';
page = Math.floor(offset / 50);
await tick();
if (!loading) revealResponse();
}
function filterTrace(next: TraceView) {
targetOffset = null;
view = next;
page = 0;
}
const label = (item: TraceItem) =>
item.type === 'response'
? modelNames[item.model_id || ''] || item.model_id || $i18n.t('Response')
: item.name ||
{
function_call: $i18n.t('Tool call'),
function_call_output: $i18n.t('Tool result'),
reasoning: $i18n.t('Reasoning'),
'open_webui:code_interpreter': $i18n.t('Code interpreter')
}[item.type || ''] ||
item.type ||
$i18n.t('Saved item');
const status = (item: TraceItem) =>
({
completed: $i18n.t('Completed'),
failed: $i18n.t('Failed'),
in_progress: $i18n.t('In progress'),
pending: $i18n.t('Pending'),
cancelled: $i18n.t('Cancelled'),
rejected: $i18n.t('Rejected')
})[item.status || ''] || '';
const duration = (seconds: number) =>
seconds < 1
? `${Math.round(seconds * 1000)}ms`
: seconds < 60
? `${seconds.toFixed(1)}s`
: `${(seconds / 60).toFixed(1)}m`;
onMount(() => {
mounted = true;
});
onDestroy(() => {
controller?.abort();
});
</script>
<section
aria-label={$i18n.t('Session details')}
class="flex max-h-[calc(100dvh-6rem)] min-w-0 flex-col text-xs font-normal text-gray-500 dark:text-gray-400"
>
<div class="flex shrink-0 items-start gap-3 mb-3">
<h3 class="min-w-0 flex-1 text-sm font-normal text-gray-900 dark:text-gray-100 line-clamp-2">
{session.title || $i18n.t('Untitled chat')}
</h3>
<a
href={`/c/${encodeURIComponent(session.id)}`}
target="_blank"
rel="noopener noreferrer"
class="shrink-0 py-1 hover:text-gray-900 dark:hover:text-gray-100">{$i18n.t('Open chat')} ↗</a
>
<button
type="button"
data-close-session
aria-label={$i18n.t('Close session details')}
on:click={onClose}
class="shrink-0 rounded-lg p-1 hover:bg-gray-50 dark:hover:bg-gray-800"
><XMark className="size-4" /></button
>
</div>
<div
bind:this={content}
class="min-h-0 overflow-y-auto overscroll-contain scrollbar-hover"
data-session-content
>
<div class="mb-3 flex flex-wrap gap-x-3 gap-y-1 text-[0.6875rem]">
{#if session.user_name}<span>{session.user_name}</span>{/if}
{#if session.started_at}<span
>{dayjs
.unix(session.started_at)
.locale($i18n.language)
.format('MMM D, YYYY · HH:mm')}</span
>{/if}
{#if session.kind === 'subagent'}<span>{$i18n.t('Sub-agent')}</span>{/if}
</div>
<dl class="flex flex-wrap items-baseline gap-x-4 gap-y-1 mb-3">
<div class="flex gap-1.5">
<dt>{$i18n.t('Prompts')}</dt>
<dd class="tabular-nums text-gray-900 dark:text-gray-200">{session.prompts}</dd>
</div>
<div class="flex gap-1.5">
<dt>{$i18n.t('Responses')}</dt>
<dd class="tabular-nums text-gray-900 dark:text-gray-200">{session.responses}</dd>
</div>
{#if session.recorded_responses}<div
class="flex gap-1.5"
title={`${session.recorded_responses}/${session.responses} ${$i18n.t('responses with recorded usage')}`}
>
<dt>{$i18n.t('Tokens')}</dt>
<dd class="tabular-nums text-gray-900 dark:text-gray-200">
{formatter.format(session.tokens)}{session.complete_responses < session.responses
? '*'
: ''}
</dd>
</div>{/if}
{#if session.cache_read != null}<div class="flex gap-1.5">
<dt>{$i18n.t('Cache read')}</dt>
<dd class="tabular-nums text-gray-900 dark:text-gray-200">
{formatter.format(session.cache_read)}
</dd>
</div>{/if}
{#if session.cache_write != null}<div class="flex gap-1.5">
<dt>{$i18n.t('Cache write')}</dt>
<dd class="tabular-nums text-gray-900 dark:text-gray-200">
{formatter.format(session.cache_write)}
</dd>
</div>{/if}
</dl>
<div
class="flex items-center gap-3 mb-2"
role="group"
aria-label={$i18n.t('Session visualization')}
>
{#each [{ id: 'tokens', label: $i18n.t('Tokens') }, { id: 'timeline', label: $i18n.t('Timeline') }] as option}
<button
type="button"
aria-pressed={visualization === option.id}
class="py-1 hover:text-gray-900 dark:hover:text-gray-100"
class:text-gray-900={visualization === option.id}
class:dark:text-gray-100={visualization === option.id}
on:click={() => (visualization = option.id as typeof visualization)}
>{option.label}</button
>
{/each}
</div>
{#if visualization === 'tokens'}
{#if chart?.usage.some((bar) => bar.recorded > 0)}
<SessionUsageChart usage={chart.usage} onSelect={jumpToResponse} />
{:else if !loading && !error}
<p class="mb-4 text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Token usage not recorded')}
</p>
{/if}
{:else if !loading && !error}
<SessionWaterfall {items} {page} {label} {status} />
{/if}
<div class="flex items-center gap-3 mb-2" aria-label={$i18n.t('Trace filter')}>
{#each [{ id: 'all', label: $i18n.t('All') }, { id: 'tools', label: $i18n.t('Tools') }, { id: 'errors', label: $i18n.t('Errors') }] as filter}
<button
type="button"
aria-pressed={view === filter.id}
class="py-1 hover:text-gray-900 dark:hover:text-gray-100"
class:text-gray-900={view === filter.id}
class:dark:text-gray-100={view === filter.id}
on:click={() => filterTrace(filter.id as TraceView)}>{filter.label}</button
>
{/each}
</div>
<div aria-busy={loading} aria-label={$i18n.t('Saved execution sequence')}>
{#if loading}<div
class="flex justify-center py-12"
role="status"
aria-label={$i18n.t('Loading trace')}
>
<Spinner className="size-5" />
</div>
{:else if error}<div role="alert" class="py-12 text-center">
{$i18n.t('Unable to load session.')}
<button type="button" class="underline ml-2" on:click={load}>{$i18n.t('Retry')}</button>
</div>
{:else}
{#each rows as row (`${row.item.message_id}:${row.item.index}`)}
{@const item = row.item}
{#if item.index < 0}
<button
type="button"
data-model-group
aria-expanded={view === 'all' && row.expandable
? expanded.has(item.message_id)
: undefined}
aria-disabled={view !== 'all' || !row.expandable}
on:click={() => {
if (view === 'all' && row.expandable) toggleGroup(item.message_id);
}}
class="block w-full text-left mt-2 py-1.5 px-2.5 hover:text-gray-900 dark:hover:text-gray-100 focus-visible:outline focus-visible:outline-1 focus-visible:outline-gray-400"
data-trace-offset={row.offset}
class:bg-gray-50={view === 'all' && targetOffset === row.offset}
class:dark:bg-gray-850={view === 'all' && targetOffset === row.offset}
>
<div class="flex items-center gap-2">
<span
class="size-2 shrink-0"
style:background={item.model_id
? modelColor(item.model_id)
: 'var(--color-gray-400)'}
></span><span
class="min-w-0 truncate text-gray-900 dark:text-gray-200"
title={label(item)}>{label(item)}</span
>{#if row.failed || item.status === 'failed'}<span>{$i18n.t('Errors')}</span
>{/if}{#if item.duration_seconds !== null}<span
data-response-duration
class="shrink-0 text-[0.6875rem] tabular-nums"
title={`${$i18n.t('Response duration')} · ${dayjs.unix(item.started_at!).format('MMM D, HH:mm:ss')}–${dayjs.unix(item.ended_at!).format('MMM D, HH:mm:ss')}`}
>{duration(item.duration_seconds)}</span
>{/if}{#if item.created_at}<span
class="ml-auto shrink-0 text-[0.6875rem] tabular-nums"
>{dayjs.unix(item.created_at).format('HH:mm')}</span
>{/if}
{#if view === 'all' && row.expandable}<ChevronRight
className={`size-3 shrink-0 ${expanded.has(item.message_id) ? 'rotate-90' : ''}`}
/>{/if}
</div>
</button>
{:else}
<div class:ps-4={view === 'all'}>
<div
data-operation
title={item.error_type || undefined}
aria-label={[
label(item),
status(item),
item.duration_seconds !== null ? duration(item.duration_seconds) : ''
]
.filter(Boolean)
.join(' · ')}
class="flex items-center gap-2 w-full text-left px-2.5 py-1.5"
>
<span
class="size-2 shrink-0"
style:background={item.model_id
? modelColor(item.model_id)
: 'var(--color-gray-400)'}
></span>
<span
class="min-w-0 flex-1 truncate text-gray-900 dark:text-gray-200"
title={label(item)}>{label(item)}</span
>
{#if status(item)}<span class="text-[0.6875rem] shrink-0">{status(item)}</span>{/if}
{#if item.duration_seconds !== null}<span
class="text-[0.6875rem] tabular-nums shrink-0 min-w-12 text-right"
>{duration(item.duration_seconds)}</span
>{/if}
</div>
</div>
{/if}
{:else}<p class="py-12 text-center">
{$i18n.t('No saved items match this filter.')}
</p>{/each}
{/if}
</div>
</div>
<div class="flex shrink-0 items-center justify-end gap-2 pt-3 text-[0.6875rem]">
<button
type="button"
aria-label={$i18n.t('Previous trace items')}
disabled={loading || page === 0}
class="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-850 disabled:opacity-30"
on:click={() => {
targetOffset = null;
page--;
}}><ChevronLeft className="size-3.5" /></button
>
<span>{$i18n.t('Page')} {page + 1}</span>
<button
type="button"
aria-label={$i18n.t('Next trace items')}
disabled={loading || error || !hasMore}
class="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-850 disabled:opacity-30"
on:click={() => {
targetOffset = null;
page++;
}}><ChevronRight className="size-3.5" /></button
>
</div>
</section>

View file

@ -0,0 +1,412 @@
<script lang="ts">
import { getContext, onMount, onDestroy, tick } from 'svelte';
import dayjs from 'dayjs';
import Spinner from '$lib/components/common/Spinner.svelte';
import Modal from '$lib/components/common/Modal.svelte';
import Dropdown from '$lib/components/common/Dropdown.svelte';
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte';
import Check from '$lib/components/icons/Check.svelte';
import ChevronUp from '$lib/components/icons/ChevronUp.svelte';
import ChevronDown from '$lib/components/icons/ChevronDown.svelte';
import ChevronLeft from '$lib/components/icons/ChevronLeft.svelte';
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
import {
getSessions,
SESSION_TOKEN_RANGES,
type Session,
type SessionOrder,
type SessionScope,
type SessionOverview
} from '$lib/apis/analytics/sessions';
import SessionDetail from './SessionDetail.svelte';
import { modelColor } from './UsageChart.svelte';
import SessionSignals from './SessionSignals.svelte';
export let scope: SessionScope;
export let modelNames: Record<string, string> = {};
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
let query = '';
let modelId = '';
let hideSubagents = false;
let order: SessionOrder = 'tokens';
let direction: 'asc' | 'desc' = 'desc';
let sortFocus: SessionOrder | null = null;
let explorer: HTMLElement;
$: columns = [
{ key: 'title', label: $i18n.t('Session') },
{ key: 'user', label: $i18n.t('User') },
{ key: 'recent', label: $i18n.t('Last active') },
{ key: 'responses', label: $i18n.t('Responses'), numeric: true },
{ key: 'tokens', label: $i18n.t('Tokens'), numeric: true },
{ key: 'errors', label: $i18n.t('Response errors'), numeric: true },
{ key: 'duration', label: $i18n.t('Span'), numeric: true }
] as { key: SessionOrder; label: string; numeric?: boolean }[];
function toggleSort(key: SessionOrder) {
direction =
order === key
? direction === 'asc'
? 'desc'
: 'asc'
: key === 'title' || key === 'user'
? 'asc'
: 'desc';
order = key;
sortFocus = key;
}
let tokenRange: number | null = null;
let page = 0;
let items: Session[] = [];
let overview: SessionOverview | null = null;
let overviewKey = '';
let hasMore = false;
let selected: Session | null = null;
let detailPanel: HTMLElement;
let selectedButton: HTMLElement | null = null;
async function selectSession(session: Session, event: MouseEvent) {
selectedButton = event.currentTarget as HTMLElement;
selected = session;
await tick();
detailPanel
?.querySelector<HTMLButtonElement>('[data-close-session]')
?.focus({ preventScroll: true });
}
async function closeSession() {
selected = null;
await tick();
selectedButton?.focus({ preventScroll: true });
}
let mounted = false;
let loading = true;
let error = false;
let controller: AbortController;
let timer: ReturnType<typeof setTimeout>;
const pageSize = 25;
$: formatter = new Intl.NumberFormat($i18n.language, {
notation: 'compact',
maximumFractionDigits: 1
});
$: scopeKey = JSON.stringify([scope, query, modelId, hideSubagents]);
$: if (scopeKey) tokenRange = null;
$: filterKey = JSON.stringify([scopeKey, order, direction, tokenRange]);
$: if (filterKey) {
page = 0;
selected = null;
}
$: if (mounted && filterKey && page >= 0) scheduleLoad();
function scheduleLoad() {
clearTimeout(timer);
controller?.abort();
loading = true;
error = false;
timer = setTimeout(load, 200);
}
async function load() {
controller?.abort();
const current = new AbortController();
controller = current;
loading = true;
error = false;
try {
const result = await getSessions(
localStorage.token,
scope,
{
...(tokenRange !== null
? {
token_min: SESSION_TOKEN_RANGES[tokenRange].min,
...(SESSION_TOKEN_RANGES[tokenRange].max !== null
? { token_max: SESSION_TOKEN_RANGES[tokenRange].max! }
: {})
}
: {}),
query,
model_id: modelId,
hide_subagents: hideSubagents,
order_by: order,
direction,
include_summary: overviewKey !== scopeKey,
skip: page * pageSize,
limit: pageSize
},
current.signal
);
if (!current.signal.aborted) {
items = result.items;
if (result.overview) {
overview = result.overview;
overviewKey = scopeKey;
}
hasMore = result.has_more;
}
} catch {
if (!current.signal.aborted) {
error = true;
items = [];
}
} finally {
if (!current.signal.aborted) {
loading = false;
await tick();
if (sortFocus && document.activeElement === document.body)
explorer
?.querySelector<HTMLButtonElement>(`[data-sort="${sortFocus}"]`)
?.focus({ preventScroll: true });
sortFocus = null;
}
}
}
const span = (seconds: number | null) =>
seconds === null
? $i18n.t('Not logged')
: seconds < 60
? `${Math.round(seconds)}s`
: seconds < 3600
? `${Math.round(seconds / 60)}m`
: `${(seconds / 3600).toFixed(1)}h`;
onMount(() => {
mounted = true;
});
onDestroy(() => {
clearTimeout(timer);
controller?.abort();
});
</script>
<div class="min-w-0">
<section
bind:this={explorer}
aria-label={$i18n.t('Sessions')}
class="min-w-0 flex-1 text-xs text-gray-500 dark:text-gray-400"
>
{#if overview && overviewKey === scopeKey && !error}<SessionSignals
{overview}
selectedRange={tokenRange}
onSelect={(index) => (tokenRange = index)}
/>{/if}
<div class="flex flex-wrap items-center justify-between gap-3 mb-3">
<input
type="search"
bind:value={query}
maxlength="200"
aria-label={$i18n.t('Search sessions')}
placeholder={$i18n.t('Search sessions, users or folders')}
class="min-w-0 h-7 w-full sm:w-56 bg-transparent p-0 text-xs text-gray-500 dark:text-gray-400 placeholder:text-gray-400 outline-none focus:text-gray-900 dark:focus:text-gray-100"
/>
<div class="flex w-full sm:w-auto items-center gap-x-4">
<select
bind:value={modelId}
aria-label={$i18n.t('Model')}
class="min-w-0 w-fit max-w-40 pr-5 py-1 text-xs bg-transparent outline-none text-gray-500 dark:text-gray-400"
>
<option value="">{$i18n.t('All models')}</option>
{#each Object.entries(modelNames).sort( (a, b) => a[1].localeCompare(b[1]) ) as [id, name]}<option
value={id}>{name}</option
>{/each}
</select>
<div class="ml-auto shrink-0">
<Dropdown align="end" closeOnSelect>
<button
type="button"
aria-label={$i18n.t('Session options')}
class="flex items-center justify-center p-1.5 text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white"
>
<EllipsisHorizontal className="size-4" />
</button>
<div slot="content">
<DropdownMenu className="min-w-48">
<button
type="button"
role="menuitemcheckbox"
aria-checked={hideSubagents}
on:click={() => (hideSubagents = !hideSubagents)}
>
<span class="flex-1 text-left">{$i18n.t('Hide sub-agents')}</span>
<span class="size-3.5 shrink-0"
>{#if hideSubagents}<Check className="size-3.5" />{/if}</span
>
</button>
</DropdownMenu>
</div>
</Dropdown>
</div>
</div>
</div>
<div aria-busy={loading} class="min-h-40">
{#if loading}
<div
class="flex justify-center py-12"
role="status"
aria-label={$i18n.t('Loading sessions')}
>
<Spinner className="size-5" />
</div>
{:else if error}
<div role="alert" class="py-12 text-center">
{$i18n.t('Unable to load sessions.')}
<button type="button" class="underline underline-offset-2 ml-2" on:click={load}
>{$i18n.t('Retry')}</button
>
</div>
{:else if !items.length}
<div class="py-12 text-center">{$i18n.t('No sessions match these filters.')}</div>
{:else}
<div class="max-h-[22rem] overflow-auto scrollbar-hover">
<table class="session-table w-full text-left text-xs tabular-nums whitespace-nowrap">
<thead class="sticky top-0 z-10 bg-white dark:bg-gray-900 text-[0.6875rem]">
<tr>
{#each columns as column}
<th
scope="col"
class="font-normal"
aria-sort={order === column.key
? direction === 'asc'
? 'ascending'
: 'descending'
: 'none'}
title={column.key === 'duration'
? $i18n.t('First to last saved message, including idle time')
: undefined}
>
<button
type="button"
data-sort={column.key}
on:click={() => toggleSort(column.key)}
class="w-full flex gap-1.5 items-center px-2.5 py-1.5 text-left font-normal cursor-pointer select-none focus-visible:outline focus-visible:outline-1 focus-visible:outline-gray-400"
class:justify-end={column.numeric}
>
{column.label}
{#if order === column.key}
{#if direction === 'asc'}<ChevronUp className="size-2" />{:else}<ChevronDown
className="size-2"
/>{/if}
{:else}<span class="invisible"><ChevronUp className="size-2" /></span>{/if}
</button>
</th>
{/each}
</tr>
</thead>
<tbody>
{#each items as session (session.id)}
<tr
class="hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
class:bg-gray-50={selected?.id === session.id}
class:dark:bg-gray-850={selected?.id === session.id}
>
<td class="px-2.5 py-1.5">
<button
type="button"
on:click={(event) => selectSession(session, event)}
class="text-left block w-full max-w-[12rem] sm:max-w-80 rounded-sm focus-visible:outline focus-visible:outline-1 focus-visible:outline-gray-400"
>
<span
class="block truncate text-gray-900 dark:text-gray-200"
title={session.title}>{session.title || $i18n.t('Untitled chat')}</span
>
<span
class="flex items-center gap-2 text-[0.6875rem] text-gray-400 dark:text-gray-500 mt-0.5"
><span class="truncate max-w-40"
>{session.folder_name ||
(session.model_id
? modelNames[session.model_id] || session.model_id
: $i18n.t('No model recorded'))}</span
>{#if session.forked_from}<span class="shrink-0">{$i18n.t('Fork')}</span
>{/if}{#if session.kind === 'subagent'}<span class="shrink-0"
>{$i18n.t('Sub-agent')}</span
>{/if}{#if !session.folder_name && session.model_count > 1}<span
class="shrink-0">+{session.model_count - 1}</span
>{/if}</span
>
</button>
</td>
<td class="px-2.5 py-1.5"
><span class="block max-w-28 truncate">{session.user_name || '-'}</span></td
>
<td
class="px-2.5 py-1.5"
title={session.last_active
? dayjs.unix(session.last_active).format('YYYY-MM-DD HH:mm:ss')
: ''}
>{session.last_active
? dayjs
.unix(session.last_active)
.locale($i18n.language)
.format('MMM D, HH:mm')
: $i18n.t('Not logged')}</td
>
<td class="px-2.5 py-1.5 text-right"
>{session.responses.toLocaleString($i18n.language)}</td
>
<td
class="px-2.5 py-1.5 text-right"
title={`${session.recorded_responses}/${session.responses} ${$i18n.t('responses with recorded usage')}`}
><div class="flex items-center justify-end gap-3">
<span class="w-20 h-1.5 shrink-0" aria-hidden="true">
{#if session.recorded_responses && overview && overview.max_tokens > 0}
<span
data-token-bar
class="block h-full"
style:width={`${(100 * session.tokens) / overview.max_tokens}%`}
style:background={session.model_count === 1 && session.model_id
? modelColor(session.model_id)
: 'var(--color-gray-400)'}
></span>
{/if}
</span>
<span class="min-w-12"
>{session.recorded_responses
? formatter.format(session.tokens)
: '-'}{#if session.recorded_responses > 0 && session.complete_responses < session.responses}<span
class="text-gray-400">*</span
>{/if}</span
>
</div></td
>
<td class="px-2.5 py-1.5 text-right">{session.errors}</td>
<td class="px-2.5 py-1.5 text-right">{span(session.span_seconds)}</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</div>
<div
class="mt-3 flex items-center justify-between gap-3 text-[0.6875rem] text-gray-400 dark:text-gray-500"
>
<span
title={$i18n.t(
'One session per chat. Counts cover the selected date range; span includes idle time.'
)}>{$i18n.t('- usage not recorded · * partial usage')}</span
>
<div class="flex items-center gap-2">
<button
type="button"
aria-label={$i18n.t('Previous sessions')}
disabled={loading || page === 0}
class="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-850 disabled:opacity-30"
on:click={() => page--}><ChevronLeft className="size-3.5" /></button
><span>{$i18n.t('Page')} {page + 1}</span><button
type="button"
aria-label={$i18n.t('Next sessions')}
disabled={loading || error || !hasMore}
class="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-850 disabled:opacity-30"
on:click={() => page++}><ChevronRight className="size-3.5" /></button
>
</div>
</div>
</section>
{#if selected}
<Modal
show={true}
size="lg"
ariaLabel={$i18n.t('Session details')}
onRequestClose={closeSession}
>
<div bind:this={detailPanel} class="p-5">
<SessionDetail session={selected} {scope} {modelNames} onClose={closeSession} />
</div>
</Modal>
{/if}
</div>

View file

@ -0,0 +1,94 @@
<script lang="ts">
import { getContext } from 'svelte';
import { SESSION_TOKEN_RANGES, type SessionOverview } from '$lib/apis/analytics/sessions';
export let overview: SessionOverview;
export let selectedRange: number | null = null;
export let onSelect: (index: number | null) => void;
$: counts = overview.token_distribution ?? [];
$: peak = Math.max(1, ...counts);
$: tickUnit = Math.max(1, 10 ** Math.floor(Math.log10(peak / 4)));
$: ceiling = Math.ceil(peak / 4 / tickUnit) * tickUnit * 4;
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
$: number = new Intl.NumberFormat($i18n.language, {
notation: 'compact',
maximumFractionDigits: 1
});
</script>
<section
class="mb-4 text-xs font-normal text-gray-500 dark:text-gray-400"
aria-label={$i18n.t('Session summary')}
>
<dl class="flex flex-wrap items-baseline gap-x-4 gap-y-1">
{#each [{ label: $i18n.t('Sessions'), value: number.format(overview.sessions) }, { label: $i18n.t('Prompts'), value: number.format(overview.prompts) }, { label: $i18n.t('Recorded tokens'), value: overview.recorded_responses ? number.format(overview.tokens) + (overview.complete_responses < overview.responses ? '*' : '') : '-' }, { label: $i18n.t('Response errors'), value: overview.responses ? `${((overview.errors / overview.responses) * 100).toFixed(1)}%` : '-' }] as stat}
<div class="flex items-baseline gap-1.5 whitespace-nowrap">
<dt>{stat.label}</dt>
<dd class="tabular-nums text-gray-900 dark:text-gray-200">{stat.value}</dd>
</div>
{/each}
</dl>
{#if counts.some((count) => count > 0)}
<figure class="mt-4" aria-label={$i18n.t('Sessions by recorded token usage')}>
<figcaption class="flex items-center justify-between gap-3 mb-3 text-[0.6875rem]">
<span>{$i18n.t('Sessions by recorded token usage')}</span>
{#if selectedRange !== null}<button
type="button"
class="py-1 hover:text-gray-900 dark:hover:text-gray-100"
on:click={() => onSelect(null)}>{$i18n.t('All sessions')}</button
>{:else}<span>{$i18n.t('Sessions')}</span>{/if}
</figcaption>
<div class="relative h-40 pl-12">
{#each [ceiling, ceiling * 0.75, ceiling / 2, ceiling * 0.25, 0] as count}
<div
class="absolute inset-x-0 flex items-center gap-2 pointer-events-none translate-y-1/2"
style:bottom={`${(100 * count) / ceiling}%`}
>
<span class="w-10 shrink-0 text-right text-[0.6875rem] tabular-nums"
>{number.format(count)}</span
><span class="h-px flex-1 bg-gray-100 dark:bg-gray-850/50"></span>
</div>
{/each}
<div class="relative flex h-full">
{#each SESSION_TOKEN_RANGES as range, index}
<button
type="button"
data-token-range
class="relative flex flex-1 min-w-0 items-end justify-center focus-visible:outline focus-visible:outline-1 focus-visible:outline-gray-400"
disabled={!counts[index]}
aria-pressed={selectedRange === index}
aria-label={`${range.label} ${$i18n.t('Recorded tokens')}: ${counts[index]} ${$i18n.t('Sessions')}`}
on:click={() => onSelect(selectedRange === index ? null : index)}
>
<span
class="relative w-3/4 max-w-12 bg-gray-400 dark:bg-gray-500"
style:height={`${(100 * counts[index]) / ceiling}%`}
style:opacity={selectedRange === null || selectedRange === index ? 1 : 0.3}
>
{#if counts[index]}<span
class="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 w-max whitespace-nowrap text-[0.6875rem] tabular-nums text-gray-700 dark:text-gray-300"
>{number.format(counts[index])}</span
>{/if}
</span>
</button>
{/each}
</div>
</div>
<div class="ml-12 mt-2 flex text-[0.625rem] tabular-nums">
{#each SESSION_TOKEN_RANGES as range}<span
class="flex-1 min-w-0 text-center whitespace-nowrap"
>{range.label.replace('–<', '–')}</span
>{/each}
</div>
<p class="mt-3 text-[0.625rem] text-gray-400 dark:text-gray-500">
{$i18n.t('Select a range to filter sessions. Partial usage is included.')}
{#if overview.unrecorded_sessions}
{number.format(overview.unrecorded_sessions)}
{$i18n.t(
overview.unrecorded_sessions === 1
? 'session without recorded usage'
: 'sessions without recorded usage'
)}{/if}
</p>
</figure>
{/if}
</section>

View file

@ -0,0 +1,172 @@
<script lang="ts">
import { getContext } from 'svelte';
import type { UsageBar } from '$lib/apis/analytics/sessions';
import { modelColor } from './UsageChart.svelte';
export let usage: UsageBar[];
export let onSelect: (offset: number) => void;
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
let width = 0;
let active = 0;
let plot: HTMLDivElement;
$: formatter = new Intl.NumberFormat($i18n.language, {
notation: 'compact',
maximumFractionDigits: 1
});
// Consecutive groups keep the full session visible with usable targets on narrow screens.
$: groupSize = Math.max(1, Math.ceil(usage.length / Math.max(1, Math.floor(width / 16))));
$: bars = group(usage, groupSize);
$: active = Math.min(active, Math.max(0, bars.length - 1));
$: highest = Math.max(1, ...bars.map(total));
$: unit = 10 ** Math.floor(Math.log10(highest));
$: ceiling = Math.ceil(highest / unit) * unit;
$: current = bars[active];
const total = (bar: UsageBar) => (bar.input_tokens ?? 0) + (bar.output_tokens ?? 0);
const partial = (bar: UsageBar) => bar.complete < bar.last - bar.first + 1;
const range = (bar: UsageBar) =>
`${bar.first === bar.last ? $i18n.t('Response') : $i18n.t('Responses')} ${bar.first}${bar.last > bar.first ? `–${bar.last}` : ''}`;
const amount = (value: number | null) =>
value == null ? '-' : value.toLocaleString($i18n.language);
const description = (bar: UsageBar) =>
`${range(bar)} · ${$i18n.t('Input')} ${amount(bar.input_tokens)} · ${$i18n.t('Output')} ${amount(bar.output_tokens)}${partial(bar) ? ` · ${$i18n.t('Partial usage')}` : ''}${bar.errors ? ` · ${bar.errors} ${$i18n.t('Response errors')}` : ''}`;
function group(points: UsageBar[], size: number): UsageBar[] {
const result: UsageBar[] = [];
for (let i = 0; i < points.length; i += size) {
const slice = points.slice(i, i + size);
const sum = (key: 'input_tokens' | 'output_tokens') =>
slice.some((p) => p[key] != null) ? slice.reduce((n, p) => n + (p[key] ?? 0), 0) : null;
result.push({
...slice[0],
last: slice[slice.length - 1].last,
input_tokens: sum('input_tokens'),
output_tokens: sum('output_tokens'),
recorded: slice.reduce((n, p) => n + p.recorded, 0),
complete: slice.reduce((n, p) => n + p.complete, 0),
errors: slice.reduce((n, p) => n + p.errors, 0),
model_id: slice.every((p) => p.model_id === slice[0].model_id) ? slice[0].model_id : null
});
}
return result;
}
function navigate(event: KeyboardEvent, index: number) {
let next = index;
if (event.key === 'ArrowRight') next = Math.min(index + 1, bars.length - 1);
else if (event.key === 'ArrowLeft') next = Math.max(index - 1, 0);
else if (event.key === 'Home') next = 0;
else if (event.key === 'End') next = bars.length - 1;
else return;
event.preventDefault();
active = next;
plot.querySelectorAll<HTMLButtonElement>('[data-usage-bar]')[next]?.focus();
}
</script>
{#if bars.length}
<figure class="mb-4" aria-label={$i18n.t('Recorded tokens by response')}>
<figcaption
class="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1 mb-3 text-[0.6875rem]"
>
<span>{$i18n.t('Recorded tokens by response')}</span>
<span class="flex items-center gap-3">
<span class="flex items-center gap-1.5"
><span class="size-2 bg-gray-400 opacity-45"></span>{$i18n.t('Input')}</span
>
<span class="flex items-center gap-1.5"
><span class="size-2 bg-gray-400"></span>{$i18n.t('Output')}</span
>
{#if usage.some((bar) => bar.errors > 0)}<span class="flex items-center gap-1.5"
><span class="size-1.5 bg-gray-400 dark:bg-gray-500"></span>{$i18n.t(
'Response errors'
)}</span
>{/if}
</span>
</figcaption>
<div class="relative h-40 pl-12">
{#each [ceiling, ceiling * 0.75, ceiling / 2, ceiling * 0.25, 0] as value}
<div
class="absolute inset-x-0 flex items-center gap-2 pointer-events-none translate-y-1/2"
style:bottom={`${(100 * value) / ceiling}%`}
>
<span class="w-10 shrink-0 text-right text-[0.6875rem] tabular-nums"
>{formatter.format(value)}</span
>
<span class="h-px flex-1 bg-gray-100 dark:bg-gray-850/50"></span>
</div>
{/each}
<div
bind:this={plot}
bind:clientWidth={width}
class="relative flex h-full"
role="group"
aria-label={$i18n.t('Use arrow keys to explore the chart')}
>
{#each bars as bar, index (bar.first)}
<button
type="button"
data-usage-bar
class="relative flex-1 min-w-0 flex items-end justify-center focus-visible:outline focus-visible:outline-1 focus-visible:outline-gray-400"
tabindex={index === active ? 0 : -1}
aria-label={description(bar)}
title={description(bar)}
on:mouseenter={() => (active = index)}
on:focus={() => (active = index)}
on:keydown={(event) => navigate(event, index)}
on:click={() => onSelect(bar.offset)}
>
<span
class="w-3/4 max-w-12 h-full flex flex-col-reverse"
aria-hidden="true"
style:color={bar.model_id ? modelColor(bar.model_id) : 'var(--color-gray-400)'}
>
{#if !bar.recorded}<span class="absolute bottom-0 text-[0.6875rem] leading-none"
>-</span
>
{:else if total(bar) === 0}<span class="h-px w-full bg-current"></span>
{:else}
<span
class="block shrink-0 bg-current opacity-45"
style:height={`${(100 * (bar.input_tokens ?? 0)) / ceiling}%`}
></span>
<span
class="block shrink-0 bg-current"
style:height={`${(100 * (bar.output_tokens ?? 0)) / ceiling}%`}
></span>
{/if}
</span>
{#if bar.errors}<span
aria-hidden="true"
class="absolute top-0 size-1.5 bg-gray-400 dark:bg-gray-500"
></span>{/if}
</button>
{/each}
</div>
</div>
<div class="ml-12 mt-2 flex justify-between text-[0.625rem] tabular-nums">
<span>{bars[0].first}</span><span>{$i18n.t('Response order')}</span><span
>{bars[bars.length - 1].last}</span
>
</div>
{#if current}
<div
class="mt-3 flex flex-wrap gap-x-3 gap-y-1 text-[0.6875rem] tabular-nums"
aria-live="polite"
>
<span class="text-gray-900 dark:text-gray-200">{range(current)}</span>
<span>{$i18n.t('Input')} {amount(current.input_tokens)}</span><span
>{$i18n.t('Output')} {amount(current.output_tokens)}</span
>
{#if partial(current)}<span
>{$i18n.t('Partial usage')} · {current.complete}/{current.last - current.first + 1}
{$i18n.t('complete')}</span
>{/if}
{#if current.errors}<span>{current.errors} {$i18n.t('Response errors')}</span>{/if}
</div>
{/if}
<p class="mt-1 text-[0.625rem] text-gray-400 dark:text-gray-500">
{$i18n.t(
'Select a bar to jump to its saved responses. Grouped bars sum consecutive responses.'
)}
{$i18n.t('- usage not recorded')}
</p>
</figure>
{/if}

View file

@ -0,0 +1,140 @@
<script lang="ts">
import { getContext } from 'svelte';
import type { TraceItem } from '$lib/apis/analytics/sessions';
import { modelColor } from './UsageChart.svelte';
export let items: TraceItem[];
export let page: number;
export let label: (item: TraceItem) => string;
export let status: (item: TraceItem) => string;
const i18n = getContext<typeof import('$lib/i18n').default>('i18n');
const timed = (item: TraceItem) =>
item.started_at != null &&
Number.isFinite(item.started_at) &&
item.ended_at != null &&
Number.isFinite(item.ended_at) &&
item.ended_at >= item.started_at;
const measured = (item: TraceItem) =>
item.duration_seconds != null &&
Number.isFinite(item.duration_seconds) &&
item.duration_seconds >= 0;
const duration = (seconds: number) =>
seconds < 1
? `${Math.round(seconds * 1000)}ms`
: seconds < 60
? `${seconds.toFixed(1)}s`
: `${(seconds / 60).toFixed(1)}m`;
$: waterfall = items.some(timed);
$: sequence = !waterfall && !items.some(measured);
$: bars = sequence ? items : items.filter(waterfall ? timed : measured);
$: lanes = sequence
? [...new Set(bars.map(label))].map((name) => ({
name,
entries: bars.flatMap((item, index) => (label(item) === name ? [{ item, index }] : []))
}))
: bars.map((item, index) => ({ name: label(item), entries: [{ item, index }] }));
$: start = waterfall ? Math.min(...bars.map((item) => item.started_at!)) : 0;
$: end = waterfall
? Math.max(...bars.map((item) => item.ended_at!))
: Math.max(0, ...bars.map((item) => item.duration_seconds ?? 0));
$: span = end - start;
const elapsed = (item: TraceItem) =>
waterfall ? item.ended_at! - item.started_at! : item.duration_seconds!;
</script>
<figure class="mb-4" aria-label={$i18n.t('Execution timeline')}>
<figcaption class="flex justify-between gap-3 mb-2 text-[0.6875rem]">
<span
>{sequence
? $i18n.t('Recorded sequence')
: waterfall
? $i18n.t('Execution timeline')
: $i18n.t('Recorded duration')}</span
>
<span>{$i18n.t('Page')} {page + 1}</span>
</figcaption>
{#if bars.length}
<!-- Keyboard users must be able to scroll the bounded chart. -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="max-h-48 overflow-y-auto scrollbar-hover focus-visible:outline focus-visible:outline-1 focus-visible:outline-gray-400"
tabindex="0"
role="region"
aria-label={$i18n.t('Execution timeline')}
>
<div
class="grid grid-cols-[6rem_minmax(0,1fr)_3rem] sm:grid-cols-[10rem_minmax(0,1fr)_3.5rem] gap-x-2 sticky top-0 z-10 bg-white dark:bg-gray-900 pb-1 text-[0.625rem] tabular-nums"
aria-hidden="true"
>
<span></span>
<div class="flex justify-between">
{#if sequence}
<span>1</span><span>{$i18n.t('Saved order')}</span><span>{bars.length}</span>
{:else}
<span>0s</span><span>{duration(span / 2)}</span><span>{duration(span)}</span>
{/if}
</div>
<span class="text-right">{sequence ? $i18n.t('Count') : ''}</span>
</div>
{#each lanes as lane, laneIndex (laneIndex)}
{@const item = lane.entries[0].item}
<div
data-waterfall-row
class="grid grid-cols-[6rem_minmax(0,1fr)_3rem] sm:grid-cols-[10rem_minmax(0,1fr)_3.5rem] gap-x-2 items-center min-h-7 text-[0.6875rem]"
title={sequence
? lane.name
: `${item.model_id || ''} · ${label(item)} · ${status(item)}${waterfall ? ` · ${duration(item.started_at! - start)}–${duration(item.ended_at! - start)}` : ''}`}
>
<span class="truncate"
>{lane.name}{!sequence && item.status === 'failed' ? ` · ${status(item)}` : ''}</span
>
<div class="relative h-7" aria-hidden="true">
{#each [0, 50, 100] as tick}<span
class="absolute inset-y-0 w-px bg-gray-100 dark:bg-gray-850/50"
style:left={`${tick}%`}
></span>{/each}
{#each lane.entries as entry (entry.index)}
<span
data-waterfall-bar={sequence ? undefined : ''}
data-sequence-mark={sequence ? '' : undefined}
class={sequence
? 'absolute top-2.5 size-2 -translate-x-1/2'
: 'absolute top-2 h-3 min-w-px max-w-full'}
style:left={sequence
? `${(100 * (entry.index + 0.5)) / bars.length}%`
: `${waterfall && span > 0 ? (100 * (item.started_at! - start)) / span : 0}%`}
style:width={sequence
? `min(0.5rem, ${80 / bars.length}%)`
: `${span > 0 ? (100 * elapsed(item)) / span : 0}%`}
title={sequence
? `#${entry.index + 1} · ${entry.item.model_id || ''} · ${status(entry.item)}`
: undefined}
style:background={entry.item.model_id
? modelColor(entry.item.model_id)
: 'var(--color-gray-400)'}
></span>
{/each}
</div>
<span class="text-right tabular-nums"
>{sequence ? lane.entries.length : duration(elapsed(item))}</span
>
</div>
{/each}
</div>
<p class="mt-2 text-[0.625rem] text-gray-400 dark:text-gray-500">
{sequence
? $i18n.t('Saved order only; spacing does not represent elapsed time.')
: waterfall
? $i18n.t('Time from first timed operation on this page.')
: $i18n.t('Start/end times not recorded; bars compare durations only.')}
{#if !sequence && bars.length < items.length}{items.length - bars.length}
{waterfall
? $i18n.t('items without recorded start/end times')
: $i18n.t('items without recorded durations')}{/if}
</p>
{:else}
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-500">
{$i18n.t('No saved items match this filter.')}
</p>
{/if}
</figure>

View file

@ -1,5 +1,6 @@
{
"-1 for no limit, or a positive integer for a specific limit": "",
"- usage not recorded · * partial usage": "- usage not recorded · * partial usage",
"(latest)": "",
"(leave blank for to use commercial endpoint)": "",
"[Last] dddd [at] h:mm A": "",
@ -70,6 +71,7 @@
"{{user}}'s Chats": "",
"{{webUIName}} Backend Required": "",
"* (all domains)": "",
"* Partial token usage.": "* Partial token usage.",
"*Prompt node ID(s) are required for image generation": "",
"*required": "",
"1 file": "",
@ -116,8 +118,10 @@
"Actions for {{filename}}": "Actions for {{filename}}",
"Activate this command by typing \"/{{COMMAND}}\" to chat input.": "",
"Active": "",
"active sessions": "active sessions",
"Active Users": "",
"Activity": "",
"Activity over time": "Activity over time",
"Add": "",
"Add a model ID": "",
"Add a preference, fact, or instruction about you": "",
@ -241,6 +245,7 @@
"Amazing": "",
"an assistant": "",
"Analytics": "",
"Analytics view": "Analytics view",
"Analyzed": "",
"Analyzing...": "",
"and": "",
@ -361,6 +366,7 @@
"Azure OpenAI": "",
"Back": "",
"Back to files": "",
"Back to sessions": "Back to sessions",
"Back to sign in": "",
"Background Image": "",
"Background image must be at most 25 megapixels.": "",
@ -406,9 +412,11 @@
"Call feature is not supported when using Web STT engine": "",
"Call in progress": "",
"Call mode": "",
"Calls": "Calls",
"Camera": "",
"Cancel": "",
"Cancel download of {{model}}": "",
"Cancelled": "Cancelled",
"Cannot create an empty note.": "",
"Cannot delete the production version": "",
"Capture": "",
@ -516,6 +524,7 @@
"Close comment": "",
"Close Configure Connection Modal": "",
"Close embed": "",
"Close execution details": "Close execution details",
"Close feedback": "",
"Close modal": "",
"Close Modal": "",
@ -528,6 +537,7 @@
"Code Editor": "",
"Code execution": "",
"Code formatted successfully": "",
"Code interpreter": "Code interpreter",
"Code Interpreter": "",
"Codes match": "",
"Collaboration channel where people join as members": "",
@ -568,6 +578,7 @@
"Comparing with knowledge base...": "",
"Comparison options": "",
"Comparison reached its time limit; some changes are grouped together.": "",
"Completed": "Completed",
"Completions": "",
"Compress uploaded images before sending or storage.": "",
"Computing checksums ({{count}} files)_one": "",
@ -702,6 +713,7 @@
"Current": "",
"Current branch": "",
"Current Model": "",
"Current page": "Current page",
"Current streak": "",
"Custom": "",
"Custom animation": "",
@ -726,6 +738,7 @@
"Date Modified": "",
"Date range": "",
"Day": "",
"day buckets": "day buckets",
"DD/MM/YYYY": "",
"December": "",
"Decline": "",
@ -1119,6 +1132,7 @@
"Enter Your Username": "",
"Enterprise licenses also include dedicated support, customization options, and more, at a fraction of the cost of building and maintaining this stack internally.": "",
"Enterprise licensing": "",
"Entire filtered range": "Entire filtered range",
"Entra ID": "",
"Environment Variables": "",
"Ephemeral": "",
@ -1134,6 +1148,7 @@
"Error uploading file: {{error}}": "",
"Error: A model with the ID '{{modelId}}' already exists. Please select a different ID to proceed.": "",
"Error: Model ID cannot be empty. Please enter a valid ID to proceed.": "",
"Errors": "Errors",
"Evaluations": "",
"Event": "",
"Event created": "",
@ -1160,6 +1175,8 @@
"Exclude": "",
"Execute code for analysis": "",
"Executing {{NAME}}...": "",
"Execution item details": "Execution item details",
"Execution trace": "Execution trace",
"Expand": "",
"Expand {{name}}": "",
"Expand input": "",
@ -1191,6 +1208,7 @@
"Extract action items from this note.": "",
"Extracted text lines": "",
"Extracting text and comparing…": "",
"failed": "failed",
"Failed": "",
"Failed to add file.": "",
"Failed to add members": "",
@ -1261,6 +1279,7 @@
"Failed to upload avatar.": "",
"Failed to upload background image.": "",
"Failed to upload file.": "",
"Failed tool calls": "Failed tool calls",
"Fast": "",
"Features Permissions": "",
"February": "",
@ -1302,6 +1321,7 @@
"Filter is now globally enabled": "",
"Filters": "",
"Fingerprint spoofing detected: Unable to use initials as avatar. Defaulting to default profile image.": "",
"First to last saved message, including idle time": "First to last saved message, including idle time",
"Focus Chat Input": "",
"Folder": "",
"Folder Background Image": "",
@ -1418,6 +1438,7 @@
"Hide from Sidebar": "",
"Hide Hidden Files": "",
"Hide Model": "",
"Hide sub-agents": "Hide sub-agents",
"Hide whitespace": "",
"High": "",
"History": "",
@ -1470,6 +1491,7 @@
"Imported automations successfully": "",
"Imported notes successfully": "",
"Importing...": "",
"In progress": "In progress",
"Inactive": "",
"Include": "",
"Include the current directory in tool instructions.": "",
@ -1552,6 +1574,7 @@
"Last 30 days": "",
"Last 7 days": "",
"Last 90 days": "",
"Last active": "Last active",
"Last Active": "",
"Last Modified": "",
"Last reply": "",
@ -1610,7 +1633,9 @@
"Loading more results": "",
"Loading policy...": "",
"Loading release notes...": "",
"Loading sessions": "Loading sessions",
"Loading tools...": "",
"Loading trace": "Loading trace",
"Loading...": "",
"local": "",
"Local": "",
@ -1619,6 +1644,7 @@
"Location access not allowed": "",
"Location unavailable": "",
"Longest active chat": "",
"Longest span": "Longest span",
"Longest streak": "",
"Lost": "",
"Low": "",
@ -1674,6 +1700,7 @@
"Message rating should be enabled to use this feature": "",
"Message share": "",
"Message text...": "",
"Message time, then saved output order. Includes branches. Dashed lines mean timing was not logged.": "Message time, then saved output order. Includes branches. Dashed lines mean timing was not logged.",
"messages": "",
"Messages": "",
"Messages are end-to-end encrypted and aren’t saved.": "",
@ -1752,6 +1779,9 @@
"More Concise": "",
"More options": "",
"More Options": "",
"Most response errors": "Most response errors",
"Most responses": "Most responses",
"Most tokens": "Most tokens",
"Move": "",
"Move to top level": "Move to top level",
"Moved {{name}}": "",
@ -1799,6 +1829,8 @@
"Next month": "",
"Next page": "",
"Next run": "",
"Next sessions": "Next sessions",
"Next trace items": "Next trace items",
"Next version": "",
"No": "",
"No access grants. Private to you.": "",
@ -1854,6 +1886,7 @@
"No matching scopes.": "",
"No model data": "",
"No model IDs": "",
"No model recorded": "No model recorded",
"No model usage found": "",
"No models accessible": "",
"No models available": "",
@ -1874,9 +1907,12 @@
"No results": "",
"No results found": "",
"No runs yet": "",
"No saved items match this filter.": "No saved items match this filter.",
"No saved payload": "No saved payload",
"No scopes requested.": "",
"No search query generated": "",
"No servers detected": "",
"No sessions match these filters.": "No sessions match these filters.",
"No skills found": "",
"No source available": "",
"No sources found": "",
@ -1885,6 +1921,7 @@
"No terminal connections configured.": "",
"No terminal servers available": "No terminal servers available",
"No text differences": "",
"No tool calls saved for this session.": "No tool calls saved for this session.",
"No tool server connections configured.": "",
"No tools accessible": "",
"No tools found": "",
@ -1899,6 +1936,8 @@
"Not configured": "",
"Not factually correct": "",
"Not helpful": "",
"Not logged": "Not logged",
"Not recorded": "Not recorded",
"Not Registered": "",
"Not scheduled": "",
"Note": "",
@ -1929,6 +1968,7 @@
"Omit": "",
"On": "",
"Once": "",
"One session per chat. Counts cover the selected date range; span includes idle time.": "One session per chat. Counts cover the selected date range; span includes idle time.",
"Only active during Voice Mode.": "",
"Only active when \"Paste Large Text as File\" setting is toggled on.": "",
"Only active when a tool call is waiting for approval.": "",
@ -1952,6 +1992,8 @@
"Oops! You're using an unsupported method (frontend only). Please serve the WebUI from the backend.": "",
"Open": "",
"Open automation": "",
"Open chat": "Open chat",
"Open chat for full content": "Open chat for full content",
"Open create menu": "",
"Open file": "",
"Open Folder": "",
@ -2091,6 +2133,7 @@
"Preview failed": "",
"Preview gesture": "",
"Preview not available": "",
"Preview shortened. Open the chat for full content.": "Preview shortened. Open the chat for full content.",
"Previous": "",
"Previous 30 days": "",
"Previous 7 days": "",
@ -2098,6 +2141,8 @@
"Previous message": "",
"Previous month": "",
"Previous page": "",
"Previous sessions": "Previous sessions",
"Previous trace items": "Previous trace items",
"Previous version": "",
"Private": "",
"Private conversation between selected users": "",
@ -2147,17 +2192,20 @@
"Realtime": "",
"Realtime Voice": "",
"Reason": "",
"Reasoning": "Reasoning",
"Reasoning text...": "",
"Rebuild knowledge file, knowledge search, and memory vectors using the current embedding model.": "",
"Receives matching events across the instance, including system/config events and events associated with any user.": "",
"Receives matching events that are not associated with a user.": "",
"Receives matching user-associated events only when the actor, user subject, or user data matches these users or current group members. System/config events are not sent.": "",
"Recent activity": "Recent activity",
"Recently Used": "",
"Recommended": "",
"Reconnect": "",
"Reconnected": "",
"Record": "",
"Record voice": "",
"Recorded duration · logarithmic scale": "Recorded duration · logarithmic scale",
"Recover your authenticator": "",
"Recovery code": "",
"Redirecting you to Open WebUI Community": "",
@ -2236,8 +2284,13 @@
"Resolved": "",
"Response": "",
"Response complete": "",
"response errors": "response errors",
"Response duration": "Response duration",
"Response errors": "Response errors",
"Response notifications cannot be activated as the website permissions have been denied. Please visit your browser settings to grant the necessary access.": "",
"Responses": "",
"responses with input and output tokens": "responses with input and output tokens",
"responses with recorded usage": "responses with recorded usage",
"Restart": "",
"Restricted": "",
"Result": "",
@ -2281,6 +2334,8 @@
"Save your changes before continuing?": "",
"Save your recovery codes": "",
"Saved": "",
"Saved execution sequence": "Saved execution sequence",
"Saved item": "Saved item",
"Saving approves the updated app identity and selected scopes.": "Saving approves the updated app identity and selected scopes.",
"Saving...": "",
"Scan the QR code, then enter the six-digit code from your authenticator app.": "",
@ -2326,6 +2381,8 @@
"Search Prompts": "",
"Search results": "",
"Search scopes": "",
"Search sessions": "Search sessions",
"Search sessions, users or folders": "Search sessions, users or folders",
"Search skills": "",
"Search Skills": "",
"Search the internet": "",
@ -2414,7 +2471,11 @@
"Service Account": "",
"Services": "",
"Session": "",
"Session details": "Session details",
"Session expired. Please sign in again.": "",
"Session signals": "Session signals",
"Sessions": "Sessions",
"Sessions can be active in more than one bucket.": "Sessions can be active in more than one bucket.",
"Set a local zoom level for the app interface.": "",
"Set as default": "",
"Set as Pinned Model": "",
@ -3641,7 +3702,9 @@
"Sonar Reasoning Pro": "",
"Sort": "",
"Sort by": "",
"Sort sessions": "Sort sessions",
"Source": "",
"Span": "Span",
"Speaking": "",
"Specific users or groups": "",
"Speech recognition error: {{error}}": "",
@ -3679,6 +3742,7 @@
"Streamable HTTP": "",
"Strikethrough": "",
"Su_day_of_week": "",
"Sub-agent": "Sub-agent",
"Submit": "",
"Submit answers": "",
"Submit question": "",
@ -3841,10 +3905,14 @@
"Token activity": "",
"Token counts are estimates and may not reflect actual API usage": "",
"Token share": "",
"Token usage not recorded": "Token usage not recorded",
"tokens": "",
"Tokens": "",
"Too verbose": "",
"tool": "",
"Tool call": "Tool call",
"Tool calls": "Tool calls",
"tool calls with a saved final status": "tool calls with a saved final status",
"Tool created successfully": "",
"Tool deleted successfully": "",
"Tool Description": "",
@ -3853,7 +3921,9 @@
"tool loops per sub-agent": "",
"Tool Menu": "",
"Tool Name": "",
"Tool outcomes": "Tool outcomes",
"Tool Permissions": "",
"Tool result": "Tool result",
"Tool Servers": "",
"Tool updated successfully": "",
"Tools": "",
@ -3862,10 +3932,13 @@
"Tools have a function calling system that allows arbitrary code execution.": "",
"Tools Public Sharing": "",
"Tools Sharing": "",
"Tools used in this session": "Tools used in this session",
"Top": "",
"Top sessions": "Top sessions",
"Total": "",
"Total chats": "",
"Total Tokens": "",
"Trace filter": "Trace filter",
"Transformers": "",
"Translation": "",
"Translation key": "",
@ -3888,6 +3961,9 @@
"Ultra-fast": "",
"Unable to copy link": "",
"Unable to load analytics. Please try again.": "",
"Unable to load execution items.": "Unable to load execution items.",
"Unable to load session.": "Unable to load session.",
"Unable to load sessions.": "Unable to load sessions.",
"Unable to load tools": "",
"Unarchive": "",
"Unarchive Chat": "",
@ -3911,6 +3987,7 @@
"Unloads {{FROM_NOW}}": "",
"Unmute": "",
"Unmute to continue": "",
"Unnamed tool": "Unnamed tool",
"Unpin": "",
"Unpin from Sidebar": "",
"Unread": "",
@ -3923,6 +4000,7 @@
"Unsupported input format": "",
"Untagged": "",
"Untitled": "",
"Untitled chat": "Untitled chat",
"Update": "",
"Update All Models": "",
"Update and Copy Link": "",
@ -4153,5 +4231,47 @@
"YouTube": "",
"YouTube video player": "",
"Zoom in": "",
"Zoom out": ""
"Zoom out": "",
"Recorded tokens": "Recorded tokens",
"p95 tool latency": "p95 tool latency",
"calls with recorded timing": "calls with recorded timing",
"rejected": "rejected",
"pending or unknown": "pending or unknown",
"Recorded duration": "Recorded duration",
"Saved message order, including branches. Copied history is excluded. Unknown timing is not estimated.": "Saved message order, including branches. Copied history is excluded. Unknown timing is not estimated.",
"Redacted preview. Open the chat for full content.": "Redacted preview. Open the chat for full content.",
"Close session details": "Close session details",
"Cache read": "Cache read",
"Cache write": "Cache write",
"Coverage": "Coverage",
"Session summary": "Session summary",
"Arguments": "Arguments",
"Rejected": "Rejected",
"Saved operation details": "Saved operation details",
"Recorded tokens by response": "Recorded tokens by response",
"Partial usage": "Partial usage",
"complete": "complete",
"Response order": "Response order",
"Select a bar to jump to its saved responses. Grouped bars sum consecutive responses.": "Select a bar to jump to its saved responses. Grouped bars sum consecutive responses.",
"- usage not recorded": "- usage not recorded",
"from first timed operation": "from first timed operation",
"Execution time from first timed operation": "Execution time from first timed operation",
"Sessions by recorded token usage": "Sessions by recorded token usage",
"All sessions": "All sessions",
"Select a range to filter sessions. Partial usage is included.": "Select a range to filter sessions. Partial usage is included.",
"sessions without recorded usage": "sessions without recorded usage",
"session without recorded usage": "session without recorded usage",
"Session options": "Session options",
"Execution timeline": "Execution timeline",
"Time from first timed operation on this page.": "Time from first timed operation on this page.",
"Start/end times not recorded; bars compare durations only.": "Start/end times not recorded; bars compare durations only.",
"items without recorded start/end times": "items without recorded start/end times",
"items without recorded durations": "items without recorded durations",
"Timing not recorded for this page.": "Timing not recorded for this page.",
"Session visualization": "Session visualization",
"Timeline": "Timeline",
"Recorded sequence": "Recorded sequence",
"Saved order": "Saved order",
"Saved order only; spacing does not represent elapsed time.": "Saved order only; spacing does not represent elapsed time.",
"Count": "Count"
}