Files
David Pine 5b6da4c588 Add PR Artifact Explorer canvas 🤖🤖🤖 (#2341)
* Add PR Artifact Explorer canvas

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 33fefd65-ed18-4eda-9c7d-48008f4a9c9d

* Address PR #2341 review feedback and codespell CI failures

PR review fixes:

- zip.mjs: bounded streaming inflate for readZipEntry (output cap = entry.uncompressedSize) to prevent memory exhaustion from malformed entries

- zip.mjs: new bounded verify Transform in streamZipEntry that enforces decompressed byte cap and verifies CRC32 on flush

- zip.mjs: new readEntryPrefix() helper that inflates only up to a byte cap for indexing use cases

- preview.mjs: move URL/path parsing inside the try block so URIError becomes a 400 response instead of an unhandled rejection

- cache.mjs: buildMetadata uses bounded readEntryPrefix (8 KiB) instead of full readEntry+slice, eliminating unbounded decompression during indexing

- cache.mjs: clearArtifactCache aborts and awaits in-flight downloads via AbortController before removing cache dirs so clear cannot be repopulated

- server.mjs / preview.mjs: track static preview servers by canvas origin and stop them on canvas close, preventing loopback server leaks

- trx-preview.js: prefer authoritative ResultSummary.outcome when it is a recognized TRX value; only infer from counters when unknown

- extension.mjs: set_account validates the requested id resolves to the active account before persisting; unknown ids now return an error

- server.mjs: reject progressive-pull offsets that are not multiples of PROGRESSIVE_PULL_BATCH_SIZE to prevent caching incomplete pulls as complete

- README.md: remove Markdown-rendering claim (files are shown as escaped text)

CI fix:

- .codespellrc: skip vendored asciinema-player(*.min.js) and primer-*.css bundles

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 47369ff4-859a-425f-8a47-763cc1a5f25f

* Address second round of PR #2341 review feedback

- github.mjs: request isDraft in the pullRequestSignals GraphQL enrichment and propagate draft into search-sourced pulls (search REST API has no draft field)

- cache.mjs: give each writeJsonAtomic write a unique temp filename via a module sequence and clean up the temp file on failure to avoid concurrent-write races

- cache.mjs: deleteCachedArtifact now aborts and awaits any in-flight download for the artifact before removing files; internal mismatched-metadata purge uses a raw removeArtifactFiles helper to avoid aborting its own operation

- accounts.mjs: skip non-github.com CLI accounts before reading tokens so GitHub Enterprise Server credentials are never sent to api.github.com

- preview.mjs: require the requested entry to be the root index.html before launching a static preview (previously any nested HTML file could start one)

- zip.mjs: validate the EOCD comment length ends exactly at the archive tail so a file comment containing the EOCD signature is not mistaken for the record

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 47369ff4-859a-425f-8a47-763cc1a5f25f

* Address remaining PR artifact explorer feedback

Fix malformed preference normalization, replace artifact-presence request fanout with cached repository artifact pagination, restrict static previews to the root index, and derive completed TRX outcomes from counters. Add focused regression coverage for all four behaviors.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: db486df1-17f1-4623-ac7e-61eff2c76da4

* Fix PR artifact explorer review feedback

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 6ee2bc81-2114-4b1f-987a-cb47ea35e132

* Stabilize artifact discovery and cache cleanup

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 6ee2bc81-2114-4b1f-987a-cb47ea35e132

---------

Co-authored-by: David Pine <7679720+IEvangelist@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 33fefd65-ed18-4eda-9c7d-48008f4a9c9d
Copilot-Session: 47369ff4-859a-425f-8a47-763cc1a5f25f
Copilot-Session: db486df1-17f1-4623-ac7e-61eff2c76da4
Copilot-Session: 6ee2bc81-2114-4b1f-987a-cb47ea35e132
2026-07-30 10:16:58 +10:00

216 lines
7.3 KiB
JavaScript

import {
CanvasError,
createCanvas,
joinSession,
} from "@github/copilot-sdk/extension";
import { resolveAccounts, invalidateAccounts } from "./accounts.mjs";
import {
clearArtifactCache,
deleteCachedArtifact,
getCacheSummary,
inspectArtifact,
} from "./cache.mjs";
import {
broadcastCache,
closeAllPreviews,
navigateInstance,
startInstance,
stopInstance,
} from "./server.mjs";
import { stopStaticPreviewsForArtifact } from "./preview.mjs";
import { loadPrefs, normalizeRepository, savePrefs } from "./state.mjs";
function positiveInteger(value, label) {
const number = Number.parseInt(value, 10);
if (!Number.isSafeInteger(number) || number <= 0) {
throw new CanvasError("invalid_input", `${label} must be a positive integer.`);
}
return number;
}
const session = await joinSession({
canvases: [
createCanvas({
id: "pr-artifact-explorer",
displayName: "Artifact Explorer",
description:
"Browse GitHub pull requests and securely preview workflow artifacts, including static sites and asciinema recordings.",
inputSchema: {
type: "object",
properties: {
repository: {
type: "string",
description: "Repository in owner/name format.",
},
pullNumber: {
type: "integer",
minimum: 1,
description: "Pull request number to open.",
},
url: {
type: "string",
description: "GitHub pull request URL to open.",
},
},
additionalProperties: false,
},
actions: [
{
name: "open_pull_request",
description: "Navigate an open explorer canvas to a pull request.",
inputSchema: {
type: "object",
properties: {
repository: { type: "string" },
pullNumber: { type: "integer", minimum: 1 },
},
required: ["repository", "pullNumber"],
additionalProperties: false,
},
handler: (ctx) => {
const repository = normalizeRepository(ctx.input?.repository);
const pullNumber = positiveInteger(ctx.input?.pullNumber, "pullNumber");
const route = `#/pull/${encodeURIComponent(repository)}/${pullNumber}`;
return {
navigated: navigateInstance(ctx.instanceId, route),
repository,
pullNumber,
};
},
},
{
name: "inspect_artifact",
description: "Download, index, and smart-detect a GitHub Actions artifact.",
inputSchema: {
type: "object",
properties: {
repository: { type: "string" },
artifactId: { type: "integer", minimum: 1 },
},
required: ["repository", "artifactId"],
additionalProperties: false,
},
handler: async (ctx) => {
const repository = normalizeRepository(ctx.input?.repository);
const artifactId = positiveInteger(ctx.input?.artifactId, "artifactId");
const prefs = await loadPrefs();
const auth = await resolveAccounts({
preferredId: prefs.account,
repository,
});
if (!auth.activeToken) {
throw new CanvasError("github_auth_required", "No usable GitHub account was found.");
}
const metadata = await inspectArtifact(auth.activeToken, repository, artifactId);
await broadcastCache();
navigateInstance(
ctx.instanceId,
`#/artifact/${encodeURIComponent(repository)}/0/${artifactId}`,
);
const entries = metadata.analysis.entries ?? [];
return {
artifact: metadata.artifact,
analysis: {
...metadata.analysis,
entries: entries.slice(0, 200),
entriesTruncated: entries.length > 200,
},
};
},
},
{
name: "cache_status",
description: "Report downloaded artifact cache usage.",
handler: async () => getCacheSummary(),
},
{
name: "clear_cache",
description: "Delete one downloaded artifact or clear the entire artifact cache.",
inputSchema: {
type: "object",
properties: {
artifactId: { type: "integer", minimum: 1 },
},
additionalProperties: false,
},
handler: async (ctx) => {
if (ctx.input?.artifactId != null) {
await stopStaticPreviewsForArtifact(ctx.input.artifactId);
const result = await deleteCachedArtifact(
positiveInteger(ctx.input.artifactId, "artifactId"),
);
navigateInstance(ctx.instanceId, "#/cache");
await broadcastCache({ refresh: true });
return result;
}
await closeAllPreviews();
const result = await clearArtifactCache();
navigateInstance(ctx.instanceId, "#/cache");
await broadcastCache({ refresh: true });
return result;
},
},
{
name: "accounts",
description: "List GitHub accounts inherited from the Copilot app and GitHub CLI.",
handler: async () => {
const prefs = await loadPrefs();
const auth = await resolveAccounts({
preferredId: prefs.account,
repository: prefs.repository,
force: true,
});
return { active: auth.active, accounts: auth.accounts };
},
},
{
name: "set_account",
description: "Select the GitHub account used by the artifact explorer.",
inputSchema: {
type: "object",
properties: { id: { type: "string" } },
required: ["id"],
additionalProperties: false,
},
handler: async (ctx) => {
if (typeof ctx.input?.id !== "string" || !ctx.input.id) {
throw new CanvasError("invalid_account", "Account id is required.");
}
const prefs = await loadPrefs();
invalidateAccounts();
const auth = await resolveAccounts({
preferredId: ctx.input.id,
repository: prefs.repository,
force: true,
});
if (!auth.active || auth.active.id !== ctx.input.id) {
throw new CanvasError(
"invalid_account",
`Account "${ctx.input.id}" was not found or is unavailable.`,
);
}
prefs.account = ctx.input.id;
await savePrefs(prefs);
return { active: auth.active, accounts: auth.accounts };
},
},
],
open: async (ctx) => {
const entry = await startInstance(
ctx.instanceId,
ctx.input,
(message) => session.log(message, { level: "debug" }),
);
return {
title: "Artifact Explorer",
status: "GitHub pull request artifacts",
url: entry.url,
};
},
onClose: async (ctx) => {
await stopInstance(ctx.instanceId);
},
}),
],
});