import { collectConversationLinksWithDiagnostics, conversationLinkLocator, markdownLinkTargets, type ConversationLinkDiagnostics, type RenderedConversationLink } from "../chat-rendered-links.js"; import { expect } from "@playwright/test"; import type { ChatCatalogContext } from "../chat-catalog-contract.js"; import type { ChatRun } from "../chat-flow.js"; export interface Entity { id: string; companyId?: string; name?: string; title?: string; description?: string | null; identifier?: string; urlKey?: string; status?: string; priority?: string; assigneeAgentId?: string | null; projectId?: string | null; parentId?: string | null; goalId?: string | null; goalIds?: string[]; level?: string; ownerAgentId?: string | null; archivedAt?: string | null; key?: string; body?: string; latestRevisionId?: string; latestRevisionNumber?: number; createdByAgentId?: string | null; updatedByAgentId?: string | null; createdByRunId?: string | null; createdAt?: string; updatedAt?: string; authorAgentId?: string | null; authorUserId?: string | null; issueId?: string; action?: string; agentId?: string | null; actorId?: string; actorType?: string; entityId?: string; documentId?: string; originalRevisionId?: string | null; currentRevisionId?: string | null; resolvedByAgentId?: string | null; selectedText?: string; resolvedAt?: string | null; details?: Record; } export interface InternalObservation { scenarioId: string; origin: string; companyId: string; leadId: string; state: Record; tasks: Entity[]; projects: Entity[]; goals: Entity[]; comments: Entity[]; renderedLinkEvidence?: RenderedConversationLink[]; unservedLinkEvidence?: Array; linkDiagnostics?: ConversationLinkDiagnostics; activity: Entity[]; annotations?: Entity[]; agents?: Entity[]; documents: Entity[]; revisions: Entity[]; reply: string; links: string[]; humanQueries: string[]; runs: ChatRun[]; } export function entity(state: Record, key: string): Entity { const value = state[key]; if (!value || typeof value !== "object" || typeof (value as Entity).id !== "string") throw new Error(`Missing fixture ${key}`); return value as Entity; } export const companyPath = (ctx: ChatCatalogContext) => `/api/companies/${ctx.input.fixtures.company.id}`; export async function project(ctx: ChatCatalogContext, name = "Launch", extra: Record = {}) { return ctx.input.api.post(`${companyPath(ctx)}/projects`, { name, ...extra }); } export async function task(ctx: ChatCatalogContext, title: string, projectId: string, extra: Record = {}) { // Backlog fixtures never start provider work. These are prerequisite records, not requested outcomes. return ctx.input.api.post(`${companyPath(ctx)}/issues`, { title, projectId, status: "backlog", priority: "medium", ...extra }); } export async function goal(ctx: ChatCatalogContext, title: string, extra: Record = {}) { return ctx.input.api.post(`${companyPath(ctx)}/goals`, { title, level: "company", ownerAgentId: ctx.input.fixtures.agent.id, ...extra }); } export async function putDocument(ctx: ChatCatalogContext, issueId: string, body: string, baseRevisionId: string | null = null) { return ctx.input.api.putSensitive(`/api/issues/${issueId}/documents/plan`, { title: "Website implementation plan", format: "markdown", body, baseRevisionId, }); } export async function observeInternal(ctx: ChatCatalogContext, state: Record): Promise { await ctx.refreshIssue(); const { api, fixtures } = ctx.input; const [tasks, projects, goals, runs] = await Promise.all([ api.getRunObservation(`${companyPath(ctx)}/issues?includeAgentCreatedTasks=true&limit=1000`), api.get(`${companyPath(ctx)}/projects?includeArchived=true`), api.get(`${companyPath(ctx)}/goals`), ctx.allRuns(), ]); const source = ctx.issue(); const chat = source ? await api.get(`/api/issues/${source.id}/comments?order=asc`) : []; const replies = chat.filter(row => row.authorAgentId === fixtures.agent.id && runs.some(run => run.id === row.createdByRunId)); const target = state.task ? entity(state, "task") : undefined; const comments = target ? await api.get(`/api/issues/${target.id}/comments?order=asc`) : []; const companyActivity = await api.getRunObservation(`${companyPath(ctx)}/activity?limit=1000`); const taskActivity = target ? await api.get(`/api/issues/${target.id}/activity`) : []; const activity = [...new Map([...companyActivity, ...taskActivity].map(row => [row.id, row])).values()]; const collected = source ? await collectConversationLinksWithDiagnostics(ctx.input.page, { origin: api.baseURL, companyId: fixtures.company.id, companyPrefix: fixtures.company.issuePrefix, sourceId: source.id, leadId: fixtures.agent.id, comments: chat, runs, projects, activity, }) : { links: [] }; const renderedLinkEvidence = collected.links; const links = [...new Set(renderedLinkEvidence.map(link => link.href))]; const documents: Entity[] = []; const revisions: Entity[] = []; if (target) { for (const summary of await api.get(`/api/issues/${target.id}/documents`)) { const endpoint = `/api/issues/${target.id}/documents/${encodeURIComponent(summary.key!)}`; documents.push(await api.get(endpoint)); revisions.push(...await api.get(`${endpoint}/revisions`)); } } return { scenarioId: ctx.scenario.id, origin: api.baseURL, companyId: fixtures.company.id, leadId: fixtures.agent.id, state, tasks: tasks.filter(row => row.id !== source?.id), projects, goals, runs, comments, activity, documents, revisions, renderedLinkEvidence, ...("rejected" in collected && collected.rejected ? { unservedLinkEvidence: collected.rejected } : {}), ...(collected.diagnostics ? { linkDiagnostics: collected.diagnostics } : {}), humanQueries: chat.filter(row => !row.authorAgentId).map(row => row.body ?? ""), reply: replies.map(row => row.body ?? "").join("\n"), links }; } export function hasLink(o: InternalObservation, kind: "issues" | "projects" | "goals", row: Entity): boolean { return o.links.some(href => { try { const url = new URL(href, o.origin); if (url.origin !== new URL(o.origin).origin) return false; const parts = url.pathname.split("/").map(decodeURIComponent); const index = parts.indexOf(kind); const target = parts[index + 1]; return index >= 0 && !!target && [row.id, row.identifier, row.urlKey].filter(Boolean).includes(target); } catch { return false; } }); } /** * Rendered links that the saved reply itself carries: a Markdown link target in a saved reply body, or a * task identifier written in that body, which the conversation links. A chat bubble can also render * prose from the run stream that was never saved; links found only there are not part of the reply that * history, notifications and other channels deliver. Only link structure is matched, never wording. */ export function savedReplyLinks(o: Pick): string[] { const location = (href: string) => { try { const url = new URL(href, o.origin); return url.origin === new URL(o.origin).origin ? decodeURIComponent(url.pathname).replace(/\/+$/, "") + url.search : url.href; } catch { return null; } }; const targets = new Set(markdownLinkTargets(o.reply).map(location)); return o.links.filter(href => { const at = location(href); if (!at) return false; if (targets.has(at)) return true; const parts = at.split("?")[0]!.split("/"); const identifier = parts[parts.indexOf("issues") + 1]; return parts.includes("issues") && !!identifier && /^[A-Za-z][A-Za-z0-9]*-\d+$/.test(identifier) && new RegExp(`(? = []; return { add(id: string, passed: boolean, detail: string) { rows.push({ id, passed, detail }); }, result() { return { passed: rows.length > 0 && rows.every(row => row.passed), checks: rows }; } }; } export function sameTask(before: Entity, after: Entity | undefined, except: readonly string[] = []) { return !!after && ["id", "companyId", "title", "description", "projectId", "status", "priority", "assigneeAgentId", "goalId"] .filter(key => !except.includes(key)).every(key => before[key as keyof Entity] === after[key as keyof Entity]); } /** Follow the exact rendered chat links, check the real result view, and return to the source. */ export async function verifyInternalResult(ctx: ChatCatalogContext, _state: Record, value: unknown, remainingBudget?: () => number) { const options = () => remainingBudget ? { timeout: remainingBudget() } : {}; const o = observation(value); if (!o) throw new Error("Result navigation requires a complete observation"); const sourceUrl = ctx.input.page.url(); const candidates: Array<{ kind: "issues" | "projects" | "goals"; row: Entity }> = [ ...o.tasks.map(row => ({ kind: "issues" as const, row })), ...o.projects.map(row => ({ kind: "projects" as const, row })), ...o.goals.map(row => ({ kind: "goals" as const, row })), ].filter(target => hasLink(o, target.kind, target.row)); if (!candidates.length) throw new Error("No independently matched result link was rendered"); for (const { kind, row } of candidates) { const href = o.links.find(link => hasLink({ ...o, links: [link] }, kind, row))!; const link = internalResultLink(ctx, o, href).first(); await expect(link).toBeVisible(options()); await link.click(options()); await ctx.input.page.waitForURL(url => { const parts = url.pathname.split("/").map(decodeURIComponent); const at = parts.indexOf(kind); return at >= 0 && [row.id, row.identifier, row.urlKey].includes(parts[at + 1]); }, options()); await expect(ctx.input.page.getByRole("heading", { name: row.title ?? row.name!, exact: true }).first()).toBeVisible(options()); await ctx.input.evidence(`chat-catalog-opened-${kind}-${row.id}.json`, { id: row.id, kind, url: ctx.input.page.url(), title: row.title ?? row.name }); await ctx.input.page.goto(sourceUrl, { waitUntil: "domcontentloaded", ...options() }); await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible(options()); remainingBudget?.(); } } export function internalResultLink(ctx: ChatCatalogContext, o: InternalObservation, href: string) { const receipt = o.renderedLinkEvidence?.find(link => link.href === href); if (!receipt) throw new Error("Result navigation requires current-conversation rendered-link custody"); return conversationLinkLocator(ctx.input.page, receipt); }