feat(ui): context panel 2.0 - surface rail, changes-first git view, live PR surface (#2418)
* feat(ui): add context surface registry and rail switcher * feat(ui): move git and project notes into context surfaces, embed editor file tree * feat(ui): replace right sidebar with context surfaces, per-surface panel widths * refactor(ui): retire legacy main-tab overlays and right-sidebar state * feat(ui): rail polish, right-docked file tree, terminal surface * feat(ui): move terminal into context surface, per-surface tab closing, editor empty state * feat(ui): tune default rail order and activity dot * fix(ui): keep context panel controls anchored during width animations * feat(ui): lazy-follow context panel resize with window-level drag tracking * feat(ui): panel dividers, right-dock tree icon, muted outline folder icons * feat(ui): restructure git view into changes-first surface with standalone PR surface - Remove commit/update/pr tabs; git view is always changes + commit - Promote pull request to its own rail surface with shared repo context - Move update-branch and re-integrate flows into separate dialogs - Add PR status chip and repo actions menu to the git header row - Seed new PR-status entries from resolved sibling remotes to avoid a false "checking status" state when the PR is already known - History/graph dialog refresh button, fingerprint global identity icon, muted outline folder icons follow-ups * feat(ui): progressive-disclosure PR surface with live checks and pinned chat context - Segment the PR surface into Overview / Checks / Comments pill tabs with live badges; merge controls move to the status row - Live checks segment: progress bar, per-run rows with workflow names, elapsed timers, expandable failures, auto-refresh while pending - PR comments and failed checks pin as chat-context drafts (like terminal selections) instead of sending an immediate message; works on new-session drafts too - Shared prContext cache client+server, ETag conditional requests in the octokit wrapper (304s bypass rate limits), extended checks aggregate (inProgress/queued/startedAt) - Resolve gh-CLI auth login for merge-permission checks - Full-width description editor with matched control heights * fix(ui): single source of truth for PR checks and status readers - Derive the checks aggregate from the visible run list and sync it into the PR-status store so bar, badges, header, and git-view chip agree - Route PR body hydration through the shared context cache - Git-view PR chip reads the freshest entry across remote keys * fix(github): freshness stamps prevent stale cache responses from regressing PR state - pr/status and pulls/context responses carry a server-side fetchedAt that survives cache serves - The status store rejects responses older than the held snapshot (only clearing the loading flag), and the checks sync adopts the context's stamp so stale status polls cannot flip fresher derived checks - Regression test for the stale-response guard * perf(github): repo-level pull-list cache collapses per-branch PR resolution - One pulls.list per repo per state per 45s answers every branch (10 worktrees = 1 call, not 10 query fans); in-flight fetches coalesce - A complete repo list makes a no-PR miss authoritative, skipping the per-owner head queries AND the Search API fallback (the 30/min killer) - force refresh bypasses the repo list cache; PR create/merge/ready invalidate it * perf(github): back off Search API misses per repo+branch A branch without a PR re-searched on every poll; with >100 closed PRs the list miss is never authoritative, so the search fallback still ran and burned the 30/min search quota. Remember misses for 10 minutes; PR creation clears remembered misses for the repo. * fix(github): dedupe re-run check runs to the latest per (app, name) listForRef returns the superseded completed run alongside its re-run; GitHub's UI shows only the latest per name. Mirror that in both pr/status and pulls/context so counts and run lists match github.com. * fix(ui): address review findings on registry test, surface docs, and PR-context keys - Rail-order test asserts against the registry itself (was stale after the 'pr' surface landed and failed) - surfaces DOCUMENTATION.md describes actual behavior: has-content surfaces hide until content exists; only multi-instance/terminal panes are keep-alive, singleton surfaces remount and restore from stores - PR-context cache keys are runtime-scoped JSON tuples; invalidation compares the directory exactly instead of by string prefix (+ test) * fix(ui): wrap long unbreakable tokens in check-run details Annotation messages with long SHAs/URLs overflowed the panel; break-words on annotation title/message/rawDetails and output summary/text, and the expanded run body clips instead of widening the panel. * fix(ui): busy state for context-attach buttons and honest attach labels - 'Attach failed checks' / 'Attach all to chat' show a spinner and disable while the context request runs (previously nothing happened for seconds) - Action labels/tooltips reworded from send-to-agent to attach-to-chat semantics across all locales * fix(i18n): Ukrainian attach wording uses 'прикріпити' with proper cases * fix(ui): runtime-scope PR-view remote caches, correct surfaces doc on preview - Remote/remote-url caches in PullRequestView are keyed by runtime + directory so a backend switch never serves another runtime's remotes - surfaces DOCUMENTATION.md: preview is not keep-alive; preview tabs remount on switch like singleton surfaces * fix(ui): rail active color, clearer collapse icon, remove dead bottom-terminal dock Design-review feedback on the context panel: - Context rail: icons enlarged 16px -> 18px; the active surface is now highlighted with the primary color only (no background, no scale animation), replacing the previous scale-up effect that read as a resize rather than a selected state. - Files tree: the icon-only 'collapse all folders' toolbar button now uses collapse-vertical instead of contract-up-down, which was easily mistaken for a close button. The labelled 'Collapse all' dropdown item in the session sidebar keeps its icon since text removes the ambiguity. - Terminal: removed the leftover bottom-dock expand/close buttons that rendered in the context-panel terminal but controlled a dock that no longer exists (nothing toggles it anymore), so the expand button appeared to do nothing and duplicated the panel-header fullscreen control. Cleaned up the entire inert layer with it: four useUIStore fields (isBottomTerminalOpen/Expanded, bottomTerminalHeight, hasManuallyResizedBottomTerminal), five actions, their persistence, the MainLayout resize listener that only served the dock height, the dock-driven refit effect in TerminalView, and the terminalView.bottomDock.* keys across all 10 locale dictionaries. Validated: ui type-check and lint clean; messages parity test (2 pass) and useUIStore contextPanel test (13 pass) green; icon sprite regenerated via icons:generate. * refactor: use PR visual state for git header icon Derives the pull request icon color from a single visual state Covers merged, closed, draft, blocked, and open PR states Removes conditional class handling from the git header icon
This commit is contained in:
committed by
GitHub
parent
005b2e61b0
commit
e2fa7dbad2
@@ -17,9 +17,60 @@ const timeoutFetch = (url, options = {}) => {
|
||||
return fetch(url, { ...options, signal: AbortSignal.timeout(OCTOKIT_REQUEST_TIMEOUT_MS) });
|
||||
};
|
||||
|
||||
/** Create an Octokit instance with a per-request timeout applied. */
|
||||
// Conditional-request cache for GET calls: GitHub serves 304 Not Modified for
|
||||
// matching If-None-Match WITHOUT counting the request against the REST rate
|
||||
// limit, so polling unchanged PRs/checks becomes rate-limit-free. Keyed by
|
||||
// token+URL so different identities never share responses.
|
||||
const ETAG_CACHE_MAX_ENTRIES = 300;
|
||||
const etagCache = new Map();
|
||||
|
||||
const rememberEtag = (key, etag, body, headers) => {
|
||||
etagCache.delete(key);
|
||||
etagCache.set(key, { etag, body, headers });
|
||||
if (etagCache.size > ETAG_CACHE_MAX_ENTRIES) {
|
||||
const oldest = etagCache.keys().next().value;
|
||||
if (oldest !== undefined) {
|
||||
etagCache.delete(oldest);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const createConditionalFetch = (token) => async (url, options = {}) => {
|
||||
const method = (options.method || 'GET').toUpperCase();
|
||||
if (method !== 'GET') {
|
||||
return timeoutFetch(url, options);
|
||||
}
|
||||
|
||||
const cacheKey = `${token}\n${url}`;
|
||||
const cached = etagCache.get(cacheKey);
|
||||
const headers = { ...(options.headers || {}) };
|
||||
if (cached?.etag) {
|
||||
headers['if-none-match'] = cached.etag;
|
||||
}
|
||||
|
||||
const response = await timeoutFetch(url, { ...options, headers });
|
||||
|
||||
if (response.status === 304 && cached) {
|
||||
// Touch for LRU and replay the cached success response.
|
||||
rememberEtag(cacheKey, cached.etag, cached.body, cached.headers);
|
||||
return new Response(cached.body, { status: 200, headers: cached.headers });
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
const etag = response.headers.get('etag');
|
||||
if (etag) {
|
||||
const body = await response.arrayBuffer();
|
||||
rememberEtag(cacheKey, etag, body, response.headers);
|
||||
return new Response(body, { status: response.status, headers: response.headers });
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
/** Create an Octokit instance with per-request timeout + ETag revalidation. */
|
||||
export function createOctokit(token) {
|
||||
return new Octokit({ auth: token, request: { fetch: timeoutFetch } });
|
||||
return new Octokit({ auth: token, request: { fetch: createConditionalFetch(token) } });
|
||||
}
|
||||
|
||||
export function getOctokitOrNull() {
|
||||
|
||||
@@ -325,6 +325,59 @@ const safeListPulls = async (octokit, options) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Repo-level pull list, shared across every branch resolution. Ten worktree
|
||||
// branches of one repo need ONE pulls.list per state per TTL window, not ten
|
||||
// per-branch query fans. In-flight requests coalesce so concurrent branch
|
||||
// resolutions share a single GitHub call.
|
||||
const REPO_PULLS_CACHE_TTL_MS = 45_000;
|
||||
const repoPullsCache = new Map();
|
||||
|
||||
export const invalidateRepoPullsCache = (owner, repo) => {
|
||||
const prefix = `${normalizeText(owner)}/${normalizeText(repo)}::`;
|
||||
for (const key of repoPullsCache.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
repoPullsCache.delete(key);
|
||||
}
|
||||
}
|
||||
// A just-created PR must also clear remembered search misses for this repo.
|
||||
const repoNameLower = normalizeText(repo).toLowerCase();
|
||||
for (const key of _searchMissCache.keys()) {
|
||||
const [repoPart] = key.split('::');
|
||||
if (repoPart && repoPart.split(',').includes(repoNameLower)) {
|
||||
_searchMissCache.delete(key);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getRepoPulls = (octokit, repo, state, { force = false } = {}) => {
|
||||
const key = `${normalizeText(repo.owner)}/${normalizeText(repo.repo)}::${state}`;
|
||||
const cached = repoPullsCache.get(key);
|
||||
if (cached?.promise) {
|
||||
return cached.promise;
|
||||
}
|
||||
if (!force && cached && Date.now() - cached.fetchedAt < REPO_PULLS_CACHE_TTL_MS) {
|
||||
return Promise.resolve(cached);
|
||||
}
|
||||
|
||||
const promise = safeListPulls(octokit, {
|
||||
owner: repo.owner,
|
||||
repo: repo.repo,
|
||||
state,
|
||||
per_page: 100,
|
||||
}).then((prs) => {
|
||||
// `complete` means the first page held everything, so a miss is
|
||||
// authoritative: this repo has no PR in this state for any branch.
|
||||
const entry = { fetchedAt: Date.now(), prs, complete: prs.length < 100 };
|
||||
repoPullsCache.set(key, entry);
|
||||
return entry;
|
||||
}).catch((error) => {
|
||||
repoPullsCache.delete(key);
|
||||
throw error;
|
||||
});
|
||||
repoPullsCache.set(key, { promise });
|
||||
return promise;
|
||||
};
|
||||
|
||||
const parseRepoFromApiUrl = (value) => {
|
||||
const normalized = normalizeText(value);
|
||||
if (!normalized) {
|
||||
@@ -351,6 +404,24 @@ const parseRepoFromApiUrl = (value) => {
|
||||
const _searchApiDisabledRepos = new Map();
|
||||
const SEARCH_API_RETRY_MS = 5 * 60 * 1000; // retry after 5 minutes
|
||||
|
||||
// The Search API has its own tiny quota (30/min). A branch that has no PR
|
||||
// would otherwise re-search on every poll; a miss is extremely unlikely to
|
||||
// change within minutes, so remember it per repo+branch and back off.
|
||||
const SEARCH_MISS_RETRY_MS = 10 * 60 * 1000;
|
||||
const SEARCH_MISS_CACHE_MAX_ENTRIES = 500;
|
||||
const _searchMissCache = new Map();
|
||||
|
||||
const rememberSearchMiss = (key) => {
|
||||
_searchMissCache.delete(key);
|
||||
_searchMissCache.set(key, Date.now());
|
||||
if (_searchMissCache.size > SEARCH_MISS_CACHE_MAX_ENTRIES) {
|
||||
const oldest = _searchMissCache.keys().next().value;
|
||||
if (oldest !== undefined) {
|
||||
_searchMissCache.delete(oldest);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const searchFallbackPr = async ({ octokit, branch, repoNames }) => {
|
||||
// Build a repo key to check/store 403 status per-repo
|
||||
const repoKey = [...repoNames].sort().join(',').toLowerCase();
|
||||
@@ -361,6 +432,12 @@ const searchFallbackPr = async ({ octokit, branch, repoNames }) => {
|
||||
return null;
|
||||
}
|
||||
|
||||
const missKey = `${repoKey}::${normalizeText(branch)}`;
|
||||
const missedAt = _searchMissCache.get(missKey);
|
||||
if (missedAt && Date.now() - missedAt < SEARCH_MISS_RETRY_MS) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedRepoNames = new Set(repoNames.map((name) => normalizeLower(name)).filter(Boolean));
|
||||
|
||||
for (const state of ['open', 'closed']) {
|
||||
@@ -420,10 +497,11 @@ const searchFallbackPr = async ({ octokit, branch, repoNames }) => {
|
||||
}
|
||||
}
|
||||
|
||||
rememberSearchMiss(missKey);
|
||||
return null;
|
||||
};
|
||||
|
||||
const findFirstMatchingPr = async ({ octokit, target, branch, sourceCandidates }) => {
|
||||
const findFirstMatchingPr = async ({ octokit, target, branch, sourceCandidates, force = false, coverage = null }) => {
|
||||
const matcher = buildSourceMatcher(sourceCandidates);
|
||||
const sourceOwners = [];
|
||||
sourceCandidates.forEach((candidate) => pushUnique(sourceOwners, candidate.repo?.owner));
|
||||
@@ -434,6 +512,27 @@ const findFirstMatchingPr = async ({ octokit, target, branch, sourceCandidates }
|
||||
.sort((left, right) => matcher.compare(left, right, target.repo.repo))[0] ?? null;
|
||||
|
||||
for (const state of ['open', 'closed']) {
|
||||
// Shared per-repo list first: one pulls.list answers every branch of the
|
||||
// repo within the TTL. A miss in a complete list is authoritative — skip
|
||||
// the per-branch query fan entirely.
|
||||
let listWasComplete = false;
|
||||
try {
|
||||
const listEntry = await getRepoPulls(octokit, target.repo, state, { force });
|
||||
const fromList = pickPreferred(listEntry.prs);
|
||||
if (fromList) {
|
||||
return fromList;
|
||||
}
|
||||
listWasComplete = listEntry.complete;
|
||||
} catch {
|
||||
// fall through to the precise per-branch queries
|
||||
}
|
||||
if (listWasComplete) {
|
||||
continue;
|
||||
}
|
||||
if (coverage) {
|
||||
coverage.authoritative = false;
|
||||
}
|
||||
|
||||
for (const owner of sourceOwners) {
|
||||
const directCandidates = await safeListPulls(octokit, {
|
||||
owner: target.repo.owner,
|
||||
@@ -447,23 +546,12 @@ const findFirstMatchingPr = async ({ octokit, target, branch, sourceCandidates }
|
||||
return direct;
|
||||
}
|
||||
}
|
||||
|
||||
const fallbackCandidates = await safeListPulls(octokit, {
|
||||
owner: target.repo.owner,
|
||||
repo: target.repo.repo,
|
||||
state,
|
||||
per_page: 100,
|
||||
});
|
||||
const fallback = pickPreferred(fallbackCandidates);
|
||||
if (fallback) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export async function resolveGitHubPrStatus({ octokit, directory, branch, remoteName }) {
|
||||
export async function resolveGitHubPrStatus({ octokit, directory, branch, remoteName, force = false }) {
|
||||
// A deleted worktree can still have a session in the sidebar that keeps
|
||||
// requesting its PR status. Bail before touching git or GitHub for a
|
||||
// directory that no longer exists — otherwise every poll spends a git call
|
||||
@@ -506,6 +594,9 @@ export async function resolveGitHubPrStatus({ octokit, directory, branch, remote
|
||||
}
|
||||
|
||||
const sourceCandidates = resolvedTargets.slice();
|
||||
// When every consulted repo list was complete, a no-PR result is
|
||||
// authoritative and the expensive Search API fallback is pointless.
|
||||
const coverage = { authoritative: true };
|
||||
|
||||
let fallbackRepo = resolvedTargets[0].repo;
|
||||
let fallbackRemoteName = resolvedTargets[0].remoteName;
|
||||
@@ -530,6 +621,8 @@ export async function resolveGitHubPrStatus({ octokit, directory, branch, remote
|
||||
target,
|
||||
branch: candidateBranch,
|
||||
sourceCandidates,
|
||||
force,
|
||||
coverage,
|
||||
});
|
||||
if (pr) {
|
||||
return {
|
||||
@@ -543,6 +636,9 @@ export async function resolveGitHubPrStatus({ octokit, directory, branch, remote
|
||||
}
|
||||
|
||||
for (const candidateBranch of branchCandidates) {
|
||||
if (coverage.authoritative) {
|
||||
break;
|
||||
}
|
||||
const fallbackSearch = await searchFallbackPr({
|
||||
octokit,
|
||||
branch: candidateBranch,
|
||||
|
||||
@@ -7,6 +7,100 @@ const PR_STATUS_CACHE_MAX_ENTRIES = 200;
|
||||
// status on error, and a later poll fills it in.
|
||||
const PR_STATUS_RESOLVE_TIMEOUT_MS = 12_000;
|
||||
const prStatusCache = new Map();
|
||||
let resolvedAuthLoginPromise = null;
|
||||
const PR_CONTEXT_CACHE_TTL_MS = 30_000;
|
||||
const PR_CONTEXT_CACHE_MAX_ENTRIES = 50;
|
||||
const prContextCache = new Map();
|
||||
|
||||
function invalidatePrContextCache(directory, number) {
|
||||
for (const key of prContextCache.keys()) {
|
||||
try {
|
||||
const [cachedDirectory, cachedNumber] = JSON.parse(key);
|
||||
if (cachedDirectory === directory && (number == null || cachedNumber === number)) {
|
||||
prContextCache.delete(key);
|
||||
}
|
||||
} catch {
|
||||
prContextCache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Aggregate check runs into the summary shape shared by pr/status and
|
||||
// pulls/context. Keeps `pending` as queued+in_progress+unconcluded for
|
||||
// existing consumers while exposing the split and the earliest start time so
|
||||
// the UI can show live "running for N minutes" state.
|
||||
// A re-run leaves the previous completed check run in the listForRef payload
|
||||
// alongside the new in-progress one. GitHub's UI shows only the latest run
|
||||
// per (app, name); mirror that so counts match what users see on github.com.
|
||||
function dedupeCheckRuns(checkRuns) {
|
||||
const byName = new Map();
|
||||
for (const run of checkRuns) {
|
||||
const key = `${run?.app?.id ?? run?.app?.slug ?? ''}::${run?.name ?? ''}`;
|
||||
const previous = byName.get(key);
|
||||
if (!previous) {
|
||||
byName.set(key, run);
|
||||
continue;
|
||||
}
|
||||
const previousStartedAt = Date.parse(previous?.started_at || '') || 0;
|
||||
const startedAt = Date.parse(run?.started_at || '') || 0;
|
||||
if (startedAt > previousStartedAt
|
||||
|| (startedAt === previousStartedAt && (run?.id ?? 0) > (previous?.id ?? 0))) {
|
||||
byName.set(key, run);
|
||||
}
|
||||
}
|
||||
return Array.from(byName.values());
|
||||
}
|
||||
|
||||
function summarizeCheckRuns(checkRuns) {
|
||||
const counts = { success: 0, failure: 0, pending: 0, inProgress: 0, queued: 0 };
|
||||
let startedAt = null;
|
||||
for (const run of checkRuns) {
|
||||
const status = run?.status;
|
||||
const conclusion = run?.conclusion;
|
||||
if (status === 'in_progress') {
|
||||
counts.pending += 1;
|
||||
counts.inProgress += 1;
|
||||
const runStartedAt = typeof run?.started_at === 'string' ? run.started_at : null;
|
||||
if (runStartedAt && (!startedAt || runStartedAt < startedAt)) {
|
||||
startedAt = runStartedAt;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (status === 'queued') {
|
||||
counts.pending += 1;
|
||||
counts.queued += 1;
|
||||
continue;
|
||||
}
|
||||
if (!conclusion) {
|
||||
counts.pending += 1;
|
||||
continue;
|
||||
}
|
||||
if (conclusion === 'success' || conclusion === 'neutral' || conclusion === 'skipped') {
|
||||
counts.success += 1;
|
||||
} else {
|
||||
counts.failure += 1;
|
||||
}
|
||||
}
|
||||
const total = counts.success + counts.failure + counts.pending;
|
||||
const state = counts.failure > 0
|
||||
? 'failure'
|
||||
: (counts.pending > 0 ? 'pending' : (total > 0 ? 'success' : 'unknown'));
|
||||
return { state, total, ...counts, ...(startedAt ? { startedAt } : {}) };
|
||||
}
|
||||
|
||||
function summarizeCombinedStatuses(statuses) {
|
||||
const counts = { success: 0, failure: 0, pending: 0 };
|
||||
statuses.forEach((s) => {
|
||||
if (s.state === 'success') counts.success += 1;
|
||||
else if (s.state === 'failure' || s.state === 'error') counts.failure += 1;
|
||||
else if (s.state === 'pending') counts.pending += 1;
|
||||
});
|
||||
const total = counts.success + counts.failure + counts.pending;
|
||||
const state = counts.failure > 0
|
||||
? 'failure'
|
||||
: (counts.pending > 0 ? 'pending' : (total > 0 ? 'success' : 'unknown'));
|
||||
return { state, total, ...counts, inProgress: counts.pending, queued: 0 };
|
||||
}
|
||||
|
||||
function withTimeout(promise, timeoutMs, label) {
|
||||
let timer;
|
||||
@@ -435,7 +529,13 @@ export function registerGitHubRoutes(app) {
|
||||
const originalJson = res.json.bind(res);
|
||||
res.json = (data) => {
|
||||
if (data && data.connected === true) {
|
||||
setPrStatusCache(cacheKey, data, Date.now());
|
||||
// Freshness stamp travels with the payload (and survives cache
|
||||
// serves) so clients can refuse to overwrite newer data with a
|
||||
// stale cached response.
|
||||
if (typeof data.fetchedAt !== 'number') {
|
||||
data.fetchedAt = Date.now();
|
||||
}
|
||||
setPrStatusCache(cacheKey, data, data.fetchedAt);
|
||||
}
|
||||
return originalJson(data);
|
||||
};
|
||||
@@ -453,6 +553,7 @@ export function registerGitHubRoutes(app) {
|
||||
directory,
|
||||
branch,
|
||||
remoteName: remote,
|
||||
force,
|
||||
}),
|
||||
PR_STATUS_RESOLVE_TIMEOUT_MS,
|
||||
'resolveGitHubPrStatus',
|
||||
@@ -484,31 +585,9 @@ export function registerGitHubRoutes(app) {
|
||||
ref: sha,
|
||||
per_page: 100,
|
||||
});
|
||||
const checkRuns = Array.isArray(runs?.data?.check_runs) ? runs.data.check_runs : [];
|
||||
const checkRuns = dedupeCheckRuns(Array.isArray(runs?.data?.check_runs) ? runs.data.check_runs : []);
|
||||
if (checkRuns.length > 0) {
|
||||
const counts = { success: 0, failure: 0, pending: 0 };
|
||||
for (const run of checkRuns) {
|
||||
const status = run?.status;
|
||||
const conclusion = run?.conclusion;
|
||||
if (status === 'queued' || status === 'in_progress') {
|
||||
counts.pending += 1;
|
||||
continue;
|
||||
}
|
||||
if (!conclusion) {
|
||||
counts.pending += 1;
|
||||
continue;
|
||||
}
|
||||
if (conclusion === 'success' || conclusion === 'neutral' || conclusion === 'skipped') {
|
||||
counts.success += 1;
|
||||
} else {
|
||||
counts.failure += 1;
|
||||
}
|
||||
}
|
||||
const total = counts.success + counts.failure + counts.pending;
|
||||
const state = counts.failure > 0
|
||||
? 'failure'
|
||||
: (counts.pending > 0 ? 'pending' : (total > 0 ? 'success' : 'unknown'));
|
||||
checks = { state, total, ...counts };
|
||||
checks = summarizeCheckRuns(checkRuns);
|
||||
}
|
||||
} catch {
|
||||
// ignore and fall back
|
||||
@@ -522,17 +601,7 @@ export function registerGitHubRoutes(app) {
|
||||
ref: sha,
|
||||
});
|
||||
const statuses = Array.isArray(combined?.data?.statuses) ? combined.data.statuses : [];
|
||||
const counts = { success: 0, failure: 0, pending: 0 };
|
||||
statuses.forEach((s) => {
|
||||
if (s.state === 'success') counts.success += 1;
|
||||
else if (s.state === 'failure' || s.state === 'error') counts.failure += 1;
|
||||
else if (s.state === 'pending') counts.pending += 1;
|
||||
});
|
||||
const total = counts.success + counts.failure + counts.pending;
|
||||
const state = counts.failure > 0
|
||||
? 'failure'
|
||||
: (counts.pending > 0 ? 'pending' : (total > 0 ? 'success' : 'unknown'));
|
||||
checks = { state, total, ...counts };
|
||||
checks = summarizeCombinedStatuses(statuses);
|
||||
} catch {
|
||||
checks = null;
|
||||
}
|
||||
@@ -543,7 +612,20 @@ export function registerGitHubRoutes(app) {
|
||||
let canMerge = false;
|
||||
try {
|
||||
const auth = getGitHubAuth();
|
||||
const username = auth?.user?.login;
|
||||
// gh-CLI tokens have no persisted user record; resolve the login from
|
||||
// the API once (memoized) so permissions still resolve for them.
|
||||
let username = auth?.user?.login;
|
||||
if (!username) {
|
||||
if (!resolvedAuthLoginPromise) {
|
||||
resolvedAuthLoginPromise = octokit.rest.users.getAuthenticated()
|
||||
.then((resp) => resp?.data?.login || null)
|
||||
.catch(() => {
|
||||
resolvedAuthLoginPromise = null;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
username = await resolvedAuthLoginPromise;
|
||||
}
|
||||
if (username) {
|
||||
const perm = await octokit.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner: searchRepo.owner,
|
||||
@@ -790,6 +872,10 @@ export function registerGitHubRoutes(app) {
|
||||
const headBranch = head.includes(':') ? head.split(':')[1] || head : head;
|
||||
const createCacheKey = `${directory}::${headBranch}::${remote}`;
|
||||
prStatusCache.delete(createCacheKey);
|
||||
if (repo?.owner && repo?.repo) {
|
||||
const { invalidateRepoPullsCache } = await import('./pr-status.js');
|
||||
invalidateRepoPullsCache(repo.owner, repo.repo);
|
||||
}
|
||||
|
||||
return res.json({
|
||||
number: pr.number,
|
||||
@@ -881,6 +967,7 @@ export function registerGitHubRoutes(app) {
|
||||
return res.status(500).json({ error: 'Failed to update PR' });
|
||||
}
|
||||
|
||||
invalidatePrContextCache(directory, number);
|
||||
return res.json({
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
@@ -928,6 +1015,9 @@ export function registerGitHubRoutes(app) {
|
||||
pull_number: number,
|
||||
merge_method: method,
|
||||
});
|
||||
invalidatePrContextCache(directory, number);
|
||||
const { invalidateRepoPullsCache } = await import('./pr-status.js');
|
||||
invalidateRepoPullsCache(repo.owner, repo.repo);
|
||||
return res.json({ merged: Boolean(result?.data?.merged), message: result?.data?.message });
|
||||
} catch (error) {
|
||||
if (error?.status === 403) {
|
||||
@@ -986,6 +1076,11 @@ export function registerGitHubRoutes(app) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
invalidatePrContextCache(directory, number);
|
||||
{
|
||||
const { invalidateRepoPullsCache } = await import('./pr-status.js');
|
||||
invalidateRepoPullsCache(repo.owner, repo.repo);
|
||||
}
|
||||
return res.json({ ready: true });
|
||||
} catch (error) {
|
||||
console.error('Failed to mark PR ready:', error);
|
||||
@@ -1468,6 +1563,41 @@ export function registerGitHubRoutes(app) {
|
||||
}
|
||||
|
||||
const requestedRepo = getRequestedRepo(req);
|
||||
|
||||
// Short response cache: the checks view, comments view, and the
|
||||
// send-to-chat actions request the same context within seconds of each
|
||||
// other. Detail-inclusive responses satisfy detail-free requests.
|
||||
const contextCacheKey = JSON.stringify([
|
||||
directory,
|
||||
number,
|
||||
includeDiff,
|
||||
requestedRepo ? `${requestedRepo.owner}/${requestedRepo.repo}` : null,
|
||||
]);
|
||||
const cachedContext = prContextCache.get(contextCacheKey);
|
||||
if (cachedContext
|
||||
&& Date.now() - cachedContext.fetchedAt < PR_CONTEXT_CACHE_TTL_MS
|
||||
&& (cachedContext.includeCheckDetails || !includeCheckDetails)) {
|
||||
return res.json(cachedContext.data);
|
||||
}
|
||||
|
||||
const originalJson = res.json.bind(res);
|
||||
res.json = (data) => {
|
||||
if (data && data.pr) {
|
||||
if (typeof data.fetchedAt !== 'number') {
|
||||
data.fetchedAt = Date.now();
|
||||
}
|
||||
prContextCache.delete(contextCacheKey);
|
||||
prContextCache.set(contextCacheKey, { data, includeCheckDetails, fetchedAt: data.fetchedAt });
|
||||
if (prContextCache.size > PR_CONTEXT_CACHE_MAX_ENTRIES) {
|
||||
const oldest = prContextCache.keys().next().value;
|
||||
if (oldest !== undefined) {
|
||||
prContextCache.delete(oldest);
|
||||
}
|
||||
}
|
||||
}
|
||||
return originalJson(data);
|
||||
};
|
||||
|
||||
const repo = await resolveRepoForRequest(octokit, directory, requestedRepo);
|
||||
if (!repo) {
|
||||
return res.json({ connected: true, repo: null, pr: null });
|
||||
@@ -1564,7 +1694,7 @@ export function registerGitHubRoutes(app) {
|
||||
if (sha) {
|
||||
try {
|
||||
const runs = await octokit.rest.checks.listForRef({ owner: repo.owner, repo: repo.repo, ref: sha, per_page: 100 });
|
||||
const checkRuns = Array.isArray(runs?.data?.check_runs) ? runs.data.check_runs : [];
|
||||
const checkRuns = dedupeCheckRuns(Array.isArray(runs?.data?.check_runs) ? runs.data.check_runs : []);
|
||||
if (checkRuns.length > 0) {
|
||||
const parsedJobs = new Map();
|
||||
const parsedAnnotations = new Map();
|
||||
@@ -1665,6 +1795,7 @@ export function registerGitHubRoutes(app) {
|
||||
jobId: picked.id,
|
||||
url: picked.html_url,
|
||||
name: picked.name,
|
||||
workflowName: picked.workflow_name || undefined,
|
||||
conclusion: picked.conclusion,
|
||||
steps: Array.isArray(picked.steps)
|
||||
? picked.steps.map((s) => ({
|
||||
@@ -1686,6 +1817,8 @@ export function registerGitHubRoutes(app) {
|
||||
return {
|
||||
id: run.id,
|
||||
name: run.name,
|
||||
startedAt: run.started_at || undefined,
|
||||
completedAt: run.completed_at || undefined,
|
||||
app: run.app
|
||||
? {
|
||||
name: run.app.name || undefined,
|
||||
@@ -1718,27 +1851,7 @@ export function registerGitHubRoutes(app) {
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
const counts = { success: 0, failure: 0, pending: 0 };
|
||||
for (const run of checkRuns) {
|
||||
const status = run?.status;
|
||||
const conclusion = run?.conclusion;
|
||||
if (status === 'queued' || status === 'in_progress') {
|
||||
counts.pending += 1;
|
||||
continue;
|
||||
}
|
||||
if (!conclusion) {
|
||||
counts.pending += 1;
|
||||
continue;
|
||||
}
|
||||
if (conclusion === 'success' || conclusion === 'neutral' || conclusion === 'skipped') {
|
||||
counts.success += 1;
|
||||
} else {
|
||||
counts.failure += 1;
|
||||
}
|
||||
}
|
||||
const total = counts.success + counts.failure + counts.pending;
|
||||
const state = counts.failure > 0 ? 'failure' : (counts.pending > 0 ? 'pending' : (total > 0 ? 'success' : 'unknown'));
|
||||
checks = { state, total, ...counts };
|
||||
checks = summarizeCheckRuns(checkRuns);
|
||||
}
|
||||
} catch {
|
||||
// ignore and fall back
|
||||
@@ -1747,15 +1860,7 @@ export function registerGitHubRoutes(app) {
|
||||
try {
|
||||
const combined = await octokit.rest.repos.getCombinedStatusForRef({ owner: repo.owner, repo: repo.repo, ref: sha });
|
||||
const statuses = Array.isArray(combined?.data?.statuses) ? combined.data.statuses : [];
|
||||
const counts = { success: 0, failure: 0, pending: 0 };
|
||||
statuses.forEach((s) => {
|
||||
if (s.state === 'success') counts.success += 1;
|
||||
else if (s.state === 'failure' || s.state === 'error') counts.failure += 1;
|
||||
else if (s.state === 'pending') counts.pending += 1;
|
||||
});
|
||||
const total = counts.success + counts.failure + counts.pending;
|
||||
const state = counts.failure > 0 ? 'failure' : (counts.pending > 0 ? 'pending' : (total > 0 ? 'success' : 'unknown'));
|
||||
checks = { state, total, ...counts };
|
||||
checks = summarizeCombinedStatuses(statuses);
|
||||
} catch {
|
||||
checks = null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user