Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 45 additions & 13 deletions test-companion/src/approved-cases.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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/<id>/artifacts` reply, or why there is none.
* The run must belong to this repository and have started from it (`repoId`, GitHub's numeric
Expand Down Expand Up @@ -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 : [],
Expand All @@ -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."
Expand All @@ -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")
}

Expand All @@ -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("")
Expand Down
43 changes: 32 additions & 11 deletions test-companion/src/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ import {
parseTmAddReport,
renderCasesUnavailable,
renderExactSave,
tmFolderUrl,
artifactDownloadLink,
keptUntil,
exactSaveSummary,
exactSaveOutcome,
EDITED_GO_NOTE,
Expand Down Expand Up @@ -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`
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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}.`)
Expand All @@ -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. */
Expand Down
95 changes: 71 additions & 24 deletions test-companion/src/report.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,31 @@ const withMark = (outcome) => {
return mark ? `${mark} ${outcome}` : String(outcome ?? "")
}

/** `[#<id>](<url>)` for the comment that asked for this run; "" unless the URL names a comment. */
export function requestLink(url) {
/** `[View comment](<url>)` 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})` : ""
}

/** `@<who> | [#<comment id>](<url>)`; the pipe is escaped so it stays inside the table cell. */
/** `@<who> · [View comment](<url>)`. */
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.
Expand All @@ -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(" "), ""]
}
Expand Down Expand Up @@ -109,6 +137,10 @@ export function renderJobSummary({
errorLine,
buildNote,
planWorkflow,
proposing,
savedToUrl,
casesDownloadUrl,
casesKeptUntil,
} = {}) {
const lines = []
lines.push(`## Test Companion — ${withMark(outcome)}`)
Expand Down Expand Up @@ -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("| | |", "|---|---|")
Expand All @@ -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), "")
Expand Down Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions test-companion/test/approved-cases.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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\)/)
})
})
Expand Down
Loading
Loading