|
| 1 | +import { eq } from "drizzle-orm"; |
| 2 | +import { Hono } from "hono"; |
| 3 | +import { describe, expect, test } from "vitest"; |
| 4 | +import { createJuniorApi } from "@/api"; |
| 5 | +import { conversationUsageCostExpr } from "@/api/conversations/aggregate"; |
| 6 | +import type { JuniorApiEnv } from "@/api/route"; |
| 7 | +import { |
| 8 | + automationExecutionListSchema, |
| 9 | + automationSummarySchema, |
| 10 | +} from "@/api/schema/automation"; |
| 11 | +import { recordAutomationExecution } from "@/chat/automations/execution-stats"; |
| 12 | +import { migrateSchema } from "@/chat/conversations/sql/migrations"; |
| 13 | +import { createSqlStore } from "@/chat/conversations/sql/store"; |
| 14 | +import { |
| 15 | + resolveViewerUser, |
| 16 | + resolveViewerUserFromSql, |
| 17 | +} from "@/chat/plugins/viewer"; |
| 18 | +import { saveScheduledAutomation } from "@/chat/scheduled-automations/tasks"; |
| 19 | +import { juniorAutomationRuns } from "@/db/schema/automation-runs"; |
| 20 | +import { juniorConversations } from "@/db/schema/conversations"; |
| 21 | +import { createConfiguredJuniorSqlFixture } from "../../fixtures/sql"; |
| 22 | + |
| 23 | +function authenticatedApi(email: string) { |
| 24 | + const app = new Hono<JuniorApiEnv>(); |
| 25 | + app.use("*", async (context, next) => { |
| 26 | + const viewer = await resolveViewerUser(email); |
| 27 | + if (!viewer) throw new Error(`missing viewer for ${email}`); |
| 28 | + context.set("viewer", viewer); |
| 29 | + await next(); |
| 30 | + }); |
| 31 | + app.route("/", createJuniorApi()); |
| 32 | + return app; |
| 33 | +} |
| 34 | + |
| 35 | +describe("Automation run cost", () => { |
| 36 | + test("follows usage that a run's Conversation gains after the run", async () => { |
| 37 | + const fixture = createConfiguredJuniorSqlFixture(); |
| 38 | + const conversationStore = createSqlStore(fixture.sql); |
| 39 | + try { |
| 40 | + await migrateSchema(fixture.sql); |
| 41 | + const actor = { |
| 42 | + |
| 43 | + platform: "slack" as const, |
| 44 | + slackUserId: "U123", |
| 45 | + teamId: "T123", |
| 46 | + }; |
| 47 | + const destination = { |
| 48 | + channelId: "C123", |
| 49 | + platform: "slack" as const, |
| 50 | + teamId: "T123", |
| 51 | + }; |
| 52 | + const runConversationId = "agent-dispatch:cost-run"; |
| 53 | + await conversationStore.recordActivity({ |
| 54 | + actor, |
| 55 | + conversationId: runConversationId, |
| 56 | + destination, |
| 57 | + title: "Automation run", |
| 58 | + visibility: "public", |
| 59 | + }); |
| 60 | + const user = await resolveViewerUserFromSql( |
| 61 | + fixture.sql.db(), |
| 62 | + |
| 63 | + ); |
| 64 | + const identity = user!.identities.find( |
| 65 | + (candidate) => candidate.provider === "slack", |
| 66 | + )!; |
| 67 | + const nowMs = Date.now(); |
| 68 | + const runAtMs = nowMs - 60 * 60 * 1000; |
| 69 | + await saveScheduledAutomation(fixture.sql.db(), { |
| 70 | + id: "sched_cost", |
| 71 | + conversationAccess: { audience: "channel", visibility: "public" }, |
| 72 | + createdAtMs: nowMs - 2 * 60 * 60 * 1000, |
| 73 | + createdBy: { slackUserId: "U123" }, |
| 74 | + creatorIdentityId: identity.id, |
| 75 | + credentialMode: "creator", |
| 76 | + destination, |
| 77 | + nextRunAtMs: nowMs + 60_000, |
| 78 | + outcomes: [], |
| 79 | + schedule: { |
| 80 | + description: "", |
| 81 | + kind: "recurring", |
| 82 | + recurrence: { |
| 83 | + frequency: "daily", |
| 84 | + interval: 1, |
| 85 | + startDate: new Date(nowMs).toISOString().slice(0, 10), |
| 86 | + time: { hour: 12, minute: 0 }, |
| 87 | + }, |
| 88 | + timezone: "UTC", |
| 89 | + }, |
| 90 | + status: "active", |
| 91 | + task: { kind: "instruction", instruction: "Post the daily digest." }, |
| 92 | + updatedAtMs: nowMs, |
| 93 | + }); |
| 94 | + const recordTurn = async (runId: string, costUsd: number) => |
| 95 | + await conversationStore.recordExecution({ |
| 96 | + conversationId: runConversationId, |
| 97 | + createdAtMs: runAtMs, |
| 98 | + execution: { runId, status: "idle", updatedAtMs: Date.now() }, |
| 99 | + lastActivityAtMs: Date.now(), |
| 100 | + metrics: { |
| 101 | + durationMs: 1_000, |
| 102 | + usage: { cost: { total: costUsd }, totalTokens: 100 }, |
| 103 | + }, |
| 104 | + updatedAtMs: Date.now(), |
| 105 | + }); |
| 106 | + const api = authenticatedApi("[email protected]"); |
| 107 | + const readCost = async () => { |
| 108 | + const summary = automationSummarySchema.parse( |
| 109 | + await ( |
| 110 | + await api.request("http://localhost/api/automations/sched_cost") |
| 111 | + ).json(), |
| 112 | + ); |
| 113 | + const executions = automationExecutionListSchema.parse( |
| 114 | + await ( |
| 115 | + await api.request( |
| 116 | + "http://localhost/api/automations/sched_cost/executions", |
| 117 | + ) |
| 118 | + ).json(), |
| 119 | + ); |
| 120 | + const day = new Date(runAtMs).toISOString().slice(0, 10); |
| 121 | + return { |
| 122 | + day: executions.executionDays.find((entry) => entry.date === day) |
| 123 | + ?.costUsd, |
| 124 | + total: summary.totalCostUsd, |
| 125 | + week: summary.costUsd[7], |
| 126 | + }; |
| 127 | + }; |
| 128 | + |
| 129 | + // The run's Turn writes usage before the run records its outcome. |
| 130 | + await recordTurn("turn-1", 0.2); |
| 131 | + await recordAutomationExecution("sched_cost", { |
| 132 | + conversationId: runConversationId, |
| 133 | + executionId: "cost-run", |
| 134 | + nowMs: runAtMs, |
| 135 | + status: "completed", |
| 136 | + }); |
| 137 | + expect(await readCost()).toEqual({ day: 0.2, total: 0.2, week: 0.2 }); |
| 138 | + |
| 139 | + // A follow-up Turn in the run's Conversation adds usage later. |
| 140 | + await recordTurn("turn-2", 0.05); |
| 141 | + expect(await readCost()).toEqual({ day: 0.25, total: 0.25, week: 0.25 }); |
| 142 | + |
| 143 | + // Each stored run cost equals the cost of its Conversation. |
| 144 | + const [parity] = await fixture.sql |
| 145 | + .db() |
| 146 | + .select({ |
| 147 | + conversation: conversationUsageCostExpr(juniorConversations.usage), |
| 148 | + run: juniorAutomationRuns.costUsd, |
| 149 | + }) |
| 150 | + .from(juniorAutomationRuns) |
| 151 | + .innerJoin( |
| 152 | + juniorConversations, |
| 153 | + eq( |
| 154 | + juniorConversations.conversationId, |
| 155 | + juniorAutomationRuns.conversationId, |
| 156 | + ), |
| 157 | + ) |
| 158 | + .where(eq(juniorAutomationRuns.id, "cost-run")); |
| 159 | + expect(parity!.run).toBe(parity!.conversation); |
| 160 | + } finally { |
| 161 | + await fixture.close(); |
| 162 | + } |
| 163 | + }); |
| 164 | +}); |
0 commit comments