Skip to content

Commit efc8a56

Browse files
committed
Close bot session tabs after pull request closure
1 parent 6291c06 commit efc8a56

11 files changed

Lines changed: 184 additions & 14 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ git switch codex/issue-dialogue-capabilities
196196
git pull --ff-only
197197
```
198198

199-
Then complete update steps 2 and 3 (`0.5.0-beta.3`). Reopen each project you want
199+
Then complete update steps 2 and 3 (`0.5.0-beta.4`). Reopen each project you want
200200
the restarted service to handle.
201201

202202
## 4. Remove automation from one project
@@ -412,6 +412,14 @@ Set `"autoMerge": { "enabled": false }` to disable automatic merging.
412412
Starting a session shows a notification and opens a background tab when tabs
413413
are enabled. Use `/bot` to list tasks and open a session.
414414

415+
Closing or merging the PR automatically closes its known bot session tabs,
416+
including earlier rounds and media helpers. This also works for manual GitHub
417+
actions with `autoMerge` disabled. Closure is detected on the next repository
418+
scan; connected TUIs also refresh every 10 seconds. Busy tabs wait until their
419+
work finishes. Session history is preserved, and `/bot` can reopen a session.
420+
Reopening it manually keeps it open for the current TUI instance. No additional
421+
configuration is required.
422+
415423
A new comment from an authorized author on a tracked issue starts another round:
416424
acknowledgement, implementation, and a push to the same open PR. The mention does
417425
not need to be repeated. Comments received during execution wait for the next

‎docs/architecture.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ loads a generic scheduler, a GitHub dispatcher, and a terminal UI component.
1212
- **Executor:** generates an acknowledgement, runs an OpenCode session in an
1313
isolated Git worktree, verifies changes, and pushes the verified commit.
1414
- **Terminal UI:** subscribes to activity events and polls for missed updates.
15-
Opens background tabs and exposes the `/bot` task selector.
15+
Opens background tabs, closes task tabs after PR closure while retaining
16+
session history, and exposes the `/bot` task selector.
1617

1718
## Workflow
1819

‎docs/runtime.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,20 @@ The queue retains waiting questions and accepted replies across restarts.
4545
After restarting the service, load the owner project again to resume polling.
4646
No terminal UI is needed to answer in GitHub.
4747

48+
## Tabs after PR closure
49+
50+
Each repository scan checks the state of tracked PRs independently of the
51+
auto-merge setting and whether their issues are still open. A manual close,
52+
manual merge, or automatic merge sends the closed PR state to connected TUIs.
53+
Missed events are recovered by the TUI's activity polling, including on startup.
54+
55+
The TUI closes only tabs associated with that task's known main sessions and
56+
media helpers. Busy tabs wait until idle. Closing a tab never deletes a session,
57+
interrupts work, or removes a worktree. A tab reopened through `/bot` or history
58+
is not repeatedly closed by later polls in the same TUI instance. Sessions from
59+
new rounds are recorded in the queue; for older queues, cleanup can include only
60+
the session IDs still present in saved state or observed by the current TUI.
61+
4862
## Base branches
4963

5064
Write your preference in the issue or an authorized comment in ordinary language:

‎package-lock.json‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "opencode2-automation",
3-
"version": "0.5.0-beta.3",
3+
"version": "0.5.0-beta.4",
44
"description": "Issue-to-PR automation for OpenCode 2 with a scheduler and GitHub dispatcher",
55
"main": "./dist/index.js",
66
"files": [

‎src/activity.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@ export const Activity = z.object({
66
phase: z.string(), status: z.string(), sessionID: z.string().optional(),
77
worktree: z.string().optional(), sessionReady: z.boolean(), error: z.string().optional(),
88
prURL: z.string().optional(),
9+
prState: z.string().optional(), sessionIDs: z.array(z.string()).optional(),
910
});
1011
export type Activity = z.infer<typeof Activity>;
1112
export function activityOf(task: Task): Activity {
1213
return { key: task.key, repo: task.repo, issueNumber: task.issue.number, round: task.round ?? 1,
13-
phase: task.merged ? "merged" : task.phase, status: task.status,
14+
phase: task.merged ? "merged" : task.pr?.state === "closed" ? "pr_closed" : task.phase, status: task.status,
15+
sessionIDs: [...new Set([...task.sessionIDs ?? [], ...[task.previousSessionID, task.sessionID].filter((id): id is string => Boolean(id)), ...task.helpers?.map(h => h.id) ?? []])],
1416
...(task.sessionID ? { sessionID: task.sessionID } : {}),
1517
...(task.worktree ? { worktree: task.worktree } : {}),
1618
sessionReady: task.sessionReady ?? Boolean(task.promptAttempted),
1719
...(task.error || task.mergeError ? { error: task.error ?? task.mergeError } : {}),
18-
...(task.pr ? { prURL: task.pr.html_url } : {}) };
20+
...(task.pr ? { prURL: task.pr.html_url, prState: task.pr.state } : {}) };
1921
}

‎src/dispatcher.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ export const Task = z.object({
2424
helpers: z.array(z.object({ id: z.string(), parentID: z.string(), capability: z.enum(["vision", "audio"]) })).optional(),
2525
branch: z.string(), worktree: z.string().optional(), baseSha: z.string().optional(),
2626
sessionID: z.string().optional(), promptAttempted: z.boolean().optional(),
27+
sessionIDs: z.array(z.string()).optional(),
2728
sessionReady: z.boolean().optional(), round: z.number().int().positive().optional(),
2829
source: z.enum(["issue", "comment"]).optional(),
2930
feedback: z.array(Comment).optional(), pendingFeedback: z.array(Comment).optional(), commentCursor: z.number().optional(),
@@ -46,6 +47,7 @@ export interface GithubPort {
4647
comments(repo: string, number: number): Promise<Comment[]>;
4748
ensureComment(repo: string, number: number, marker: string, body: string): Promise<number>;
4849
findPull(repo: string, branch: string): Promise<Pull | undefined>;
50+
pull(repo: string, number: number): Promise<Pull>;
4951
ensurePull(repo: string, branch: string, base: string, title: string, body: string): Promise<Pull>;
5052
}
5153
export interface Executor {
@@ -76,6 +78,8 @@ export class Dispatcher {
7678
let announce = false;
7779
await this.serial.run(async () => {
7880
announce = Boolean(patch.sessionReady && !task.sessionReady) || Boolean(patch.status && patch.status !== task.status && ["done", "blocked", "failed", "waiting"].includes(patch.status));
81+
announce ||= patch.pr?.state === "closed" && task.pr?.state !== "closed";
82+
if (patch.sessionID) task.sessionIDs = [...new Set([...task.sessionIDs ?? [], ...[task.previousSessionID, task.sessionID, patch.sessionID].filter((id): id is string => Boolean(id))])];
7983
Object.assign(task, patch);
8084
await this.store.save(this.queue);
8185
});
@@ -89,6 +93,13 @@ export class Dispatcher {
8993
private async scanOnce() {
9094
let queued = 0, ignored = 0;
9195
for (const repo of this.options.repositories) {
96+
// Watch PR state independently of automatic merging, issue state, and
97+
// worker progress so manual closure/merge also reaches attached TUIs.
98+
for (const task of this.queue.tasks.filter(t => t.repo === repo.repo && t.pr && !t.merged)) {
99+
const pr = await this.github.pull(repo.repo, task.pr!.number);
100+
const merged = pr.merged === true || Boolean(pr.merged_at);
101+
if (pr.state !== task.pr!.state || merged) await this.update(task, { pr, ...(merged ? { merged: true } : {}) });
102+
}
92103
const issues = await this.github.issues(repo.repo);
93104
for (const tracked of this.queue.tasks.filter(t => t.repo === repo.repo)) {
94105
if (!issues.some(i => i.number === tracked.issue.number)) issues.push(await this.github.issue(repo.repo, tracked.issue.number));
@@ -301,14 +312,14 @@ export class Dispatcher {
301312
private async mergeOnce() {
302313
if (!this.options.autoMerge.enabled || !this.github.mergeApproved) return;
303314
for (const task of this.queue.tasks) {
304-
if (task.status !== "done" || !task.pr || !task.commit || task.merged || task.pendingFeedback?.length || (task.mergeNextAt ?? 0) > this.now()) continue;
315+
if (task.status !== "done" || !task.pr || task.pr.state === "closed" || !task.commit || task.merged || task.pendingFeedback?.length || (task.mergeNextAt ?? 0) > this.now()) continue;
305316
const repo = this.options.repositories.find(r => r.repo === task.repo);
306317
if (!repo) continue;
307318
// Older queues start watching now; historical approvals must not trigger an unexpected merge.
308319
if (!task.publishedAt) { await this.update(task, { publishedAt: this.now() }); continue; }
309320
try {
310321
await this.scan(); // Pick up issue feedback before considering a completed task for merge.
311-
if (task.pendingFeedback?.length) continue;
322+
if (task.pendingFeedback?.length || task.pr.state === "closed") continue;
312323
const merged = await this.github.mergeApproved(task.repo, task.pr.number, task.commit, task.publishedAt, repo.allowedAuthors, this.options.autoMerge);
313324
if (merged) {
314325
await this.github.ensureComment(task.repo, task.pr.number, `<!-- opencode2:${task.key}:merged -->`, "Pull request merged.");

‎src/github.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export const Issue = z.object({
99
export type Issue = z.infer<typeof Issue>;
1010
export const Comment = z.object({ id: z.number(), body: z.string(), user: z.object({ login: z.string(), type: z.string().optional() }) });
1111
export type Comment = z.infer<typeof Comment>;
12-
const Pull = z.object({ number: z.number(), html_url: z.string().url(), state: z.string() });
12+
const Pull = z.object({ number: z.number(), html_url: z.string().url(), state: z.string(), merged: z.boolean().optional(), merged_at: z.string().nullable().optional() });
1313
export type Pull = z.infer<typeof Pull>;
1414

1515
export class GithubError extends Error {
@@ -60,6 +60,9 @@ export class Github {
6060
const head = encodeURIComponent(`${repo.split("/")[0]}:${branch}`);
6161
return (await this.pages(`/repos/${repo}/pulls?state=all&head=${head}`, Pull))[0];
6262
}
63+
async pull(repo: string, number: number): Promise<Pull> {
64+
return Pull.parse(await this.request(`/repos/${repo}/pulls/${number}`));
65+
}
6366
async ensurePull(repo: string, branch: string, base: string, title: string, body: string): Promise<Pull> {
6467
return await this.findPull(repo, branch) ?? Pull.parse(await this.request(`/repos/${repo}/pulls`, "POST", { head: branch, base, title, body: await this.signed(body) }));
6568
}

‎src/ui.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,36 @@ export function setupUI(context: Plugin.Context) {
88
const rpc = context.client.rpc(GithubRpc);
99
const states = new Map<string, Activity>();
1010
const seen = new Set<string>();
11+
const sessions = new Map<string, Set<string>>();
12+
const closed = new Map<string, Set<string>>();
1113
let stopped = false, syncing = false;
1214
const controller = new AbortController();
1315
const receive = (raw: unknown, initial = false) => {
1416
if (stopped) return;
1517
const activity = Activity.parse(raw);
1618
if ((states.get(activity.key)?.round ?? 0) > activity.round) return;
1719
states.set(activity.key, activity);
20+
const known = sessions.get(activity.key) ?? new Set<string>();
21+
for (const id of [...(activity.sessionIDs ?? []), ...(activity.sessionID ? [activity.sessionID] : [])]) known.add(id);
22+
sessions.set(activity.key, known);
23+
if (activity.prState === "closed" || activity.phase === "merged") {
24+
// Closing a tab preserves its session. Handle each tab once so a person
25+
// can reopen it from /bot or history without the next poll closing it.
26+
seen.add(`${activity.key}:${activity.round}:started`);
27+
if (context.ui.tabs.enabled()) {
28+
const handled = closed.get(activity.key) ?? new Set<string>();
29+
const tabs = context.ui.tabs.list();
30+
for (const id of known) {
31+
if (handled.has(id)) continue;
32+
const tab = tabs.find(t => t.sessionID === id);
33+
if (tab?.busy) continue; // Retry after ongoing work finishes.
34+
if (!tab || context.ui.tabs.close(id)) handled.add(id);
35+
}
36+
closed.set(activity.key, handled);
37+
}
38+
return;
39+
}
40+
if (activity.prState === "open") closed.delete(activity.key);
1841
const started = activity.sessionReady && activity.sessionID && ["ready", "retry_wait"].includes(activity.status);
1942
const terminal = ["done", "blocked", "failed", "waiting"].includes(activity.status);
2043
const id = `${activity.key}:${activity.round}:${started ? "started" : activity.status}`;

‎test/core.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ function fixture() {
2727
issues: async () => [structuredClone(issue)], issue: async () => structuredClone(issue),
2828
ensureComment: async () => { events.push("comment"); return 42; },
2929
findPull: async () => undefined,
30+
pull: async (_repo, number) => ({ number, html_url: `https://github.com/owner/repo/pull/${number}`, state: "open" }),
3031
ensurePull: async () => { events.push("pr"); return { number: 2, html_url: "https://github.com/owner/repo/pull/2", state: "open" }; },
3132
};
3233
const executor: Executor = {
@@ -475,6 +476,58 @@ test("auto-merge can be disabled independently of issue processing", async () =>
475476
await d.init(); await d.scan(); await d.tick(); await d.tick(); assert.equal(called, false); assert.equal(d.status()[0]?.status, "done");
476477
});
477478

