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

291 lines
9.0 KiB
JavaScript

import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { PREFS_FILE } from "./constants.mjs";
const MAX_RECENT_REPOSITORIES = 12;
const MAX_FAVORITE_REPOSITORIES = 3;
const MAX_PULL_FILTER_REPOSITORIES = 50;
const PLAYER_FONT_SIZES = new Set(["12px", "14px", "16px", "18px", "20px", "22px"]);
const PLAYER_FONTS = new Set(["system", "cascadia", "consolas"]);
const PLAYER_SPEEDS = new Set([0.5, 1, 1.5, 2]);
const PULL_ARTIFACT_FILTERS = new Set(["all", "with", "without"]);
const PULL_CI_FILTERS = new Set(["all", "failing", "passing", "pending", "none"]);
let preferenceSaveQueue = Promise.resolve();
let preferenceSaveSequence = 0;
const WINDOWS_RENAME_RETRY_CODES = new Set(["EACCES", "EBUSY", "EPERM"]);
export const DEFAULT_PREFS = Object.freeze({
account: null,
repository: "microsoft/aspire",
pullState: "open",
repositories: {
pinned: null,
favorites: [],
recent: ["microsoft/aspire"],
},
pullFilters: {},
explorer: {
sidebarCollapsed: false,
},
player: {
fontSize: "16px",
fontFamily: "system",
lineHeight: 1.2,
speed: 1,
},
});
export function normalizeRepository(value) {
const repository = String(value ?? "").trim().replace(/^https?:\/\/github\.com\//i, "");
const match = repository.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/);
if (!match) {
throw new Error("Repository must use the owner/name format.");
}
if ([match[1], match[2]].some((part) => part === "." || part === "..")) {
throw new Error("Repository owner and name cannot be dot segments.");
}
return `${match[1]}/${match[2]}`;
}
function normalizeStoredRepository(value) {
try {
return typeof value === "string" && value.trim() ? normalizeRepository(value) : null;
} catch {
return null;
}
}
function normalizeRepositoryList(value, limit) {
const repositories = [];
for (const item of Array.isArray(value) ? value : []) {
const repository = normalizeStoredRepository(item);
if (repository && !repositories.includes(repository)) repositories.push(repository);
if (repositories.length === limit) break;
}
return repositories;
}
function normalizePlayer(value) {
const lineHeight = Number(value?.lineHeight);
const speed = Number(value?.speed);
return {
fontSize: PLAYER_FONT_SIZES.has(value?.fontSize)
? value.fontSize
: DEFAULT_PREFS.player.fontSize,
fontFamily: PLAYER_FONTS.has(value?.fontFamily)
? value.fontFamily
: DEFAULT_PREFS.player.fontFamily,
lineHeight:
Number.isFinite(lineHeight) && lineHeight >= 1 && lineHeight <= 1.6
? Math.round(lineHeight * 10) / 10
: DEFAULT_PREFS.player.lineHeight,
speed: PLAYER_SPEEDS.has(speed) ? speed : DEFAULT_PREFS.player.speed,
};
}
function normalizeExplorer(value) {
return {
sidebarCollapsed: value?.sidebarCollapsed === true,
};
}
function normalizePullFilter(value) {
const author =
typeof value?.author === "string" && value.author.trim()
? value.author.trim().slice(0, 100)
: null;
const updatedAt = Number(value?.updatedAt);
return {
state: ["open", "closed", "all"].includes(value?.state) ? value.state : "open",
author,
artifacts: PULL_ARTIFACT_FILTERS.has(value?.artifacts) ? value.artifacts : "all",
ci: PULL_CI_FILTERS.has(value?.ci) ? value.ci : "all",
updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : 0,
};
}
function normalizePullFilters(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const entries = [];
for (const [key, filter] of Object.entries(value)) {
const repository = normalizeStoredRepository(key);
if (!repository || !filter || typeof filter !== "object") continue;
entries.push([
repository.toLocaleLowerCase(),
normalizePullFilter(filter),
]);
}
return Object.fromEntries(
entries
.sort((left, right) => right[1].updatedAt - left[1].updatedAt)
.slice(0, MAX_PULL_FILTER_REPOSITORIES),
);
}
export function normalizePrefs(value) {
const prefs = value && typeof value === "object" ? value : {};
const repository =
normalizeStoredRepository(prefs.repository) ?? DEFAULT_PREFS.repository;
const pinned = normalizeStoredRepository(prefs.repositories?.pinned);
const favorites = normalizeRepositoryList(
prefs.repositories?.favorites,
MAX_FAVORITE_REPOSITORIES,
).filter((item) => item !== pinned);
return {
account: typeof prefs.account === "string" && prefs.account ? prefs.account : null,
repository,
pullState: ["open", "closed", "all"].includes(prefs.pullState)
? prefs.pullState
: DEFAULT_PREFS.pullState,
repositories: {
pinned,
favorites,
recent: normalizeRepositoryList(
[
repository,
...(Array.isArray(prefs.repositories?.recent)
? prefs.repositories.recent
: []),
],
MAX_RECENT_REPOSITORIES,
),
},
pullFilters: normalizePullFilters(prefs.pullFilters),
explorer: normalizeExplorer(prefs.explorer),
player: normalizePlayer(prefs.player),
};
}
export async function loadPrefs() {
try {
return normalizePrefs(JSON.parse(await readFile(PREFS_FILE, "utf8")));
} catch (error) {
if (error?.code === "ENOENT") {
return normalizePrefs();
}
if (error instanceof SyntaxError) {
throw new Error(`Preferences are not valid JSON: ${PREFS_FILE}`, { cause: error });
}
throw error;
}
}
async function replacePreferencesFile(temporary) {
let lastError;
for (let attempt = 0; attempt < 7; attempt++) {
try {
await rename(temporary, PREFS_FILE);
return;
} catch (error) {
if (!WINDOWS_RENAME_RETRY_CODES.has(error?.code)) throw error;
lastError = error;
if (attempt === 6) break;
await delay(10 * 2 ** attempt);
}
}
try {
await rm(temporary, { force: true });
} catch (cleanupError) {
throw new AggregateError(
[lastError, cleanupError],
"Preferences could not be replaced or cleaned up.",
);
}
throw lastError;
}
export async function savePrefs(value) {
const prefs = normalizePrefs(value);
const save = async () => {
await mkdir(dirname(PREFS_FILE), { recursive: true });
const temporary =
`${PREFS_FILE}.${process.pid}.${++preferenceSaveSequence}.tmp`;
await writeFile(temporary, `${JSON.stringify(prefs, null, 2)}\n`, "utf8");
await replacePreferencesFile(temporary);
return prefs;
};
const pending = preferenceSaveQueue.then(save, save);
preferenceSaveQueue = pending.then(
() => undefined,
() => undefined,
);
return pending;
}
export function rememberRepository(preferences, value) {
const repository = normalizeRepository(value);
preferences.repository = repository;
preferences.repositories ??= {};
preferences.repositories.recent = normalizeRepositoryList(
[
repository,
...(Array.isArray(preferences.repositories.recent)
? preferences.repositories.recent
: []),
],
MAX_RECENT_REPOSITORIES,
);
return repository;
}
export function setPinnedRepository(preferences, value) {
const repository = value == null || value === "" ? null : normalizeRepository(value);
preferences.repositories ??= {};
preferences.repositories.pinned = repository;
preferences.repositories.favorites = normalizeRepositoryList(
preferences.repositories.favorites,
MAX_FAVORITE_REPOSITORIES,
).filter((item) => item !== repository);
return repository;
}
export function setFavoriteRepository(preferences, value, favorite) {
const repository = normalizeRepository(value);
preferences.repositories ??= {};
const favorites = normalizeRepositoryList(
preferences.repositories.favorites,
MAX_FAVORITE_REPOSITORIES,
).filter((item) => item !== repository);
if (favorite) {
if (preferences.repositories.pinned === repository) {
throw new Error("The pinned repository is already available in quick switch.");
}
if (favorites.length >= MAX_FAVORITE_REPOSITORIES) {
throw new Error("You can favorite up to three repositories.");
}
favorites.unshift(repository);
}
preferences.repositories.favorites = favorites;
return favorites;
}
export function setPullFilterPreferences(preferences, repositoryValue, value) {
const repository = normalizeRepository(repositoryValue).toLocaleLowerCase();
preferences.pullFilters = normalizePullFilters({
...preferences.pullFilters,
[repository]: {
...preferences.pullFilters?.[repository],
...value,
updatedAt: Date.now(),
},
});
return preferences.pullFilters[repository];
}
export function setExplorerPreferences(preferences, value) {
preferences.explorer = normalizeExplorer({
...preferences.explorer,
...value,
});
return preferences.explorer;
}
export function setPlayerPreferences(preferences, value) {
preferences.player = normalizePlayer({
...preferences.player,
...value,
});
return preferences.player;
}