|
| 1 | +import { |
| 2 | + createChat, |
| 3 | + createDashboardAgentDb, |
| 4 | + getChatMessages, |
| 5 | + getInvestigation, |
| 6 | + listStaleOpenInvestigations, |
| 7 | + settleInvestigationStateAndCloseCard, |
| 8 | + upsertInvestigationRevision, |
| 9 | + type DashboardAgentDb, |
| 10 | + type DashboardAgentDbClient, |
| 11 | +} from "@internal/dashboard-agent-db"; |
| 12 | +import { |
| 13 | + forceSettledInvestigationState, |
| 14 | + investigationStateSchema, |
| 15 | + type InvestigationState, |
| 16 | +} from "@internal/dashboard-agent-contracts"; |
| 17 | +import { postgresTest } from "@internal/testcontainers"; |
| 18 | +import type { PrismaClient } from "@trigger.dev/database"; |
| 19 | +import { readdirSync, readFileSync } from "node:fs"; |
| 20 | +import path from "node:path"; |
| 21 | +import { afterEach, describe, expect } from "vitest"; |
| 22 | + |
| 23 | +/** |
| 24 | + * The write the consented watch investigation closes its card with. |
| 25 | + * |
| 26 | + * The lane has no `onTurnComplete` to hand settlements to, so it closes the card |
| 27 | + * itself. Settling the row and appending the terminal card used to be two operations |
| 28 | + * with the append's error swallowed: the row went terminal, the card never arrived, |
| 29 | + * the stale sweep stopped selecting the row, and the panel kept spinning for ever. |
| 30 | + */ |
| 31 | + |
| 32 | +let agentDb: DashboardAgentDb; |
| 33 | +let agentDbClient: DashboardAgentDbClient | undefined; |
| 34 | + |
| 35 | +/** Replays every migration in order, so a new migration can't leave the suite on a stale schema. */ |
| 36 | +async function applyAgentSchema(prisma: PrismaClient) { |
| 37 | + const folder = path.resolve(__dirname, "../../../internal-packages/dashboard-agent-db/drizzle"); |
| 38 | + for (const name of readdirSync(folder) |
| 39 | + .filter((file) => file.endsWith(".sql")) |
| 40 | + .sort()) { |
| 41 | + const sql = readFileSync(path.join(folder, name), "utf8"); |
| 42 | + for (const statement of sql.split("--> statement-breakpoint")) { |
| 43 | + const trimmed = statement.trim(); |
| 44 | + if (trimmed.length > 0) await prisma.$executeRawUnsafe(trimmed); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +const ORG_ID = "org_watch_card"; |
| 50 | +const USER_ID = "user_watch_card"; |
| 51 | +const PROJECT_REF = "proj_watch_card"; |
| 52 | +const ENV_REF = "env_watch_card"; |
| 53 | +const MESSAGE_ID = "investigate:watch:watch_1:fired:investigate:settled"; |
| 54 | + |
| 55 | +async function boot(prisma: PrismaClient, connectionUri: string, chatId: string) { |
| 56 | + await applyAgentSchema(prisma); |
| 57 | + agentDbClient = createDashboardAgentDb(connectionUri, { max: 2 }); |
| 58 | + agentDb = agentDbClient.db; |
| 59 | + await createChat(agentDb, { id: chatId, organizationId: ORG_ID, userId: USER_ID }); |
| 60 | +} |
| 61 | + |
| 62 | +afterEach(async () => { |
| 63 | + await agentDbClient?.close(); |
| 64 | + agentDbClient = undefined; |
| 65 | +}); |
| 66 | + |
| 67 | +function openState(): InvestigationState { |
| 68 | + return investigationStateSchema.parse({ |
| 69 | + outcome: "in_progress", |
| 70 | + severity: "warn", |
| 71 | + confidence: "low", |
| 72 | + title: "Investigating run_abc123", |
| 73 | + headline: "The run finished with errors. Looking into why.", |
| 74 | + hypotheses: [], |
| 75 | + evidence: [], |
| 76 | + }); |
| 77 | +} |
| 78 | + |
| 79 | +async function seed(chatId: string, state: unknown): Promise<string> { |
| 80 | + const created = await upsertInvestigationRevision(agentDb, { |
| 81 | + chatId, |
| 82 | + projectRef: PROJECT_REF, |
| 83 | + environmentRef: ENV_REF, |
| 84 | + state, |
| 85 | + }); |
| 86 | + if (!created.ok) throw new Error("the fixture investigation wasn't created"); |
| 87 | + return created.id; |
| 88 | +} |
| 89 | + |
| 90 | +async function transcript(chatId: string): Promise<{ id: string; parts: any[] }[]> { |
| 91 | + return (await getChatMessages(agentDb, { |
| 92 | + chatId, |
| 93 | + userId: USER_ID, |
| 94 | + organizationId: ORG_ID, |
| 95 | + })) as { id: string; parts: any[] }[]; |
| 96 | +} |
| 97 | + |
| 98 | +describe("closing a consented watch investigation's card", () => { |
| 99 | + postgresTest( |
| 100 | + "commits the terminal revision and the card together, under the lane's own message id", |
| 101 | + async ({ prisma, postgresContainer }) => { |
| 102 | + const chatId = "chat_watch_card"; |
| 103 | + await boot(prisma, postgresContainer.getConnectionUri(), chatId); |
| 104 | + const id = await seed(chatId, openState()); |
| 105 | + |
| 106 | + const result = await settleInvestigationStateAndCloseCard(agentDb, { |
| 107 | + id, |
| 108 | + chatId, |
| 109 | + projectRef: PROJECT_REF, |
| 110 | + environmentRef: ENV_REF, |
| 111 | + state: forceSettledInvestigationState(openState()), |
| 112 | + messageId: MESSAGE_ID, |
| 113 | + }); |
| 114 | + expect(result).toMatchObject({ ok: true, id, revision: 1, closed: true }); |
| 115 | + |
| 116 | + const stored = await transcript(chatId); |
| 117 | + expect(stored.map((message) => message.id)).toEqual([MESSAGE_ID]); |
| 118 | + expect(stored[0]!.parts[0]!.output.blocks[0]).toMatchObject({ id, revision: 1 }); |
| 119 | + expect(stored[0]!.parts[0]!.output.blocks[0].investigation.outcome).toBe("inconclusive"); |
| 120 | + expect( |
| 121 | + investigationStateSchema.parse((await getInvestigation(agentDb, { id }))?.state).outcome |
| 122 | + ).toBe("inconclusive"); |
| 123 | + |
| 124 | + // The lane dedupes on the action, so a redelivered kick closes nothing twice. |
| 125 | + const again = await settleInvestigationStateAndCloseCard(agentDb, { |
| 126 | + id, |
| 127 | + chatId, |
| 128 | + projectRef: PROJECT_REF, |
| 129 | + environmentRef: ENV_REF, |
| 130 | + state: forceSettledInvestigationState(openState()), |
| 131 | + messageId: MESSAGE_ID, |
| 132 | + }); |
| 133 | + expect(again).toMatchObject({ ok: true, closed: false }); |
| 134 | + expect((await transcript(chatId)).length).toBe(1); |
| 135 | + }, |
| 136 | + 30_000 |
| 137 | + ); |
| 138 | + |
| 139 | + /** |
| 140 | + * The regression. A terminal row with no terminal card must be impossible: if the |
| 141 | + * card can't be written the settle rolls back, so the row stays `in_progress` and the |
| 142 | + * stale sweep still selects it. |
| 143 | + */ |
| 144 | + postgresTest( |
| 145 | + "a card that can't be written rolls the settle back, leaving the row in_progress", |
| 146 | + async ({ prisma, postgresContainer }) => { |
| 147 | + const chatId = "chat_watch_card_fails"; |
| 148 | + await boot(prisma, postgresContainer.getConnectionUri(), chatId); |
| 149 | + const id = await seed(chatId, openState()); |
| 150 | + |
| 151 | + // A state the row accepts but no card can be rendered from, so the delivery half |
| 152 | + // genuinely fails against a real database. |
| 153 | + await expect( |
| 154 | + settleInvestigationStateAndCloseCard(agentDb, { |
| 155 | + id, |
| 156 | + chatId, |
| 157 | + projectRef: PROJECT_REF, |
| 158 | + environmentRef: ENV_REF, |
| 159 | + state: { outcome: "inconclusive" }, |
| 160 | + messageId: MESSAGE_ID, |
| 161 | + }) |
| 162 | + ).rejects.toThrow(/isn't renderable/); |
| 163 | + |
| 164 | + const row = await getInvestigation(agentDb, { id }); |
| 165 | + expect(row?.revision).toBe(0); |
| 166 | + expect((row!.state as { outcome?: string }).outcome).toBe("in_progress"); |
| 167 | + expect(await transcript(chatId)).toEqual([]); |
| 168 | + |
| 169 | + // Still selectable, so the backstop sweep can finish the job. |
| 170 | + const stale = await listStaleOpenInvestigations(agentDb, { |
| 171 | + olderThan: new Date(), |
| 172 | + limit: 10, |
| 173 | + }); |
| 174 | + expect(stale.map((candidate) => candidate.id)).toEqual([id]); |
| 175 | + }, |
| 176 | + 30_000 |
| 177 | + ); |
| 178 | + |
| 179 | + postgresTest( |
| 180 | + "refuses a row that belongs to another project, and writes nothing", |
| 181 | + async ({ prisma, postgresContainer }) => { |
| 182 | + const chatId = "chat_watch_card_tenancy"; |
| 183 | + await boot(prisma, postgresContainer.getConnectionUri(), chatId); |
| 184 | + const id = await seed(chatId, openState()); |
| 185 | + |
| 186 | + expect( |
| 187 | + await settleInvestigationStateAndCloseCard(agentDb, { |
| 188 | + id, |
| 189 | + chatId, |
| 190 | + projectRef: "proj_someone_else", |
| 191 | + environmentRef: ENV_REF, |
| 192 | + state: forceSettledInvestigationState(openState()), |
| 193 | + messageId: MESSAGE_ID, |
| 194 | + }) |
| 195 | + ).toEqual({ ok: false, error: "context_mismatch" }); |
| 196 | + |
| 197 | + expect(await transcript(chatId)).toEqual([]); |
| 198 | + expect((await getInvestigation(agentDb, { id }))?.revision).toBe(0); |
| 199 | + } |
| 200 | + ); |
| 201 | +}); |
0 commit comments