Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: close leaked X tabs, tick unreadable PRs, query collaborators server-side, and refuse to persist an unparseable model list (#3634)

[._.]/ Adam Eivy30d40892830b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 153e28e36c..a9075ec96d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -27,3 +27,5 @@
- CoS agents whose deliverable is a **report** are no longer scored as failures either. `/do:plan-task`, `/do:replan`, `/do:review` and `/do:scan` file an issue or print a report and are explicitly told to write no code, so they reach the idle reaper with a clean tree and no commit — the exact shape the reaper calls `idle-no-changes`. Widening the evidence probe to count in-run commits fixed only the commit-shaped half. Each launchable slashdo workflow now declares its deliverable on its catalog entry: the six that land a commit keep the clean-tree gate armed, and the four report-shaped ones carry `worktreeChangesExpected: false` and opt out of it, the same escape hatch a `reference-watch` run against a forge tracker already uses. `/do:next` still defers to the work tracker its claim flow actually resolved.
- Ten Digital Twin AI passes now actually run. Each shipped a `stage-config.json` entry with no prompt template behind it, so `buildPrompt()` threw "Template not found" and every call site's `.catch(() => null)` quietly took the fallback path — contradiction detection returned no issues, test generation and writing analysis produced nothing, trait extraction and confidence scoring never ran, enrichment served a generic canned question and stored answers unformatted, test scoring degraded to keyword matching, and import/interview analysis was skipped. All ten templates are now authored against what each call site's parser expects, `twin-interview-analyze` gained the config entry it was also missing, and a migration seeds both into existing installs. A new parity guard fails the build if a stage-config entry ever ships without its template again.
+
+- Four sentinel/lifecycle gaps from the v2.40.0 diff are closed. A redirected X handoff (login wall, X redirect) left the Chrome tab it owned open forever, because `openXHandoff` verifies the landing path *after* taking ownership with `closeAfterRead: false` — the tab is now closed before the verification error bubbles. A pending-merge PR whose `gh pr view` fails permanently (deleted PR, renamed repo, revoked token) never ticked, so `MAX_PENDING_MERGE_TICKS` never fired and the entry re-shelled to `gh` forever with nothing surfaced; an unreadable cycle now counts as a tick and times out with a notification naming the PR. The `collaborators` author filter fetched the 100 *oldest* issues by any author and filtered them in memory, hiding a claimable collaborator-filed issue on any busy repo while `self` worked fine — it now fans out one server-side `--author` query per trusted login (capped at 25, with the truncation logged) and merges. And an `api` provider whose `/models` returns HTTP 200 with a non-JSON or unrecognized body no longer overwrites the stored model list with `[]` under a "Models refreshed" toast; it throws with the real reason and leaves the list untouched, the same posture the CLI arms already take. A genuinely empty catalog still saves as empty.
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 9ac154a54e..d76e3fde34 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -839,17 +839,31 @@ export function createProviderService(config = {}) {
throw new Error(`HTTP ${response?.status || 'error'}`);
}
- const responseData = await response.json().catch(() => ({ data: [] }));
+ // THROW rather than degrade to `[]` — same posture as `_execCliModelList`.
+ // A 200 carrying a non-JSON body (an HTML login/captcha page, a proxy
+ // error page) or a shape with neither `data` nor `models` means the probe
+ // FAILED; returning an empty list makes that indistinguishable from a
+ // provider whose catalog is legitimately empty. `refreshProviderModels`
+ // persists whatever comes back and the UI toasts "Models refreshed", so
+ // the degraded path silently empties the model dropdown with no reason
+ // shown. Propagating the error leaves the stored list untouched and puts
+ // the real cause in the toast. A body that parses to a genuinely empty
+ // `data`/`models` array still returns `[]` — that distinction is the point.
+ const responseData = await response.json().catch(() => null);
+
+ if (!responseData || typeof responseData !== 'object') {
+ throw new Error('Model list response was not valid JSON');
+ }
- if (responseData.data && Array.isArray(responseData.data)) {
+ if (Array.isArray(responseData.data)) {
return responseData.data.map(m => m.id);
}
- if (responseData.models && Array.isArray(responseData.models)) {
+ if (Array.isArray(responseData.models)) {
return responseData.models;
}
- return [];
+ throw new Error('Model list response had no recognizable "data" or "models" array');
},
async _refreshCLIProviderModels(provider) {
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index 3a0805c7d9..e21175705f 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -1190,6 +1190,51 @@ describe('Provider Service', () => {
expect(updated).not.toBeNull();
expect(updated.models).toEqual([]);
});
+
+ it('throws and leaves the stored list untouched when a 200 body is not JSON', async () => {
+ // A captive portal / login page / proxy error served as HTTP 200. Degrading
+ // to `[]` here emptied the model dropdown while the UI toasted "Models
+ // refreshed" — indistinguishable from the legitimately-empty case above.
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => { throw new SyntaxError('Unexpected token < in JSON at position 0'); },
+ }));
+
+ const p = await providerService.createProvider({
+ name: 'Garbled API',
+ type: 'api',
+ endpoint: 'https://api.generic.com/v1',
+ models: ['model-a', 'model-b'],
+ allowCustomEndpoint: true,
+ });
+
+ const err = await providerService.refreshProviderModels(p.id).catch(e => e);
+ expect(err).toBeInstanceOf(Error);
+ expect(err.status).toBe(502);
+ expect(err.message).toMatch(/not valid JSON/);
+ expect((await providerService.getProviderById(p.id)).models).toEqual(['model-a', 'model-b']);
+ });
+
+ it('throws and leaves the stored list untouched when a 200 body has no recognizable shape', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ object: 'error', message: 'invalid api key' }),
+ }));
+
+ const p = await providerService.createProvider({
+ name: 'Shapeless API',
+ type: 'api',
+ endpoint: 'https://api.generic.com/v1',
+ models: ['model-a'],
+ allowCustomEndpoint: true,
+ });
+
+ const err = await providerService.refreshProviderModels(p.id).catch(e => e);
+ expect(err).toBeInstanceOf(Error);
+ expect(err.status).toBe(502);
+ expect(err.message).toMatch(/data.*models/);
+ expect((await providerService.getProviderById(p.id)).models).toEqual(['model-a']);
+ });
});
describe('reserved-key prototype safety (#2521)', () => {
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 69e3028c3c..b936d4e2da 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -245,6 +245,14 @@ const normalizeIssues = (raw, numberKey, authorKey) => raw.map((r) => ({
const GLAB_SELF_LOGIN_ARGS = ['api', 'user', '-q', '.username'];
+// Upper bound on the `--author <login>` queries the `collaborators` gate fans
+// out per detection pass. Each login costs one CLI round-trip, and this runs on
+// the perpetual-work cadence, so a repo with a large org-wide collaborator list
+// must not turn one detection into hundreds of `gh` shells. When the trusted set
+// exceeds the cap, the first N (you first, then the member listing order) are
+// queried and the truncation is LOGGED — never dropped silently.
+const MAX_COLLABORATOR_AUTHOR_QUERIES = 25;
+
// Per-forge config for the shared issue detector. Each entry captures only what
// differs between GitHub (`gh`) and GitLab (`glab`): the CLI + issue-list args,
// how owner/self/collaborators mode resolves the author filter, the transient
@@ -419,11 +427,13 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
// out-of-vocab value) = the @me security boundary. Transient resolver failures
// skip this dispatch and retry next tick rather than parking a full cadence.
let authorApplied = false;
- // Trusted login set for `collaborators` mode (null on every other path). The
- // gate is applied AFTER the list returns rather than as a `--author` arg —
- // both CLIs take a single account there — so `authorApplied` is still set, and
- // an empty post-filter list gets the same `no-authored-issues` treatment that
- // tells the user to widen the filter.
+ // Trusted login set for `collaborators` mode (null on every other path).
+ // Neither CLI's `--author` accepts a SET, so the gate fans out into ONE
+ // `--author <login>` query per trusted login and merges (see below) — the same
+ // server-side-filtered shape `self`/`owner` use, so `--limit 100` bounds
+ // *authored* issues rather than paging the 100 oldest issues by any author.
+ // `authorApplied` is still set, so an empty merged list gets the same
+ // `no-authored-issues` treatment that tells the user to widen the filter.
let trustedLogins = null;
if (issueAuthorFilter === 'any') {
// no --author filter
@@ -454,23 +464,53 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
authorApplied = true;
}
- const res = await runCli(cfg.cli, args, repoPath);
- if (res.code !== 0) return transient(cfg.listFail);
- let raw;
- try {
- raw = JSON.parse(res.stdout || '[]');
- } catch {
- return transient(cfg.parseFail);
+ // One issue-list invocation: run it, parse it, and report the forge-flavored
+ // transient reason on any failure. Shared by the single-query paths and by the
+ // `collaborators` per-login fan-out below.
+ const listIssues = async (extraArgs = []) => {
+ const res = await runCli(cfg.cli, [...args, ...extraArgs], repoPath);
+ if (res.code !== 0) return { error: cfg.listFail };
+ let parsed;
+ try {
+ parsed = JSON.parse(res.stdout || '[]');
+ } catch {
+ return { error: cfg.parseFail };
+ }
+ if (!Array.isArray(parsed)) return { error: cfg.parseFail };
+ return { issues: cfg.normalize(parsed) };
+ };
+
+ let issues;
+ if (trustedLogins) {
+ // Fan out one server-side `--author` query per trusted login and merge by
+ // issue number. Post-filtering a single unfiltered page would silently hide
+ // a claimable collaborator-filed issue on any repo with more than
+ // `--limit 100` open issues (it would park with `no-authored-issues` while
+ // the same repo works fine under `self`).
+ const logins = [...trustedLogins];
+ const queried = logins.slice(0, MAX_COLLABORATOR_AUTHOR_QUERIES);
+ if (queried.length < logins.length) {
+ // Never silent: a truncated set means issues from the dropped logins are
+ // invisible this pass, which is exactly the failure mode being fixed.
+ console.warn(`⚠️ Collaborators author filter capped at ${queried.length} of ${logins.length} trusted logins — issues filed by the other ${logins.length - queried.length} are not listed this pass`);
+ }
+ const merged = new Map();
+ for (const login of queried) {
+ const out = await listIssues(['--author', login]);
+ if (out.error) return transient(out.error);
+ for (const issue of out.issues) merged.set(issue.number, issue);
+ }
+ issues = [...merged.values()];
+ } else {
+ const out = await listIssues();
+ if (out.error) return transient(out.error);
+ issues = out.issues;
}
- if (!Array.isArray(raw)) return transient(cfg.parseFail);
-
- let issues = cfg.normalize(raw);
- // `collaborators` gate: keep only issues whose author is in the trusted set.
- // An unresolvable author (missing/blank login) is DROPPED, never kept — the
- // gate is a security boundary, so "can't tell who filed it" resolves to "not
- // trusted". The query carried no `--author` on this path, so `raw.length` IS
- // the unfiltered open count — remember it instead of re-listing below.
- const knownOpenCount = trustedLogins ? raw.length : null;
+
+ // `collaborators` gate, belt-and-braces over the `--author` queries above:
+ // keep only issues whose author is in the trusted set. An unresolvable author
+ // (missing/blank login) is DROPPED, never kept — the gate is a security
+ // boundary, so "can't tell who filed it" resolves to "not trusted".
if (trustedLogins) issues = issues.filter((i) => trustedLogins.has(i.authorLogin));
if (issues.length === 0) {
@@ -483,8 +523,8 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
// reason.)
// Reporting a flat "no open issues" there hid a claimable queue behind a
// full recheck park (the "open issues exist but the task still parked"
- // failure this fixes). Recover the unfiltered count — free when the gate ran
- // client-side, otherwise a re-probe WITHOUT the author filter — and if issues
+ // failure this fixes). Recover the unfiltered count with a re-probe WITHOUT
+ // the author filter — and if issues
// exist, park with the actionable `no-authored-issues` reason + the real open
// count so the user is told to widen the filter, not that there is nothing
// to do. The count is raw open issues (any author), not claimable ones —
@@ -492,7 +532,7 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self' } =
// when the other-authored issues are all blocked/assigned/epics. Counting
// claimable ones would cost the full skip-list scan here.
if (authorApplied) {
- const openCount = knownOpenCount ?? (await countOpenIssuesUnfiltered(cfg, repoPath));
+ const openCount = await countOpenIssuesUnfiltered(cfg, repoPath);
if (openCount > 0) return parked('no-authored-issues', openCount);
}
return parked('no-open-issues');
diff --git a/server/services/perpetualWork.test.js b/server/services/perpetualWork.test.js
index 3019695ccc..7c3d7fc813 100644
--- a/server/services/perpetualWork.test.js
+++ b/server/services/perpetualWork.test.js
@@ -390,57 +390,104 @@ describe('perpetualWork', () => {
});
// `gh issue list --author` takes exactly ONE account, so the collaborators
- // gate can't be a query — it's a client-side filter over the unfiltered list,
- // which is what these cover.
+ // gate fans out into one server-side `--author <login>` query per trusted
+ // login and merges — post-filtering a single unfiltered page hid claimable
+ // issues past `--limit 100` on a busy repo. These cover that fan-out.
describe('collaborators filter', () => {
// gh api probes: `.login` (self) then the paginated collaborator logins.
- const routeCollaborators = ({ me = 'alice', collaborators = 'bob\ncarol\n', collabCode = 0, issues = [] } = {}) => {
+ // `issuesByAuthor` maps a lowercased login to the issues that author filed.
+ const routeCollaborators = ({ me = 'alice', collaborators = 'bob\ncarol\n', collabCode = 0, issuesByAuthor = {} } = {}) => {
spawn.mockImplementation((cmd, args = []) => {
if (cmd === 'gh' && args[0] === 'api' && args.includes('user')) return fakeChild(`${me}\n`);
if (cmd === 'gh' && args[0] === 'api') return fakeChild(collabCode === 0 ? collaborators : '', collabCode);
- if (cmd === 'gh' && args[0] === 'issue') return fakeChild(JSON.stringify(issues));
+ if (cmd === 'gh' && args[0] === 'issue') {
+ const authorIdx = args.indexOf('--author');
+ if (authorIdx === -1) return fakeChild(JSON.stringify(Object.values(issuesByAuthor).flat()));
+ return fakeChild(JSON.stringify(issuesByAuthor[args[authorIdx + 1]] || []));
+ }
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
return fakeChild('');
});
};
- it('keeps issues filed by you or a collaborator and drops everyone else', async () => {
- routeCollaborators({ issues: [
- { number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } },
- { number: 2, title: 'a teammate\'s', assignees: [], labels: [], author: { login: 'Bob' } },
- { number: 3, title: 'a stranger\'s', assignees: [], labels: [], author: { login: 'mallory' } }
- ] });
+ const authorListCalls = () => spawn.mock.calls
+ .filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue' && a.includes('--author'))
+ .map(([, a]) => a[a.indexOf('--author') + 1]);
+
+ it('issues one --author query per trusted login and merges the results', async () => {
+ // The pre-fix shape (one unfiltered `--limit 100` page, filtered in
+ // memory) made a collaborator-filed issue past the first page invisible.
+ routeCollaborators({ issuesByAuthor: {
+ alice: [{ number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } }],
+ bob: [{ number: 2, title: 'a teammate\'s', assignees: [], labels: [], author: { login: 'Bob' } }],
+ carol: []
+ } });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out.actionable).toBe(true);
// #2's login differs in case from the collaborator listing — the gate is
// case-insensitive, so a teammate isn't silently dropped.
expect(out.sample).toEqual([1, 2]);
expect(out.total).toBe(2);
- // The listing itself is unfiltered: the trusted SET can't be a --author arg.
- const listCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'gh' && a[0] === 'issue');
- expect(listCall[1]).not.toContain('--author');
- expect(listCall[1].join(' ')).toContain('author'); // …but the payload carries it
+ expect(authorListCalls()).toEqual(['alice', 'bob', 'carol']);
+ });
+
+ it('de-duplicates an issue returned by more than one author query', async () => {
+ routeCollaborators({ issuesByAuthor: {
+ alice: [{ number: 7, title: 'shared', assignees: [], labels: [], author: { login: 'alice' } }],
+ bob: [{ number: 7, title: 'shared', assignees: [], labels: [], author: { login: 'alice' } }],
+ carol: []
+ } });
+ const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
+ expect(out.sample).toEqual([7]);
+ expect(out.total).toBe(1);
});
it('drops an issue whose author is unresolvable (unknown ⇒ untrusted)', async () => {
- routeCollaborators({ issues: [
- { number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } },
- { number: 2, title: 'no author field', assignees: [], labels: [] }
- ] });
+ routeCollaborators({ issuesByAuthor: {
+ alice: [
+ { number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } },
+ { number: 2, title: 'no author field', assignees: [], labels: [] }
+ ],
+ bob: [], carol: []
+ } });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out.sample).toEqual([1]);
});
- it('reports no-authored-issues with the real open count, reusing the list it already fetched', async () => {
- routeCollaborators({ issues: [
- { number: 1, title: 'x', assignees: [], labels: [], author: { login: 'mallory' } },
- { number: 2, title: 'y', assignees: [], labels: [], author: { login: 'eve' } }
- ] });
+ it('goes transient when one of the per-author list queries fails', async () => {
+ spawn.mockImplementation((cmd, args = []) => {
+ if (cmd === 'gh' && args[0] === 'api' && args.includes('user')) return fakeChild('alice\n');
+ if (cmd === 'gh' && args[0] === 'api') return fakeChild('bob\n');
+ if (cmd === 'gh' && args[0] === 'issue') {
+ return args[args.indexOf('--author') + 1] === 'bob' ? fakeChild('', 1) : fakeChild('[]');
+ }
+ return fakeChild('');
+ });
+ const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
+ expect(out).toMatchObject({ actionable: false, reason: 'gh-list-failed', transient: true });
+ });
+
+ it('caps the fan-out and logs the truncation rather than dropping logins silently', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const many = Array.from({ length: 40 }, (_, i) => `member${i}`).join('\n');
+ routeCollaborators({ collaborators: many, issuesByAuthor: {} });
+ await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
+ // alice + 40 members = 41 trusted logins, capped at 25 queries.
+ expect(authorListCalls()).toHaveLength(25);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('capped at 25 of 41'));
+ warn.mockRestore();
+ });
+
+ it('reports no-authored-issues with the real open count from an unfiltered re-probe', async () => {
+ routeCollaborators({ issuesByAuthor: {
+ mallory: [{ number: 1, title: 'x', assignees: [], labels: [], author: { login: 'mallory' } }],
+ eve: [{ number: 2, title: 'y', assignees: [], labels: [], author: { login: 'eve' } }]
+ } });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ actionable: false, count: 0, total: 2, reason: 'no-authored-issues' });
- // The gate ran client-side over an UNfiltered query, so the open-issue
- // denominator was already in hand — no duplicate list call.
- expect(spawn.mock.calls.filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue')).toHaveLength(1);
+ // The author-filtered queries can't supply the unfiltered denominator, so
+ // exactly one extra list runs WITHOUT --author.
+ expect(spawn.mock.calls.filter(([cmd, a]) => cmd === 'gh' && a[0] === 'issue' && !a.includes('--author'))).toHaveLength(1);
});
it('goes transient with a remedy (never silently narrows to self) when the collaborators probe fails', async () => {
@@ -448,9 +495,7 @@ describe('perpetualWork', () => {
// would hide a teammate's claimable issue with no explanation — and since
// it fails identically forever, the result must name the way out rather
// than leaving the caller to say "try again shortly".
- routeCollaborators({ collabCode: 1, issues: [
- { number: 1, title: 'mine', assignees: [], labels: [], author: { login: 'alice' } }
- ] });
+ routeCollaborators({ collabCode: 1 });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ actionable: false, reason: 'gh-collaborators-failed', transient: true, cli: 'gh' });
expect(out.remedy).toMatch(/push access/);
@@ -458,7 +503,7 @@ describe('perpetualWork', () => {
});
it('goes transient when the authenticated login can\'t be resolved', async () => {
- routeCollaborators({ me: '', issues: [] });
+ routeCollaborators({ me: '' });
const out = await detectGithubIssues(app, { issueAuthorFilter: 'collaborators' });
expect(out).toMatchObject({ reason: 'gh-unavailable', transient: true });
});
@@ -607,11 +652,15 @@ describe('perpetualWork', () => {
if (cmd === 'glab' && args[0] === 'api' && args.includes('user')) return fakeChild('octo\n');
if (cmd === 'glab' && args[0] === 'api') return fakeChild('teammate\n');
if (cmd === 'glab' && args[0] === 'issue') {
- return fakeChild(JSON.stringify([
- { iid: 10, title: 'mine', assignees: [], labels: [], author: { username: 'octo' } },
- { iid: 11, title: 'a member\'s', assignees: [], labels: [], author: { username: 'teammate' } },
- { iid: 12, title: 'a stranger\'s', assignees: [], labels: [], author: { username: 'drive-by' } }
- ]));
+ const byAuthor = {
+ octo: [{ iid: 10, title: 'mine', assignees: [], labels: [], author: { username: 'octo' } }],
+ teammate: [{ iid: 11, title: 'a member\'s', assignees: [], labels: [], author: { username: 'teammate' } }],
+ 'drive-by': [{ iid: 12, title: 'a stranger\'s', assignees: [], labels: [], author: { username: 'drive-by' } }]
+ };
+ const idx = args.indexOf('--author');
+ return fakeChild(JSON.stringify(idx === -1
+ ? Object.values(byAuthor).flat()
+ : byAuthor[args[idx + 1]] || []));
}
if (cmd === 'git' && args[0] === 'branch') return fakeChild('main\n');
if (cmd === 'glab' && args[0] === 'mr') return fakeChild('[]');
@@ -621,8 +670,12 @@ describe('perpetualWork', () => {
expect(out.sample).toEqual([10, 11]);
const membersCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'api' && String(a[2] || '').includes('members'));
expect(membersCall[1]).toContain('projects/:id/members/all');
- const listCall = spawn.mock.calls.find(([cmd, a]) => cmd === 'glab' && a[0] === 'issue');
- expect(listCall[1]).not.toContain('--author');
+ // The trusted SET can't be one `--author` arg, so it fans out to one
+ // server-side query per login — the outsider's issue is never listed.
+ const authored = spawn.mock.calls
+ .filter(([cmd, a]) => cmd === 'glab' && a[0] === 'issue' && a.includes('--author'))
+ .map(([, a]) => a[a.indexOf('--author') + 1]);
+ expect(authored).toEqual(['octo', 'teammate']);
});
it('collaborators filter goes transient when the members probe fails', async () => {
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 8f250191e4..a34e5b16c1 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -330,8 +330,22 @@ export async function processPendingMergePrs(app) {
const key = pendingMergeKey(entry);
const prView = await readPendingPullRequest(repoSpec, entry.prNumber);
if (!prView) {
- outcomes.set(key, entry);
+ // An unreadable PR is still a cycle this entry spent pending, so it has to
+ // tick. A PR whose `gh pr view` fails PERMANENTLY (deleted PR, renamed
+ // repo, revoked token) would otherwise be re-queued unchanged forever:
+ // MAX_PENDING_MERGE_TICKS never fires, the entry leaks in apps.json, and
+ // we re-shell to `gh` on every cadence with nothing surfaced to the user.
+ // `result.errors` accounting is unchanged — the cycle is both an error and
+ // a tick.
result.errors += 1;
+ const unreadable = { ...entry, ticks: entry.ticks + 1 };
+ if (unreadable.ticks >= MAX_PENDING_MERGE_TICKS) {
+ await notifyPendingMergeTimeout(app, entry, 'it could not be read from the forge');
+ outcomes.set(key, null);
+ result.timedOut += 1;
+ } else {
+ outcomes.set(key, unreadable);
+ }
continue;
}
result.checked += 1;
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 2bbadb172b..4ba43764e7 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -258,6 +258,36 @@ describe('merge-only PR watcher', () => {
}));
expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
});
+
+ it('ticks an unreadable PR so a permanently-broken entry can time out', async () => {
+ // `gh pr view` fails (deleted PR / renamed repo / revoked token). Counting
+ // this cycle as an error but NOT as a tick re-queued the entry unchanged
+ // forever — MAX_PENDING_MERGE_TICKS never fired and it leaked in apps.json.
+ const app = pendingApp([pendingMerge({ ticks: 2 })]);
+ mockApps.set(app.id, app);
+ execGhMock.mockRejectedValueOnce(new Error('could not resolve to a PullRequest'));
+
+ const result = await processPendingMergePrs(app);
+
+ expect(result).toMatchObject({ ok: true, checked: 0, errors: 1, timedOut: 0 });
+ expect(readPendingMergePrs(mockApps.get('app1'))[0].ticks).toBe(3);
+ });
+
+ it('times out and notifies once a permanently-unreadable PR exhausts its tick budget', async () => {
+ const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);
+ mockApps.set(app.id, app);
+ execGhMock.mockRejectedValueOnce(new Error('could not resolve to a PullRequest'));
+
+ const result = await processPendingMergePrs(app);
+
+ expect(result).toMatchObject({ ok: true, errors: 1, timedOut: 1 });
+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'agent_warning',
+ link: 'https://github.com/o/r/pull/88',
+ description: expect.stringContaining('could not be read from the forge'),
+ }));
+ expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
+ });
});
describe('sweepPendingMergePrs', () => {
diff --git a/server/services/xBrowser.js b/server/services/xBrowser.js
index db48cecb26..3a4cda461d 100644
--- a/server/services/xBrowser.js
+++ b/server/services/xBrowser.js
@@ -1,5 +1,5 @@
import { isPrivateAddress } from '../lib/safeUrlFetch.js';
-import { navigateToUrlPinned } from './browserService.js';
+import { closeCdpPage, navigateToUrlPinned } from './browserService.js';
const ORIGIN = 'https://x.com';
const USERNAME_PATTERN = /^[A-Za-z0-9_]{1,15}$/;
@@ -59,6 +59,21 @@ export async function openXHandoff({ kind, value = '' }) {
settleMs: 500,
closeAfterRead: false,
});
- verifyFinalXPath(target, page.url);
+ // `closeAfterRead: false` means THIS function owns the tab from here on. If
+ // the final-path check rejects the landing page (an X redirect, a login wall),
+ // nobody downstream ever learns the page id — so close it here before the
+ // throw bubbles, or every failed handoff leaks a Chrome tab. try/finally, not
+ // try/catch: the verification error still bubbles to the error middleware.
+ let verified = false;
+ try {
+ verifyFinalXPath(target, page.url);
+ verified = true;
+ } finally {
+ if (!verified) {
+ await closeCdpPage(page.id).catch((err) => {
+ console.error(`❌ Failed to close redirected X handoff tab ${page.id}: ${err.message}`);
+ });
+ }
+ }
return { pageId: page.id, url: page.url };
}
diff --git a/server/services/xBrowser.test.js b/server/services/xBrowser.test.js
index 0a470146cd..e90d221432 100644
--- a/server/services/xBrowser.test.js
+++ b/server/services/xBrowser.test.js
@@ -1,12 +1,17 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const navigateToUrlPinned = vi.fn();
-vi.mock('./browserService.js', () => ({ navigateToUrlPinned }));
+const closeCdpPage = vi.fn();
+vi.mock('./browserService.js', () => ({ navigateToUrlPinned, closeCdpPage }));
const { fixedXUrl, openXHandoff, verifyFinalXPath } = await import('./xBrowser.js');
describe('X browser handoffs', () => {
- beforeEach(() => navigateToUrlPinned.mockReset());
+ beforeEach(() => {
+ navigateToUrlPinned.mockReset();
+ closeCdpPage.mockReset();
+ closeCdpPage.mockResolvedValue(undefined);
+ });
it('builds only the named fixed-origin destinations', () => {
expect(fixedXUrl('profile', 'example_user')).toBe('https://x.com/example_user');
@@ -28,4 +33,26 @@ describe('X browser handoffs', () => {
expect(() => verifyFinalXPath('https://x.com/example_user', 'https://example.com/example_user')).toThrow('left the fixed origin');
expect(() => verifyFinalXPath('https://x.com/example_user', 'https://x.com/another_user')).toThrow('different page than the one requested');
});
+
+ it('closes the tab it owns when the handoff lands on a redirected page', async () => {
+ // `closeAfterRead: false` hands tab ownership to openXHandoff; the caller
+ // never learns the page id when verification throws, so failing to close
+ // here leaked a Chrome tab on every redirected compose/profile handoff.
+ navigateToUrlPinned.mockResolvedValue({ id: 'page-2', url: 'https://x.com/i/flow/login' });
+ await expect(openXHandoff({ kind: 'profile', value: 'example_user' }))
+ .rejects.toThrow('different page than the one requested');
+ expect(closeCdpPage).toHaveBeenCalledWith('page-2');
+ });
+
+ it('does not close the tab on a verified handoff, and survives a failed close', async () => {
+ navigateToUrlPinned.mockResolvedValue({ id: 'page-3', url: 'https://x.com/example_user' });
+ await expect(openXHandoff({ kind: 'profile', value: 'example_user' })).resolves.toMatchObject({ pageId: 'page-3' });
+ expect(closeCdpPage).not.toHaveBeenCalled();
+
+ // A close that itself fails must not mask the verification error.
+ closeCdpPage.mockRejectedValue(new Error('CDP socket closed'));
+ navigateToUrlPinned.mockResolvedValue({ id: 'page-4', url: 'https://x.com/other_user' });
+ await expect(openXHandoff({ kind: 'profile', value: 'example_user' }))
+ .rejects.toThrow('different page than the one requested');
+ });
});