diff --git a/test-companion/src/approved-cases.mjs b/test-companion/src/approved-cases.mjs index 7762dda..7c0c787 100644 --- a/test-companion/src/approved-cases.mjs +++ b/test-companion/src/approved-cases.mjs @@ -10,7 +10,7 @@ * Everything here is pure; main.mjs does the API calls and runs tc. */ import { createHash } from "node:crypto" -import { hasApproverEdits } from "./report.mjs" +import { hasApproverEdits, plain } from "./report.mjs" /** The artifact a generate preview leaves: the cases file plus subject.json naming its repo and commit. */ export const CASES_ARTIFACT = "test-companion-cases" @@ -46,14 +46,6 @@ export function casesDigest(bytes) { return createHash("sha256").update(bytes ?? "").digest("hex") } -// Agent-written text shown in the plan: one line, no Markdown, no @mentions or autolinks. -const plain = (s) => - String(s ?? "") - .replace(/\s+/g, " ") - .trim() - .replace(/[\\`*_{}[\]()<>#+!|~]/g, "\\$&") - .replace(/@/g, "@\u200b") - .replace(/:\/\//g, ":\u200b//") // Agent-written text that may span lines, shown in a code block: nothing in it is Markdown, // a mention or a link. The fence is longer than any run of backticks inside. @@ -253,6 +245,40 @@ export function readCasesDestination(casesText) { return { project, folder } } +/** + * The folder's Test Management page that `tc tm add` reported, or undefined. Only a page of + * exactly that shape is linked: the URL comes from the CLI's output, not from us. + */ +export function tmFolderUrl(url, folderId) { + const u = String(url ?? "") + const folder = String(folderId ?? "") + if (!/^\d{1,20}$/.test(folder)) return undefined + const page = /^https:\/\/[a-z0-9-]+\.browserstack\.com\/projects\/\d{1,20}\/folder\/(\d{1,20})\/test-cases$/.exec(u) + return page && page[1] === folder ? u : undefined +} + +/** "until 2026-11-30" from an artifact's `expires_at`, or "" when it isn't a date. */ +export function keptUntil(expiresAt) { + const day = /^(\d{4}-\d{2}-\d{2})T/.exec(String(expiresAt ?? ""))?.[1] + return day ? `until ${day}` : "" +} + +/** GitHub's download page for one artifact of a run in this repository, or undefined. */ +export function artifactDownloadLink(repo, runId, artifactId) { + const r = String(repo ?? "") + const run = String(runId ?? "") + const artifact = String(artifactId ?? "") + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(r) || !/^\d+$/.test(run) || !/^\d+$/.test(artifact)) return undefined + return `https://github.com/${r}/actions/runs/${run}/artifacts/${artifact}` +} + +// "folder in project", linked to the folder's page when the save reported one. +function whereLinked({ project, folder } = {}, folderUrl, folderId) { + const where = `${plain(folder)} in ${plain(project)}` + const url = tmFolderUrl(folderUrl, folderId) + return url ? `[${where}](${url})` : where +} + /** * The plan run's cases artifact from a `GET .../runs//artifacts` reply, or why there is none. * The run must belong to this repository and have started from it (`repoId`, GitHub's numeric @@ -345,6 +371,7 @@ export function parseTmAddReport(stdout) { return { project: String(report.project ?? ""), folderId: String(report.folderId ?? ""), + folderUrl: String(report.folderUrl ?? ""), created: report.created, failed: Array.isArray(report.failed) ? report.failed : [], skipped: Array.isArray(report.skipped) ? report.skipped : [], @@ -371,8 +398,11 @@ const UNAVAILABLE_WHY = { "lookup-failed": "I couldn't look up the plan's saved cases on GitHub just now", } -/** The reply when the approved cases can't be saved as they are. Never regenerates. */ -export function renderCasesUnavailable(reason, detail) { +/** + * The reply when the approved cases can't be saved as they are. Never regenerates. `download` is + * the plan's cases artifact, given only when those cases are the approved ones. + */ +export function renderCasesUnavailable(reason, detail, { download, until } = {}) { const why = UNAVAILABLE_WHY[reason] ?? "the plan's cases could not be used" const extra = String(detail ?? "").trim() const notInstead = "I have not generated a new set in its place, because that would save cases nobody reviewed." @@ -384,10 +414,12 @@ export function renderCasesUnavailable(reason, detail) { "old-cli": `${notInstead} ${update} Then reply **go** to this plan again; it is still waiting.`, "old-cli-plan": `${notInstead} ${update} Then ask me to **generate** again and approve the fresh plan.`, } + const keep = download ? ["", `You can still [download the approved test cases](${download})${until ? `, kept ${until}` : ""}.`] : [] return [ `I did not save anything: ${why}${extra ? ` (${extra})` : ""}.`, "", next[reason] ?? `${notInstead} Ask me to **generate** again and approve the fresh plan.`, + ...keep, ].join("\n") } @@ -407,12 +439,12 @@ export function browserstackLink(url) { } /** The answer text for an exact save: what was created, with ids, and anything that failed. */ -export function renderExactSave(report, { project, folder } = {}) { +export function renderExactSave(report, destination = {}) { const created = report?.created ?? [] const failed = report?.failed ?? [] const skipped = report?.skipped ?? [] const lines = [] - const where = `${plain(folder)} in ${plain(project)}` + const where = whereLinked(destination, report?.folderUrl, report?.folderId) if (created.length > 0) { lines.push(`Saved the ${created.length} approved test case${created.length === 1 ? "" : "s"} to ${where} exactly as planned; nothing was generated again.`) lines.push("") diff --git a/test-companion/src/main.mjs b/test-companion/src/main.mjs index 2138d8b..574f10d 100644 --- a/test-companion/src/main.mjs +++ b/test-companion/src/main.mjs @@ -38,6 +38,9 @@ import { parseTmAddReport, renderCasesUnavailable, renderExactSave, + tmFolderUrl, + artifactDownloadLink, + keptUntil, exactSaveSummary, exactSaveOutcome, EDITED_GO_NOTE, @@ -1079,7 +1082,8 @@ async function main() { // so it is reported like any other run, which also completes its check. if (proposing && !runDidNotWork(outcome)) { const sha = checkSha(plan.context, summary, env.GITHUB_SHA) - addToJobSummary(renderJobSummary(view)) + const planView = { ...view, proposing: true } + addToJobSummary(renderJobSummary(planView)) const size = describeChangeSize(pull) const sizeNote = size.large ? `> **This is a large change** — ${size.files} files and ${size.lines} changed lines. Trim the list below before replying go if you only want part of it covered.\n\n` @@ -1092,7 +1096,7 @@ async function main() { const isGenerate = (plan.workflow ?? summary.workflow) === "generate" const casesBytes = isGenerate ? readBytes(join(CASES_DIR, CASES_DATA_FILE)) : undefined // The cases get most of the comment; the run's own report above them is kept short. - const summaryShown = casesBytes ? renderSummaryWithin(view, PLAN_SUMMARY_LIMIT) : renderCheckSummary(view) + const summaryShown = casesBytes ? renderSummaryWithin(planView, PLAN_SUMMARY_LIMIT) : renderCheckSummary(planView) const planned = casesBytes ? renderPlannedCases(casesBytes, { maxChars: COMMENT_LIMIT - summaryShown.length - sizeNote.length - PROPOSAL_OVERHEAD }) : undefined @@ -1124,7 +1128,7 @@ async function main() { { build: buildRunId, cases: casesSha256, shown: casesShown }, ), ) - postCheck(outcome, view, sha, [], "in_progress") + postCheck(outcome, planView, sha, [], "in_progress") // A plan's files are attached too: approving a generate plan saves these cases. if (summaryText) setOutput("summary-file", SUMMARY_FILE) if (hasResult) setOutput("result-file", RESULT_FILE) @@ -1806,19 +1810,21 @@ function saveApprovedCases(plan, save, approvalNote) { if (plan.context.pr) postComment(plan.context.pr, { ...view, consumedMarker: spend ? consumedMarker : "" }) process.exit(0) } - const unavailable = (reason, detail) => - finish({ ...base, outcome: OUTCOMES.COULD_NOT_RUN, answer: renderCasesUnavailable(reason, detail) }, false) + const unavailable = (reason, detail, keep = {}) => + finish({ ...base, outcome: OUTCOMES.COULD_NOT_RUN, answer: renderCasesUnavailable(reason, detail, keep) }, false) + // Set once the approved file is confirmed, so an unexpected failure after that still links it. + const kept = {} if (save.mode !== "exact") return unavailable(save.reason) // Anything unexpected is reported too: a plain go must never turn into a new generate run. try { - saveExactly(plan, save, sha, base, finish, unavailable) + saveExactly(plan, save, sha, base, finish, unavailable, kept) } catch (e) { - unavailable("save-failed", redactSecrets(String(e?.message ?? e), secretsNow())) + unavailable("save-failed", redactSecrets(String(e?.message ?? e), secretsNow()), kept) } } -function saveExactly(plan, save, sha, base, finish, unavailable) { +function saveExactly(plan, save, sha, base, finish, unavailable, kept = {}) { // An older CLI has no `tm add --from-file`; say so rather than report a refusal. if (!cliHasTmAddFromFile()) return unavailable("old-cli", String(env.TC_ACTION_CLI_VERSION ?? "").trim()) // A lookup that failed is not "the cases are missing": the plan stays approvable. @@ -1848,9 +1854,12 @@ function saveExactly(plan, save, sha, base, finish, unavailable) { } const unshown = unshownFields(data) if (unshown.length) return unavailable("unshown", unshown.slice(0, 10).join(", ")) + // From here the file is exactly the approved one, so a save that doesn't happen links to it. + kept.download = artifactDownloadLink(REPO, save.runId, picked.artifact?.id) + kept.until = keptUntil(picked.artifact?.expires_at) // The destination comes from the approved file itself, so the cases go where the plan said. const where = readCasesDestination(bytes.toString("utf8")) - if (where.error === "no-destination") return unavailable(missingDestinationReason(subject.cli), subject.cli || undefined) + if (where.error === "no-destination") return unavailable(missingDestinationReason(subject.cli), subject.cli || undefined, kept) if (where.error) return unavailable(where.error) notice(`Test Companion: saving the approved plan's cases from run ${save.runId} to ${where.folder} in ${where.project}.`) @@ -1868,13 +1877,25 @@ function saveExactly(plan, save, sha, base, finish, unavailable) { // Approvable again only when nothing can have been saved. A save that was killed, timed // out or crashed may have saved some, so the plan is used up: a second go could save them twice. if (tmAddStop({ status: r.status, signal: r.signal, errorCode: r.error?.code, stderr }) === "nothing-saved") { - return unavailable("save-failed", why) + return unavailable("save-failed", why, kept) } return finish({ ...base, outcome: OUTCOMES.RUN_BROKE, answer: renderSaveInterrupted(where, why) }, true) } if (report.failed.length > 0) logRedacted("tc tm add", stderr) const { outcome, spend } = exactSaveOutcome(report, OUTCOMES) - finish({ ...base, outcome, summary: { ...base.summary, ...exactSaveSummary(report, where) }, answer: renderExactSave(report, where) }, spend) + const someLost = report.failed.length > 0 + finish( + { + ...base, + outcome, + summary: { ...base.summary, ...exactSaveSummary(report, where) }, + answer: renderExactSave(report, where), + savedToUrl: tmFolderUrl(report.folderUrl, report.folderId), + casesDownloadUrl: someLost ? kept.download : undefined, + casesKeptUntil: someLost ? kept.until : undefined, + }, + spend, + ) } /** The binding a comment is asking for, or the one bound to the event. */ diff --git a/test-companion/src/report.mjs b/test-companion/src/report.mjs index 8551355..840bf72 100644 --- a/test-companion/src/report.mjs +++ b/test-companion/src/report.mjs @@ -8,20 +8,31 @@ const withMark = (outcome) => { return mark ? `${mark} ${outcome}` : String(outcome ?? "") } -/** `[#]()` for the comment that asked for this run; "" unless the URL names a comment. */ -export function requestLink(url) { +/** `[View comment]()` for a comment on this PR; "" unless the URL names a comment. */ +export function requestLink(url, label = "View comment") { const u = String(url ?? "") - const id = /^https:\/\/[^\s()|<>[\]]+#issuecomment-(\d+)$/.exec(u)?.[1] - return id ? `[#${id}](${u})` : "" + return /^https:\/\/[^\s()|<>[\]]+#issuecomment-\d+$/.test(u) ? `[${label}](${u})` : "" } -/** `@ | [#]()`; the pipe is escaped so it stays inside the table cell. */ +/** `@ · [View comment]()`. */ export function askedByCell(askedBy, askedAt) { if (!askedBy) return "" const link = requestLink(askedAt) - return link ? `@${askedBy} \\| ${link}` : `@${askedBy}` + return link ? `@${askedBy} · ${link}` : `@${askedBy}` } +/** + * Text we did not write (agent output, a folder or project name from a file the agent wrote): one + * line, no Markdown, no @mentions or autolinks. Safe inside link text and table cells. + */ +export const plain = (s) => + String(s ?? "") + .replace(/\s+/g, " ") + .trim() + .replace(/[\\`*_{}[\]()<>#+!|~]/g, "\\$&") + .replace(/@/g, "@\u200b") + .replace(/:\/\//g, ":\u200b//") + /** * Only comments posted by our own bot login count. Another App or workflow * could post our markers, and a `go` would then run their text as the plan. @@ -39,25 +50,42 @@ export function requestMarkerFor(requestId) { const previewRun = (summary) => summary?.preview === "true" -// Flags generated-but-unsaved cases loudly; bare counts read as success. -function producedLines(summary, resultArtifact) { +/** + * Flags generated-but-unsaved cases loudly; bare counts read as success. The links are built by + * the Action (`savedToUrl`, `casesDownloadUrl`), never read from the run's summary file, which + * the agent can write. + */ +function producedLines(summary, resultArtifact, { proposing, runUrl, savedToUrl, casesDownloadUrl, casesKeptUntil } = {}) { const generated = Number(summary.cases_generated ?? 0) const saved = Number(summary.cases_saved ?? 0) if (!generated && !saved) return [] + // A plan lists its cases below and says where they go; nothing is saved until it is approved. + // Preview blocks Test Companion's own writes, not the agent's shell, so a save is still reported. + if (proposing) { + const note = + saved > 0 + ? `**${saved} were already saved to Test Management while making this plan**, so approving it may save them again.` + : "Nothing is saved until you approve." + return [`**Test cases:** ${generated} generated. ${note}`, ""] + } + const lines = [`**Test cases:** ${generated} generated, ${saved} saved to Test Management.`] if (saved > 0 && summary.saved_to) { - lines.push(`They are in \`${inertMarkers(summary.saved_to)}\`.`) - } - if (saved < generated) { lines.push( - saved === 0 - ? "**Nothing was written to Test Management.** Download the result below to keep the cases." - : "Some of them were not saved. Download the result below for the full list.", + savedToUrl ? `They are in [${plain(summary.saved_to)}](${savedToUrl}).` : `They are in ${plain(summary.saved_to)}.`, ) } - if (resultArtifact) { - lines.push(`The full list is in the **${resultArtifact}** artifact on this run.`) + if (saved < generated) { + const get = casesDownloadUrl + ? `[Download the test cases](${casesDownloadUrl})${casesKeptUntil ? `, kept ${casesKeptUntil},` : ""} to keep them.` + : runUrl + ? `Download them from the **Artifacts** section of the [run page](${runUrl}) to keep them.` + : "Download the result below to keep the cases." + lines.push(saved === 0 ? `**Nothing was written to Test Management.** ${get}` : `Some of them were not saved. ${get}`) + if (resultArtifact && !casesDownloadUrl) { + lines.push(`The full list is in the **${resultArtifact}** artifact on this run.`) + } } return [lines.join(" "), ""] } @@ -109,6 +137,10 @@ export function renderJobSummary({ errorLine, buildNote, planWorkflow, + proposing, + savedToUrl, + casesDownloadUrl, + casesKeptUntil, } = {}) { const lines = [] lines.push(`## Test Companion — ${withMark(outcome)}`) @@ -162,7 +194,7 @@ export function renderJobSummary({ ["Cost", summary.credits ? `${summary.credits} credits` : ""], ["CLI", cliVersion], ["Asked by", askedByCell(askedBy, askedAt)], - ["Plan", approvedPlan?.url ? `[#${approvedPlan.id}](${approvedPlan.url})` : ""], + ["Plan", requestLink(approvedPlan?.url, "View plan")], ].filter(([, v]) => v) lines.push("| | |", "|---|---|") @@ -174,7 +206,7 @@ export function renderJobSummary({ } lines.push(...failureLines(failedTests)) - lines.push(...producedLines(summary, resultArtifact)) + lines.push(...producedLines(summary, resultArtifact, { proposing, runUrl, savedToUrl, casesDownloadUrl, casesKeptUntil })) if (String(workNote ?? "").trim()) { lines.push(inertMarkers(workNote), "") @@ -336,16 +368,31 @@ export function isApprovableJob(workflow, enabledWorkflows) { return job !== "" && !job.startsWith("-") && (enabledWorkflows ?? []).includes(job) } -export function renderProposal(body, sha, requester, workflow, runId, pinned = {}) { +// What `go` does, per job, for the plan's call to action. +const GO_DOES = { + generate: "save these test cases to Test Management", + fix: "apply this fix as a pull request", + "test-pr": "write these tests to this branch", + test: "write these tests to this branch", + automate: "write these automated tests as a pull request", +} + +/** The plan's call to action, set apart from the report so the next step is obvious. */ +export function renderNextStep(workflow) { + const does = GO_DOES[String(workflow ?? "")] ?? "run this for real" return [ - body, - "", - "Reply **go** to run this for real. Nothing is written until you do. To change the list first, reply **@browserstack go** with your edits. Leave it and it stops being approvable after a day.", - "", - proposalMarkerFor(sha, requester, workflow, runId, pinned), + "> [!IMPORTANT]", + "> **Next step:** reply `go` to " + does + ". Nothing is written until you do.", + ">", + "> - To change the plan first, reply `@browserstack go` followed by your changes.", + "> - To skip it, do nothing: it stops being approvable after a day.", ].join("\n") } +export function renderProposal(body, sha, requester, workflow, runId, pinned = {}) { + return [body, "", renderNextStep(workflow), "", proposalMarkerFor(sha, requester, workflow, runId, pinned)].join("\n") +} + /** "approved", "dropped", or undefined when no plan on this commit was used. */ export function proposalAlreadyUsed(comments, sha, us, workflow) { const want = String(sha ?? "").trim() diff --git a/test-companion/test/approved-cases.test.mjs b/test-companion/test/approved-cases.test.mjs index 253542c..389536f 100644 --- a/test-companion/test/approved-cases.test.mjs +++ b/test-companion/test/approved-cases.test.mjs @@ -176,7 +176,7 @@ describe("parseTmAddReport reads tc tm add --json", () => { failed: [], } test("the report object, with missing lists filled in", () => { - assert.deepEqual(parseTmAddReport(JSON.stringify(report, null, 2)), { ...report, skipped: [] }) + assert.deepEqual(parseTmAddReport(JSON.stringify(report, null, 2)), { ...report, skipped: [], folderUrl: "" }) }) test("the last object when something was printed before it", () => { assert.equal(parseTmAddReport(`Saving 1 case…\n${JSON.stringify(report)}`)?.created.length, 1) @@ -455,7 +455,7 @@ describe("a save that stopped without a report uses the plan up", () => { test("the wiring: killed, timed out or no report is a used-up Run broke; only 'nothing was saved' stays approvable", () => { const main = readFileSync(new URL("../src/main.mjs", import.meta.url), "utf8") const fn = main.slice(main.indexOf("function saveExactly("), main.indexOf("function pickBinding(")) - assert.match(fn, /if \(tmAddStop\(\{ status: r\.status, signal: r\.signal, errorCode: r\.error\?\.code, stderr \}\) === "nothing-saved"\) \{\n\s*return unavailable\("save-failed", why\)/) + assert.match(fn, /if \(tmAddStop\(\{ status: r\.status, signal: r\.signal, errorCode: r\.error\?\.code, stderr \}\) === "nothing-saved"\) \{\n\s*return unavailable\("save-failed", why, kept\)/) assert.match(fn, /return finish\(\{ \.\.\.base, outcome: OUTCOMES\.RUN_BROKE, answer: renderSaveInterrupted\(where, why\) \}, true\)/) }) }) diff --git a/test-companion/test/reply-links.test.mjs b/test-companion/test/reply-links.test.mjs new file mode 100644 index 0000000..c6f7448 --- /dev/null +++ b/test-companion/test/reply-links.test.mjs @@ -0,0 +1,236 @@ +import { test, describe } from "node:test" +import assert from "node:assert/strict" +import { readFileSync } from "node:fs" +import { renderJobSummary, renderNextStep, renderProposal, plain } from "../src/report.mjs" +import { + tmFolderUrl, + artifactDownloadLink, + keptUntil, + parseTmAddReport, + renderCasesUnavailable, + renderExactSave, + renderSaveInterrupted, +} from "../src/approved-cases.mjs" + +const FOLDER = "https://test-management.browserstack.com/projects/4328203/folder/61742797/test-cases" +const DOWNLOAD = "https://github.com/o/r/actions/runs/123/artifacts/456" +const RUN = "https://github.com/o/r/actions/runs/999" +const where = { project: "rag_assignment", folder: "github-app" } + +describe("tmFolderUrl: only the saved folder's Test Management page is linked", () => { + test("the page tc tm add reports for that folder is kept", () => { + assert.equal(tmFolderUrl(FOLDER, "61742797"), FOLDER) + }) + test("a region's own Test Management host is kept", () => { + const eu = "https://test-management-eu.browserstack.com/projects/1/folder/2/test-cases" + assert.equal(tmFolderUrl(eu, "2"), eu) + }) + test("a page for another folder is not linked", () => { + assert.equal(tmFolderUrl(FOLDER, "1"), undefined) + assert.equal(tmFolderUrl(FOLDER, undefined), undefined) + }) + test("anything else gives no link", () => { + assert.equal(tmFolderUrl(undefined, "2"), undefined) + assert.equal(tmFolderUrl("", "2"), undefined) + assert.equal(tmFolderUrl("https://test-management.browserstack.com/projects/PR-164148/folder/61742797/test-cases", "61742797"), undefined) + assert.equal(tmFolderUrl("https://evil.test/projects/1/folder/2/test-cases", "2"), undefined) + assert.equal(tmFolderUrl("https://browserstack.com.evil.test/projects/1/folder/2/test-cases", "2"), undefined) + assert.equal(tmFolderUrl("http://test-management.browserstack.com/projects/1/folder/2/test-cases", "2"), undefined) + assert.equal(tmFolderUrl(`${FOLDER}?next=https://evil.test`, "61742797"), undefined) + assert.equal(tmFolderUrl(`${FOLDER})[x](https://evil.test`, "61742797"), undefined) + assert.equal(tmFolderUrl(`${FOLDER}\nhttps://evil.test`, "61742797"), undefined) + }) +}) + +describe("artifactDownloadLink and keptUntil", () => { + test("repo, run and artifact ids make the link", () => { + assert.equal(artifactDownloadLink("o/r", "123", 456), DOWNLOAD) + }) + test("anything else gives no link", () => { + assert.equal(artifactDownloadLink("o/r", "123", undefined), undefined) + assert.equal(artifactDownloadLink("o", "123", "456"), undefined) + assert.equal(artifactDownloadLink("o/r/x", "123", "456"), undefined) + assert.equal(artifactDownloadLink("o/r", "12a", "456"), undefined) + }) + test("the artifact's expiry becomes a date, or nothing", () => { + assert.equal(keptUntil("2026-11-30T10:41:00Z"), "until 2026-11-30") + assert.equal(keptUntil(undefined), "") + assert.equal(keptUntil("soon](https://evil.test)"), "") + }) +}) + +describe("parseTmAddReport keeps the folder page", () => { + test("folderUrl is passed through", () => { + const out = JSON.stringify({ project: "PR-164148", folderId: "61742797", folderUrl: FOLDER, created: [], failed: [], skipped: [] }) + assert.equal(parseTmAddReport(out).folderUrl, FOLDER) + }) + test("an older CLI without it gives an empty one", () => { + assert.equal(parseTmAddReport(JSON.stringify({ created: [] })).folderUrl, "") + }) +}) + +describe("a saved generate links its folder", () => { + const report = { created: [{ identifier: "TC-1", title: "One" }], failed: [], skipped: [], folderUrl: FOLDER, folderId: "61742797" } + + test("the answer names the folder as a link", () => { + assert.ok(renderExactSave(report, where).includes(`to [github-app in rag\\_assignment](${FOLDER}) exactly as planned`)) + }) + test("without a reported page it stays plain text", () => { + const text = renderExactSave({ ...report, folderUrl: "" }, where) + assert.match(text, /to github-app in rag\\_assignment exactly as planned/) + assert.doesNotMatch(text, /\]\(https:/) + }) + test("a page for a different folder is not linked", () => { + assert.doesNotMatch(renderExactSave({ ...report, folderId: "1" }, where), /\]\(https:/) + }) + test("the counts line links the folder too", () => { + const body = renderJobSummary({ + outcome: "Succeeded", + summary: { cases_generated: "1", cases_saved: "1", saved_to: "github-app in rag_assignment" }, + savedToUrl: FOLDER, + }) + assert.ok(body.includes(`They are in [github-app in rag\\_assignment](${FOLDER}).`)) + assert.doesNotMatch(body, /Download/) + }) + test("a link in the agent-writable summary is never used", () => { + const body = renderJobSummary({ + outcome: "Succeeded", + summary: { cases_generated: "1", cases_saved: "1", saved_to: "x", saved_to_url: "https://evil.test" }, + }) + assert.doesNotMatch(body, /evil/) + assert.ok(body.includes("They are in x.")) + }) + test("a folder name can't break out into Markdown, a mention or a link", () => { + const name = "F\n\n# Heading @octocat https://evil.test ](https://evil.test)" + for (const savedToUrl of [FOLDER, undefined]) { + const body = renderJobSummary({ + outcome: "Succeeded", + summary: { cases_generated: "1", cases_saved: "1", saved_to: name }, + savedToUrl, + }) + const line = body.split("\n").find((l) => l.startsWith("**Test cases:**")) + assert.ok(line.includes(plain(name)), line) + assert.doesNotMatch(body, /^# Heading/m) + assert.doesNotMatch(body, /@octocat/) + assert.doesNotMatch(body, /https:\/\/evil/) + } + }) + test("an interrupted save has no report, so names the folder without a link", () => { + assert.match(renderSaveInterrupted(where, "killed"), /Check github-app in rag\\_assignment before/) + }) +}) + +describe("cases that weren't saved get one download link, with how long it lasts", () => { + test("none saved: the direct link replaces 'download the result below'", () => { + const body = renderJobSummary({ + outcome: "Run broke", + summary: { cases_generated: "3", cases_saved: "0" }, + casesDownloadUrl: DOWNLOAD, + casesKeptUntil: "until 2026-11-30", + resultArtifact: "test-companion-result", + runUrl: RUN, + }) + assert.ok(body.includes(`**Nothing was written to Test Management.** [Download the test cases](${DOWNLOAD}), kept until 2026-11-30, to keep them.`)) + assert.doesNotMatch(body, /artifact on this run/) + }) + test("no direct link: point at the run page's Artifacts", () => { + const body = renderJobSummary({ outcome: "Succeeded", summary: { cases_generated: "3", cases_saved: "1" }, runUrl: RUN }) + assert.ok(body.includes(`Some of them were not saved. Download them from the **Artifacts** section of the [run page](${RUN}) to keep them.`)) + }) + test("all saved: no download advice", () => { + const body = renderJobSummary({ + outcome: "Succeeded", + summary: { cases_generated: "3", cases_saved: "3" }, + resultArtifact: "test-companion-result", + runUrl: RUN, + }) + assert.doesNotMatch(body, /Download|artifact on this run/) + }) + test("a save that couldn't start links the approved cases and says until when", () => { + const text = renderCasesUnavailable("save-failed", "project not found", { download: DOWNLOAD, until: "until 2026-11-30" }) + assert.ok(text.includes(`You can still [download the approved test cases](${DOWNLOAD}), kept until 2026-11-30.`)) + }) + test("without a link the reply is as before", () => { + assert.doesNotMatch(renderCasesUnavailable("changed"), /download/) + }) + test("some failed: the answer lists them, and the link is given once, below", () => { + const report = { created: [{ identifier: "TC-1", title: "One" }], failed: [{ title: "Two", error: "bad field" }], skipped: [] } + const answer = renderExactSave(report, where) + assert.doesNotMatch(answer, /Download/) + const body = renderJobSummary({ + outcome: "Run broke", + answer, + summary: { cases_generated: "2", cases_saved: "1" }, + casesDownloadUrl: DOWNLOAD, + }) + assert.equal(body.split(DOWNLOAD).length - 1, 1) + }) +}) + +describe("a plan says nothing is saved yet, and sets the next step apart", () => { + test("a plan's counts don't offer a download", () => { + const body = renderJobSummary({ + outcome: "Succeeded", + proposing: true, + summary: { cases_generated: "10", cases_saved: "0", preview: "true" }, + resultArtifact: "test-companion-result", + runUrl: RUN, + }) + assert.ok(body.includes("**Test cases:** 10 generated. Nothing is saved until you approve.")) + assert.doesNotMatch(body, /Download|Nothing was written|artifact on this run/) + }) + test("a plan whose run did save some says so, rather than 'nothing is saved'", () => { + const body = renderJobSummary({ outcome: "Succeeded", proposing: true, summary: { cases_generated: "10", cases_saved: "8" } }) + assert.ok(body.includes("**8 were already saved to Test Management while making this plan**, so approving it may save them again.")) + assert.doesNotMatch(body, /Nothing is saved until you approve/) + }) + test("the next step is a highlighted box naming what go does", () => { + const box = renderNextStep("generate") + assert.match(box, /^> \[!IMPORTANT\]\n/) + assert.match(box, /reply `go` to save these test cases to Test Management/) + assert.match(box, /reply `@browserstack go` followed by your changes/) + assert.match(box, /stops being approvable after a day/) + assert.ok(box.split("\n").every((l) => l.startsWith(">"))) + }) + test("each job says what go does; an unknown one says run", () => { + assert.match(renderNextStep("fix"), /apply this fix as a pull request/) + assert.match(renderNextStep("test-pr"), /write these tests to this branch/) + assert.match(renderNextStep("test"), /write these tests to this branch/) + assert.match(renderNextStep("anything"), /run this for real/) + }) + test("the proposal ends with the box, then its marker", () => { + const body = renderProposal("the plan", "a".repeat(40), "octocat", "generate", "1") + const box = body.indexOf("> [!IMPORTANT]") + assert.ok(box > body.indexOf("the plan")) + assert.ok(body.indexOf("