479+
for (const merged of [false, true]) {
480+
test(`scanning detects a manually ${merged ? "merged" : "closed"} PR even with auto-merge disabled and its issue closed`, async () => {
481+
const f = fixture(); const notifications: ReturnType<Dispatcher["activity"]>[number][] = [];
482+
const config = { ...options, autoMerge: { ...options.autoMerge, enabled: false } };
483+
const make = () => new Dispatcher(config, f.store, f.github, f.executor, new AbortController().signal, [], () => 1000, async a => { notifications.push(a); });
484+
let d = make(); await d.init(); await d.scan(); await d.tick();
485+
f.github.issues = async () => [];
486+
f.github.issue = async () => ({ ...issue, state: "closed" });
487+
f.github.pull = async (_repo, number) => ({ number, html_url: "https://github.com/owner/repo/pull/2", state: "closed", merged });
488+
await d.scan();
489+
assert.equal(d.status()[0]?.pr?.state, "closed");
490+
assert.equal(d.activity()[0]?.phase, merged ? "merged" : "pr_closed");
491+
assert.equal(notifications.filter(a => a.prState === "closed").length, 1);
492+
assert.deepEqual(notifications.at(-1)?.sessionIDs, ["ses_test"]);
493+
f.store.data = Queue.parse(JSON.parse(JSON.stringify(f.store.data)));
494+
d = make(); await d.init(); await d.scan(); await d.tick();
495+
assert.equal(d.activity()[0]?.prState, "closed");
496+
assert.equal(notifications.filter(a => a.prState === "closed").length, 1);
497+
});
498+
}
499+
500+
test("a failed PR state lookup does not announce closure or change saved state", async () => {
501+
const f = fixture(), d = f.make(); await d.init(); await d.scan(); await d.tick();
502+
f.github.pull = async () => { throw new Error("GitHub unavailable"); };
503+
await assert.rejects(d.scan(), /GitHub unavailable/);
504+
assert.equal(d.status()[0]?.pr?.state, "open"); assert.equal(d.activity()[0]?.prState, "open");
505+
});
506+
507+
test("main session IDs from every follow-up round survive restart for tab cleanup", async () => {
508+
const f = fixture(); let session = 0; let d = f.make();
509+
f.executor.run = async (_task, checkpoint) => { await checkpoint({ sessionID: `ses_${++session}` }); };
510+
await d.init(); await d.scan(); await d.tick();
511+
f.github.findPull = async () => ({ number: 2, html_url: "https://github.com/owner/repo/pull/2", state: "open" });
512+
for (const id of [50, 60]) {
513+
f.github.comments = async () => [{ id, body: "Please handle one more case", user: { login: "alice" } }];
514+
await d.scan(); await d.tick();
515+
}
516+
f.store.data = Queue.parse(JSON.parse(JSON.stringify(f.store.data)));
517+
d = f.make(); await d.init();
518+
assert.deepEqual(d.activity()[0]?.sessionIDs, ["ses_1", "ses_2", "ses_3"]);
519+
});
520+
521+
test("PR state lookup uses the exact PR number and retains merge metadata", async () => {
522+
const github = new Github("fake", new AbortController().signal, (async (input: string | URL | Request, init?: RequestInit) => {
523+
assert.equal(String(input), "https://api.github.com/repos/owner/repo/pulls/17");
524+
assert.equal(init?.method, "GET");
525+
return new Response(JSON.stringify({ number: 17, html_url: "https://github.com/owner/repo/pull/17", state: "closed", merged: true, merged_at: "2026-09-11T20:00:00Z" }));
526+
}) as typeof fetch);
527+
const pr = await github.pull("owner/repo", 17);
528+
assert.equal(pr.state, "closed"); assert.equal(pr.merged, true);
529+
});
530+
478531
test("issue questions are published once, survive restart, and resume only on an authorized reply", async () => {
479532
const f = fixture(); let d = f.make();
480533
f.github.ensureComment = async (_repo, _number, marker) => { f.events.push(marker.includes(":question:") ? "question" : "comment"); return marker.includes(":question:") ? 100 : 42; };

0 commit comments

Comments
 (0)