mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 05:54:44 +00:00
* refactor(agent)!: migrate sessions to Pi Durable Replace patched AgentHarness storage with per-session SQLite and PostgreSQL commit mirroring. Migrate legacy history automatically and run agent queues with the main server. BREAKING CHANGE: Remove standalone agent workers and return native Pi entry records from chat history APIs. * fix(agent): constrain session log dialog scrolling Keep the header visible and wrap long output while log entries and expanded records scroll within the dialog. Cover desktop and narrow viewports through the dashboard Sessions flow. * fix(agent): hide entry IDs from session log card headers Retain internal entry IDs in expanded raw records for debugging. Verify that card headers omit the IDs while raw JSON preserves them. * test(e2e): handle browser wheel limits in session log checks Verify that a normal wheel event moves the viewport before explicitly scrolling to the final record. Keep the dialog bounds, fixed header, wrapping, and expanded-record assertions. * fix(agent): select model providers without inheriting unrelated auth * fix(webui): prevent resize feedback when toggling agent panel * test(agent): reproduce concurrent comment session races * fix(agent): serialize comment sessions and deduplicate history * docs(changelog): consolidate Pi Durable changes into one entry
265 lines
7.7 KiB
TypeScript
265 lines
7.7 KiB
TypeScript
import { prisma, Prisma } from '@shumai/db'
|
|
import type { TeamUsageStatsResponse, Timeframe } from '@shumai/dtos'
|
|
import { HTTPException } from 'hono/http-exception'
|
|
|
|
export interface RecordUsageParams {
|
|
teamId: string
|
|
userId?: string | null
|
|
inputTokens: number
|
|
outputTokens: number
|
|
cacheReadTokens: number
|
|
totalTokens: number
|
|
cost: number
|
|
timestamp?: Date
|
|
}
|
|
|
|
export interface GetTeamUsageStatsParams {
|
|
teamId: string
|
|
timeframe: Timeframe
|
|
userId?: string
|
|
}
|
|
|
|
export class AiUsageService {
|
|
constructor(private readonly prismaClient: Prisma.TransactionClient = prisma) {}
|
|
private async incrementBucket(params: {
|
|
teamId: string
|
|
userId: string | null
|
|
periodStart: Date
|
|
inputTokens: number
|
|
outputTokens: number
|
|
cacheReadTokens: number
|
|
totalTokens: number
|
|
cost: number
|
|
}): Promise<void> {
|
|
if (params.userId !== null) {
|
|
await this.prismaClient.aiUsage.upsert({
|
|
where: {
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
teamId_userId_periodStart: {
|
|
teamId: params.teamId,
|
|
userId: params.userId,
|
|
periodStart: params.periodStart,
|
|
},
|
|
},
|
|
update: {
|
|
inputTokens: { increment: params.inputTokens },
|
|
outputTokens: { increment: params.outputTokens },
|
|
cacheReadTokens: { increment: params.cacheReadTokens },
|
|
totalTokens: { increment: params.totalTokens },
|
|
cost: { increment: params.cost },
|
|
},
|
|
create: {
|
|
teamId: params.teamId,
|
|
userId: params.userId,
|
|
periodStart: params.periodStart,
|
|
inputTokens: params.inputTokens,
|
|
outputTokens: params.outputTokens,
|
|
cacheReadTokens: params.cacheReadTokens,
|
|
totalTokens: params.totalTokens,
|
|
cost: params.cost,
|
|
},
|
|
})
|
|
} else {
|
|
const existing = await this.prismaClient.aiUsage.findFirst({
|
|
where: {
|
|
teamId: params.teamId,
|
|
userId: null,
|
|
periodStart: params.periodStart,
|
|
},
|
|
})
|
|
|
|
if (existing) {
|
|
await this.prismaClient.aiUsage.update({
|
|
where: { id: existing.id },
|
|
data: {
|
|
inputTokens: { increment: params.inputTokens },
|
|
outputTokens: { increment: params.outputTokens },
|
|
cacheReadTokens: { increment: params.cacheReadTokens },
|
|
totalTokens: { increment: params.totalTokens },
|
|
cost: { increment: params.cost },
|
|
},
|
|
})
|
|
} else {
|
|
try {
|
|
await this.prismaClient.aiUsage.create({
|
|
data: {
|
|
teamId: params.teamId,
|
|
userId: null,
|
|
periodStart: params.periodStart,
|
|
inputTokens: params.inputTokens,
|
|
outputTokens: params.outputTokens,
|
|
cacheReadTokens: params.cacheReadTokens,
|
|
totalTokens: params.totalTokens,
|
|
cost: params.cost,
|
|
},
|
|
})
|
|
} catch (err) {
|
|
if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
|
|
await this.prismaClient.aiUsage.updateMany({
|
|
where: {
|
|
teamId: params.teamId,
|
|
userId: null,
|
|
periodStart: params.periodStart,
|
|
},
|
|
data: {
|
|
inputTokens: { increment: params.inputTokens },
|
|
outputTokens: { increment: params.outputTokens },
|
|
cacheReadTokens: { increment: params.cacheReadTokens },
|
|
totalTokens: { increment: params.totalTokens },
|
|
cost: { increment: params.cost },
|
|
},
|
|
})
|
|
} else {
|
|
throw err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async recordUsage(params: RecordUsageParams): Promise<void> {
|
|
const timestamp = params.timestamp ?? new Date()
|
|
const periodStart = new Date(timestamp)
|
|
periodStart.setMinutes(0, 0, 0)
|
|
|
|
// 1. Update/create Team Total record (userId = null)
|
|
await this.incrementBucket({
|
|
teamId: params.teamId,
|
|
userId: null,
|
|
periodStart,
|
|
inputTokens: params.inputTokens,
|
|
outputTokens: params.outputTokens,
|
|
cacheReadTokens: params.cacheReadTokens,
|
|
totalTokens: params.totalTokens,
|
|
cost: params.cost,
|
|
})
|
|
|
|
// 2. If triggered by a team member, update/create Member Usage record (userId = params.userId)
|
|
if (params.userId) {
|
|
await this.incrementBucket({
|
|
teamId: params.teamId,
|
|
userId: params.userId,
|
|
periodStart,
|
|
inputTokens: params.inputTokens,
|
|
outputTokens: params.outputTokens,
|
|
cacheReadTokens: params.cacheReadTokens,
|
|
totalTokens: params.totalTokens,
|
|
cost: params.cost,
|
|
})
|
|
}
|
|
}
|
|
|
|
async getTeamUsageStats(params: GetTeamUsageStatsParams): Promise<TeamUsageStatsResponse> {
|
|
const now = new Date()
|
|
const since = new Date(now)
|
|
|
|
switch (params.timeframe) {
|
|
case '1h':
|
|
// For 1h, target the current 1h bucket floored to start of current hour
|
|
since.setMinutes(0, 0, 0)
|
|
break
|
|
case '24h':
|
|
since.setDate(since.getDate() - 1)
|
|
since.setMinutes(0, 0, 0)
|
|
break
|
|
case '7d':
|
|
since.setDate(since.getDate() - 7)
|
|
since.setMinutes(0, 0, 0)
|
|
break
|
|
case '30d':
|
|
since.setDate(since.getDate() - 30)
|
|
since.setMinutes(0, 0, 0)
|
|
break
|
|
}
|
|
|
|
if (!params.userId) {
|
|
// Return Team-Level Usage (userId = null)
|
|
const teamRecords = await this.prismaClient.aiUsage.findMany({
|
|
where: {
|
|
teamId: params.teamId,
|
|
userId: null,
|
|
periodStart: { gte: since },
|
|
},
|
|
})
|
|
|
|
let inputTokens = 0
|
|
let outputTokens = 0
|
|
let cacheReadTokens = 0
|
|
let totalTokens = 0
|
|
let cost = 0
|
|
|
|
for (const r of teamRecords) {
|
|
inputTokens += Number(r.inputTokens)
|
|
outputTokens += Number(r.outputTokens)
|
|
cacheReadTokens += Number(r.cacheReadTokens)
|
|
totalTokens += Number(r.totalTokens)
|
|
cost += r.cost
|
|
}
|
|
|
|
return {
|
|
timeframe: params.timeframe,
|
|
team: {
|
|
inputTokens,
|
|
outputTokens,
|
|
cacheReadTokens,
|
|
totalTokens,
|
|
cost: Math.round((cost + Number.EPSILON) * 1000000) / 1000000,
|
|
},
|
|
}
|
|
} else {
|
|
// Return Specific Member Usage
|
|
const teamMember = await prisma.teamMember.findFirst({
|
|
where: {
|
|
teamId: params.teamId,
|
|
userId: params.userId,
|
|
},
|
|
include: { user: true },
|
|
})
|
|
|
|
if (!teamMember) {
|
|
throw new HTTPException(404, { message: 'Team member not found' })
|
|
}
|
|
|
|
const memberRecords = await this.prismaClient.aiUsage.findMany({
|
|
where: {
|
|
teamId: params.teamId,
|
|
userId: params.userId,
|
|
periodStart: { gte: since },
|
|
},
|
|
})
|
|
|
|
let inputTokens = 0
|
|
let outputTokens = 0
|
|
let cacheReadTokens = 0
|
|
let totalTokens = 0
|
|
let cost = 0
|
|
|
|
for (const r of memberRecords) {
|
|
inputTokens += Number(r.inputTokens)
|
|
outputTokens += Number(r.outputTokens)
|
|
cacheReadTokens += Number(r.cacheReadTokens)
|
|
totalTokens += Number(r.totalTokens)
|
|
cost += r.cost
|
|
}
|
|
|
|
return {
|
|
timeframe: params.timeframe,
|
|
member: {
|
|
userId: teamMember.user.id,
|
|
userName: teamMember.user.name,
|
|
userEmail: teamMember.user.email,
|
|
userImage: teamMember.user.image,
|
|
role: teamMember.role,
|
|
inputTokens,
|
|
outputTokens,
|
|
cacheReadTokens,
|
|
totalTokens,
|
|
cost: Math.round((cost + Number.EPSILON) * 1000000) / 1000000,
|
|
},
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export const aiUsageService = new AiUsageService()
|