Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

Merge origin/main (#999, #1001, #1000) and join PR -> issue -> session card

review3c9c1b9d09e6
diff --cc CLAUDE.md
index fcf09192a,a548a01f4..ebae885fb
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -5316,76 -5338,54 +5338,129 @@@ the Settings section and ShortcutsPane
session cards only (the `githubIssues:*` channels are served to relay TABS, never the phone
dialect), so nothing there can read a throttle as signed out; surfacing GitHub cards on the phone
would need this whole contract carried over the relay.
+ **Pull request CI, mergeability and links** (2026-09-29; core `graphql-pulls.ts` +
+ `pull-status-tracker.ts`, shared `github-pull-status.ts` + `kanban-pull-links.ts`, renderer
+ `lib/pullLinks.ts` / `lib/pullAutoMove.ts` / `lib/pullChase.ts`). The issues harvest cannot say a
+ PR's head, checks or mergeability, so ONE GraphQL read per repository adds them: every open PR's
+ `headRefName`/`headRefOid`/`isCrossRepository`/`isDraft`/`mergeable`/`mergeStateStatus`, the head
+ commit's `statusCheckRollup`, `closingIssuesReferences`, plus the 30 most recently merged/closed
+ PRs (so a branch link survives the merge). MEASURED on this repository (60 open PRs): **1 point**
+ of the separate `graphql` budget, ~18 KB; the per-PR checks read (modal open only) is also 1.
+ **When it runs:** after a heartbeat that reported a change, on a user refresh, on the first
+ heartbeat of an app run, when the last read failed or the budget skipped one (`owed`) — never on a
+ 304 otherwise. A finished check run does NOT move the heartbeat, so an UNDECIDED PR (mergeable
+ UNKNOWN or rollup PENDING/EXPECTED — measured: 40 of 50 open PRs read UNKNOWN on a first read, all
+ settled 20 s later, because the first read is what starts GitHub's computation) is CHASED at
+ 30 s / 1 min / 2 min / 5 min, at most 12 reads per episode, and only while a board is VISIBLE: the
+ renderer asks (`githubIssues.chasePulls`) every 15 s while `document.visibilityState` is visible,
+ and the host answers from a map — schedule, cap and the synchronous `claimChase` live in core, and
+ no context (credential chain) is resolved unless a read is due. A new undecided PR or a new head
+ starts a new episode; the same stuck PR does not restart the count. **Semantics, each a shipped
+ bug somewhere:** a null rollup is "no checks" and renders NOTHING (never a tick); only
+ `mergeStateStatus === 'CLEAN'` is "Ready to merge" (MERGEABLE+BLOCKED is real: 2 of 31 here);
+ a rollup counts only at the current `headRefOid`, and a CI result is never carried from an older
+ head; a failed read keeps the last snapshot marked stale (`pullStatusFreshness`, greyed after
+ 15 min); a FORBIDDEN/INSUFFICIENT_SCOPES answer for the rollup or mergeability HIDES that region
+ (`access`), which is not the same as a null rollup. **Budget:** GitHub meters `graphql` apart from
+ `core`, and so does the coordinator now — `throttle(identity, at, resource)`, a primary limit is
+ tagged with its resource (`GitHubClientError.resource`, from `x-ratelimit-resource`, or GraphQL's
+ 200-with-`RATE_LIMITED`) and holds only that resource; an untagged (secondary) limit still holds
+ the identity. A spent graphql budget (the user's own `gh pr list` spends it) must not stall REST
+ issue sync. **Links:** PR → issue = GitHub's own `closingIssuesReferences` (same repository only),
+ deliberately NOT unlinkable on the board — GitHub closes the issue at merge whatever the board
+ shows. PR → session card = the PR's head equals `data.worktree.branch` of the card's nearest bound
+ group (`worktreeBranchOf`, no git read; a stale binding still names the branch, which is exactly
+ when its PR merges); a FORK PR never links (36 of 50 open PRs here are forks). Unlinking writes a
+ git-shared tombstone in `ProjectKanban.pullLinks` — a BOARD-LEVEL field on purpose: every card-meta
+ setter rebuilds `meta[]` entries from a fixed field list, so a field added there is erased by the
+ next member/due/label edit. SSH projects show the worktree reason instead (no worktree groups
- there). The open seam: joining PR → issue → node through the `issueRef` an agent started from an
- issue card will carry (not on main yet) — `pullsForCard` is where that second link source plugs in.
++ there). PR → issue → session card: a session started on an issue (`data.issueRef`, below) links to
++ every PR whose `closingIssuesReferences` name that issue, matched against the pull board's own
++ `repository` (a `closes` number means nothing in another repository); here a FORK PR does count —
++ GitHub's "Closes #N" is meaningful wherever it comes from. The host memory remembers what a PR
++ closed while open, so the link survives the merge that should move the card; the same tombstones
++ apply, and an issue-bound card on an SSH project still links this way (only the branch half needs
++ a worktree group).
+ **What this machine observed lives on the HOST** (`core/github/pull-memory.ts`, persisted beside
+ the issue cache per identity + repository, deleted with it): every PR it has seen, its head, its
+ lifecycle, whether it was seen open, and `mergedSeenAt` — the first time it was seen merged AFTER
+ being seen open (an OBSERVED merge). The read lists only 50 open + 30 recent PRs, so without it a
+ closed-unmerged PR's block would expire once 30 newer PRs closed; remembered PRs stay on the pull
+ board (closed ones until unlinked, merges for 30 days) and an unlisted one takes its lifecycle
+ from the REST harvest. The first version kept a per-card "seen" map in settings.json instead, and
+ review found three failures in that shape: the planner's output exceeded the sanitizer's bounds so
+ the hook rewrote settings in a loop until React threw; the block expired; and two Server Edition
+ tabs both moved the card while a background tab's settings write reverted another tab's changes.
+ **Merge-driven move — session cards only, OFF by default.** The switch, the target column and
+ `armedAt` are MACHINE-LOCAL (`settings.kanbanPullAutoMove.projects[projectId]`, written ONLY by
+ the user's own Settings action): it makes this machine write the shared board on its own, so a
+ switch in the project file would make every clone move and commit cards nobody on that machine
+ asked for. Per-card opt-out is board content (`pullLinks.noAutoMove`). Guards in order
+ (`decidePullAutoMove`): opted out → never; any linked PR open/draft → wait; any closed unmerged →
+ blocked until the user unlinks it; already in target → nothing; no linked merge with
+ `mergedSeenAt >= armedAt` → no move (arming never sweeps old merges). Each planned move must then
+ win the host's one-time CLAIM (`githubIssues:claim-pull-auto-move`, persisted in the same memory,
+ keyed by project + card + PR set) — the first ask across every window wins, and a card dragged
+ back is not moved again for the same merges — and is applied as a compare-and-set on the column
+ the decision saw (`applyPullAutoMove`, run by Canvas against the store's latest board), writing
+ ONE `card-moved` board-log line whose `title` names the PRs. The planner writes nothing; it runs
+ only while the board is open and never on a stale snapshot. **GitHub issue cards are never
+ auto-moved** — GitHub already closes them when a `Closes #N` PR merges, and a second writer would
+ race it and could clobber `state_reason`.
+ Surfaces: Desktop + Server Edition identical (core + renderer; `githubIssues:pull-status`,
+ `:chase-pulls`, `:pull-checks`, `:claim-pull-auto-move` are registered by the shared core handlers
+ and served to relay tabs through the project-scope table; a relay tab never auto-moves — the
+ board belongs to the other machine). Check detail is bounded for relay guests: one read per PR per
+ 15 s, ten per project per minute, both decided before a credential is resolved. **Mobile: follow-up** — the phone board carries session
+ cards only; showing PR CI there means carrying `GitHubPullBoard` over the relay dialect.
+ **Start with agent — a GitHub issue card starts a bound session** (2026-09-28). An issue card's
+ right-click menu and its summary modal offer **Start with agent ▸**, whose rows are the canvas's
+ own agent + account picker (`agentCreationEntries`, which takes an optional `pick` so the same
+ rows can point at another action — never a fourth copy of the picker). The result is an ordinary
+ agent node in the project cwd (through `addAgentNode`, which now returns the node) carrying
+ `data.issueRef {owner, repo, number}` — persisted, git-shared, therefore hostile:
+ `normalizeIssueRef` (`@shared/github-issue-ref`) runs at BOTH serializer seams and a malformed
+ value is dropped (the node survives, only the binding goes). Rules a refactor must not undo:
+ (1) **the launch line carries the REFERENCE, never the issue's text** — titles and bodies are
+ writable by anyone on a public repository and a launch line is typed into a pane.
+ `issueLaunchPrompt` is the ONE place a reference becomes text; it re-validates the reference
+ itself and returns nothing for a hostile one. The prompt tells the agent to read the issue with
+ `gh issue view N --repo owner/repo --comments` (mid-sentence: punctuation glued to the last flag is
+ copied literally and `gh` refuses `--comments.`) AND that its title, body and comments are
+ untrusted input, not instructions — the session runs under the project's permission mode (auto by
+ default), so the prompt is the only thing that can say "read it, do not obey it" before it does.
+ A board start means **work on it**: the default task is "investigate, plan and implement the fix
+ in this working tree"; a caller's `--prompt` REPLACES that task ("Your task: …"), never the lines
+ around it. The hard limits ride the prompt itself, after any brief: never close the issue, and no
+ issue comment or PR unless the user asks in that session — end with a proposed comment. Proven
+ under a real `/bin/sh` (`github-issue-ref.realsh.test.ts`). (2) **The reference comes from the card's
+ `htmlUrl`** (`issueRefFromHtmlUrl`, which also requires the URL's number to equal the card's).
+ (3) **`done` never moves a card**: it means a turn ended, not that the work did. The issue card
+ shows every bound session as a live chip (`IssueRunChips`, subscribed per node to a PRIMITIVE
+ signature `issueRunChipSig` — never `s.byId`), RUNNING / NEEDS YOU / TURN FAILED / DROPPED plus
+ unread; a click opens that session's card. A card moves only when the session `assign`s itself or
+ a person drags it — pinned by `board-writers.guard.test.ts`, which enumerates EVERY renderer call
+ site that writes a board assignment or moves an issue, each with the human/agent action that
+ triggers it; a new writer fails until it is signed for, and "a turn ended" is not a trigger. (4) **Board-log identity of an issue card** is the synthetic id
+ `github-issue:<owner>/<repo>#<N>` (lower-cased, `issueLogId`) — a namespace no node id can reach.
+ Under it: `run-started` (UI start, `--issue` open) and `run-ended` (written by EVERY node-removal
+ funnel — `deleteNodes`, `closeStoredNodes`, the Omni delete, `deleteProject`, the Server `close` —
+ before it drops the node's agent status, with the last observed state). `duplicateNode` drops
+ `issueRef` (a copy is a new session nobody started on the issue; carrying the binding made a
+ phantom run). Known gap: ⌘Z/⌘⇧Z replay node arrays and write no run history, so an undone delete
+ revives a node whose run already ended. The summary modal shows it read-only as
+ "Agent runs" (no composer: a comment box under an issue reads as "post to GitHub"). **No cost or
+ token figure** is recorded: there is no cumulative per-session number, and a context-window
+ reading is not one. (5) The new session card is filed under the issue card's column (the same
+ unpruned direct write `createNodeInColumn` uses); the node header, the session card AND the card
+ modal's header show a `#N` chip (`IssueRefChip`; the modal's closes itself and makes the same
+ request) that opens the issue on the board (`openIssueOnBoard` →
+ `viewMode.requestedIssue`) ONLY when that board has GitHub sync — otherwise straight to GitHub,
+ rather than flipping the project's persisted view to a board that cannot show it — and the board
+ itself falls back to GitHub when the issue is not on a fetched page. Never a dead click. No "start in a new worktree" UI yet: compose `open-worktree` + `open-agent --group --issue`
+ (the skill says how). Surfaces: Desktop + Server Edition (renderer + core); Omni board shows no
+ issue lanes; **Mobile does not render the binding** — `issueRef` reaches the phone inside the
+ project file, and nodeterm-ios ignores the unknown field (follow-up there).
**Where a card comes from is a registry, not a branch per call site** (`renderer/lib/kanbanSources.ts`,
2026-08-30 — the same membership-plus-one-leaf discipline `AGENT_CONFIG` uses): each entry declares
its filter `label`, its `placement` (`assignment` = the board's own persisted assignments,
diff --cc src/core/github/pull-memory.test.ts
index 2a4805a61,000000000..788138bb6
mode 100644,000000..100644
--- a/src/core/github/pull-memory.test.ts
+++ b/src/core/github/pull-memory.test.ts
@@@ -1,81 -1,0 +1,88 @@@
+import { describe, expect, it } from 'vitest'
+import type { GitHubPullStatus, PullLifecycle } from '../../shared/github-pull-status'
+import {
+ PULL_MEMORY_MAX,
+ REMEMBERED_MERGE_VISIBLE_MS,
+ claimInMemory,
+ emptyPullMemory,
+ rememberPulls,
+ rememberedForBoard,
+ validPullMemory
+} from './pull-memory'
+
+const status = (number: number, lifecycle: PullLifecycle, over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
+ ({ number, lifecycle, headRefName: `feat/${number}`, closes: [], ...over })
+const none = new Map<number, PullLifecycle>()
+
+describe('rememberPulls', () => {
+ it('a merge counts as observed only after the PR was seen open', () => {
+ const seenOpen = rememberPulls([], [status(1, 'open')], none, 10)
+ expect(seenOpen).toEqual([{ number: 1, headRefName: 'feat/1', lifecycle: 'open', openSeen: true }])
+ const merged = rememberPulls(seenOpen, [status(1, 'merged')], none, 20)
+ expect(merged[0]).toMatchObject({ lifecycle: 'merged', openSeen: true, mergedSeenAt: 20 })
+ // The time is the FIRST observation; seeing it merged again does not move it.
+ expect(rememberPulls(merged, [status(1, 'merged')], none, 30)[0].mergedSeenAt).toBe(20)
+ })
+
+ it('a PR first seen already merged is remembered without an observed merge', () => {
+ expect(rememberPulls([], [status(1, 'merged')], none, 10)[0]).toEqual(
+ { number: 1, headRefName: 'feat/1', lifecycle: 'merged' })
+ })
+
++ it('remembers what a PR closed while open, through its merge', () => {
++ const open = rememberPulls([], [status(1, 'open', { closes: [4] })], none, 10)
++ const merged = rememberPulls(open, [status(1, 'merged')], none, 20)
++ expect(merged[0]).toMatchObject({ lifecycle: 'merged', closes: [4] })
++ expect(rememberedForBoard(merged, new Set(), 30)[0].closes).toEqual([4])
++ })
++
+ it('keeps a PR the read no longer lists — a closed one stays closed', () => {
+ const closed = rememberPulls([], [status(1, 'closed')], none, 10)
+ expect(rememberPulls(closed, [], none, 20)).toEqual(closed)
+ })
+
+ it('refreshes an unlisted PR from the REST harvest, observing its merge', () => {
+ const open = rememberPulls([], [status(1, 'open')], none, 10)
+ const merged = rememberPulls(open, [], new Map([[1, 'merged']]), 50)
+ expect(merged[0]).toMatchObject({ lifecycle: 'merged', mergedSeenAt: 50, headRefName: 'feat/1' })
+ })
+
+ it('is bounded, and keeps unfinished PRs over old finished ones', () => {
+ const many = Array.from({ length: PULL_MEMORY_MAX + 20 }, (_, index) => status(index + 1, 'merged'))
+ const kept = rememberPulls([], [...many, status(1, 'open')], none, 1)
+ expect(kept).toHaveLength(PULL_MEMORY_MAX)
+ expect(kept.some((pull) => pull.number === 1 && pull.lifecycle === 'open')).toBe(true)
+ expect(validPullMemory({ version: 1, pulls: kept, claims: [] })).toBe(true)
+ })
+})
+
+describe('rememberedForBoard', () => {
+ it('shows unlisted open and closed PRs, and merges observed within the window', () => {
+ const memory = [
+ { number: 1, headRefName: 'a', lifecycle: 'closed' as const },
+ { number: 2, headRefName: 'b', lifecycle: 'open' as const, openSeen: true as const },
+ { number: 3, headRefName: 'c', lifecycle: 'merged' as const, openSeen: true as const, mergedSeenAt: 100 },
+ { number: 4, headRefName: 'd', lifecycle: 'merged' as const },
+ { number: 5, headRefName: 'e', lifecycle: 'open' as const }
+ ]
+ expect(rememberedForBoard(memory, new Set([5]), 200).map((pull) => pull.number)).toEqual([1, 2, 3])
+ expect(rememberedForBoard(memory, new Set(), 100 + REMEMBERED_MERGE_VISIBLE_MS).map((pull) => pull.number))
+ .toEqual([1, 2, 5])
+ })
+})
+
+describe('claims', () => {
+ it('the first claim for a key wins', () => {
+ const first = claimInMemory(emptyPullMemory(), 'p|n|1')
+ expect(first.claimed).toBe(true)
+ expect(claimInMemory(first.memory, 'p|n|1').claimed).toBe(false)
+ expect(claimInMemory(first.memory, 'p|n|1,2').claimed).toBe(true)
+ })
+
+ it('rejects a malformed memory file', () => {
+ expect(validPullMemory({ version: 1, pulls: [{ number: -1, headRefName: 'x', lifecycle: 'open' }], claims: [] }))
+ .toBe(false)
+ expect(validPullMemory({ version: 2, pulls: [], claims: [] })).toBe(false)
+ expect(validPullMemory({ version: 1, pulls: [], claims: [3] })).toBe(false)
+ })
+})
diff --cc src/core/github/pull-memory.ts
index dd070786c,000000000..52b38d3ae
mode 100644,000000..100644
--- a/src/core/github/pull-memory.ts
+++ b/src/core/github/pull-memory.ts
@@@ -1,148 -1,0 +1,161 @@@
+// What this machine has OBSERVED about a repository's pull requests, kept across reads and restarts
+// (persisted per identity + repository beside the issue cache, see cache.ts). The GraphQL read only
+// lists the 50 most recently updated open PRs and the 30 most recently finished ones, so without a
+// memory two facts the merge-driven column move depends on would silently expire:
+//
+// - "PR #12 closed without merging" — the card linked to it must stay blocked until the user
+// unlinks it, not until 30 other PRs close and #12 drops out of the `recent` list;
+// - "this machine saw PR #15 open, and later saw it merged" — the only thing that counts as an
+// observed transition. A merge first seen already-merged never moves a card.
+//
+// A remembered PR that neither list covers any more gets its lifecycle from the REST issues harvest
+// (which carries every PR's state), so an old merge is still noticed; one the harvest does not have
+// keeps its last known lifecycle, which for an open PR means "wait" — the safe answer.
+//
+// It also holds CLAIMS: one per (project, card, set of PRs) that has been moved. Every board in every
+// window asks the host before it moves a card, and only the first ask wins — so two Server Edition
+// tabs cannot both move the card, and a card the user dragged back is not moved again for the same
+// merges.
+import type { GitHubPullStatus, PullLifecycle } from '../../shared/github-pull-status'
+
+export interface RememberedPull {
+ number: number
+ headRefName: string
+ crossRepository?: true
+ lifecycle: PullLifecycle
+ openSeen?: true
+ mergedSeenAt?: number
++ /** The same-repository issues it closes, as last seen while it was open — the read only reports
++ * closing issues for OPEN PRs, and the merge is exactly when an issue-bound card needs them. */
++ closes?: number[]
+}
+
+export interface PullMemory {
+ version: 1
+ pulls: RememberedPull[]
+ claims: string[]
+}
+
+export const PULL_MEMORY_MAX = 500
+export const PULL_CLAIMS_MAX = 2_000
+/** A merged PR stays on the board this long after its merge was observed — long enough for a board
+ * opened days later to see the merge and move the card. Older merges are kept only as memory. */
+export const REMEMBERED_MERGE_VISIBLE_MS = 30 * 24 * 60 * 60_000
+
+export function emptyPullMemory(): PullMemory {
+ return { version: 1, pulls: [], claims: [] }
+}
+
+const LIFECYCLES = new Set<PullLifecycle>(['open', 'draft', 'merged', 'closed'])
+
+function validRemembered(value: unknown): value is RememberedPull {
+ if (!value || typeof value !== 'object') return false
+ const pull = value as RememberedPull
+ return Number.isSafeInteger(pull.number) && pull.number > 0 &&
+ typeof pull.headRefName === 'string' && pull.headRefName.length > 0 && pull.headRefName.length <= 255 &&
+ (pull.crossRepository === undefined || pull.crossRepository === true) &&
+ LIFECYCLES.has(pull.lifecycle) &&
+ (pull.openSeen === undefined || pull.openSeen === true) &&
- (pull.mergedSeenAt === undefined || (Number.isSafeInteger(pull.mergedSeenAt) && pull.mergedSeenAt >= 0))
++ (pull.mergedSeenAt === undefined || (Number.isSafeInteger(pull.mergedSeenAt) && pull.mergedSeenAt >= 0)) &&
++ (pull.closes === undefined || (Array.isArray(pull.closes) && pull.closes.length <= 10 &&
++ pull.closes.every((number) => Number.isSafeInteger(number) && number > 0)))
+}
+
+export function validPullMemory(value: unknown): value is PullMemory {
+ if (!value || typeof value !== 'object') return false
+ const memory = value as PullMemory
+ return memory.version === 1 &&
+ Array.isArray(memory.pulls) && memory.pulls.length <= PULL_MEMORY_MAX && memory.pulls.every(validRemembered) &&
+ Array.isArray(memory.claims) && memory.claims.length <= PULL_CLAIMS_MAX &&
+ memory.claims.every((claim) => typeof claim === 'string' && claim.length <= 1_024)
+}
+
+const UNFINISHED = new Set<PullLifecycle>(['open', 'draft'])
+
+/**
+ * Folds one read into the memory. `listed` is what the GraphQL read returned (open + recent);
+ * remembered PRs it does not list take their lifecycle from `harvest` (the REST snapshot) when it
+ * has them. A merge counts as observed only when this machine had seen the PR open before.
+ */
+export function rememberPulls(
+ previous: RememberedPull[],
+ listed: GitHubPullStatus[],
+ harvest: ReadonlyMap<number, PullLifecycle>,
+ now: number
+): RememberedPull[] {
+ const byNumber = new Map(previous.map((pull) => [pull.number, pull]))
+ const next = new Map<number, RememberedPull>()
- const apply = (number: number, headRefName: string, crossRepository: boolean, lifecycle: PullLifecycle): void => {
++ const apply = (
++ number: number, headRefName: string, crossRepository: boolean, lifecycle: PullLifecycle, closes: number[]
++ ): void => {
+ const before = byNumber.get(number)
+ const openSeen = !!before?.openSeen || UNFINISHED.has(lifecycle)
+ const mergedSeenAt = before?.mergedSeenAt ??
+ (lifecycle === 'merged' && before?.openSeen ? now : undefined)
++ // An open PR's read is the truth about what it closes; a finished one's read says nothing, so
++ // what was seen while it was open stands.
++ const closing = UNFINISHED.has(lifecycle) ? closes.slice(0, 10) : before?.closes ?? closes.slice(0, 10)
+ next.set(number, {
+ number,
+ headRefName,
+ ...(crossRepository ? { crossRepository: true as const } : {}),
+ lifecycle,
+ ...(openSeen ? { openSeen: true as const } : {}),
- ...(mergedSeenAt !== undefined ? { mergedSeenAt } : {})
++ ...(mergedSeenAt !== undefined ? { mergedSeenAt } : {}),
++ ...(closing.length ? { closes: closing } : {})
+ })
+ }
- for (const pull of listed) apply(pull.number, pull.headRefName, !!pull.crossRepository, pull.lifecycle)
++ for (const pull of listed) apply(pull.number, pull.headRefName, !!pull.crossRepository, pull.lifecycle, pull.closes)
+ for (const pull of previous) {
+ if (next.has(pull.number)) continue
+ const lifecycle = harvest.get(pull.number) ?? pull.lifecycle
- apply(pull.number, pull.headRefName, !!pull.crossRepository, lifecycle)
++ apply(pull.number, pull.headRefName, !!pull.crossRepository, lifecycle, pull.closes ?? [])
+ }
+ // Bound: unfinished PRs are kept first (dropping one would turn "wait" into "not linked"), then the
+ // newest. An evicted merged PR only loses its place on a board long after it mattered.
+ return [...next.values()]
+ .sort((a, b) => Number(UNFINISHED.has(b.lifecycle)) - Number(UNFINISHED.has(a.lifecycle)) ||
+ b.number - a.number)
+ .slice(0, PULL_MEMORY_MAX)
+}
+
+/** The remembered PRs the board still needs that the read did not list: every unfinished or
+ * closed-unmerged one (a closed PR keeps blocking its card until unlinked), and merges observed
+ * within `REMEMBERED_MERGE_VISIBLE_MS`. */
+export function rememberedForBoard(
+ memory: RememberedPull[],
+ listed: ReadonlySet<number>,
+ now: number
+): GitHubPullStatus[] {
+ return memory
+ .filter((pull) => !listed.has(pull.number))
+ .filter((pull) => pull.lifecycle !== 'merged' ||
+ (pull.mergedSeenAt !== undefined && now - pull.mergedSeenAt < REMEMBERED_MERGE_VISIBLE_MS))
+ .map((pull): GitHubPullStatus => ({
+ number: pull.number,
+ lifecycle: pull.lifecycle,
+ headRefName: pull.headRefName,
+ ...(pull.crossRepository ? { crossRepository: true as const } : {}),
- closes: [],
++ closes: pull.closes ?? [],
+ ...(pull.openSeen ? { openSeen: true as const } : {}),
+ ...(pull.mergedSeenAt !== undefined ? { mergedSeenAt: pull.mergedSeenAt } : {})
+ }))
+}
+
+/** A listed status with what the memory knows about it. */
+export function withObservations(status: GitHubPullStatus, remembered: RememberedPull | undefined): GitHubPullStatus {
+ if (!remembered) return status
+ return {
+ ...status,
++ // A finished PR's read carries no closing issues; the ones seen while it was open still apply.
++ ...(status.closes.length === 0 && remembered.closes?.length ? { closes: remembered.closes } : {}),
+ ...(remembered.openSeen ? { openSeen: true as const } : {}),
+ ...(remembered.mergedSeenAt !== undefined ? { mergedSeenAt: remembered.mergedSeenAt } : {})
+ }
+}
+
+/** Records a claim; `claimed` is false when it was already there. */
+export function claimInMemory(memory: PullMemory, key: string): { memory: PullMemory; claimed: boolean } {
+ if (memory.claims.includes(key)) return { memory, claimed: false }
+ return { memory: { ...memory, claims: [...memory.claims, key].slice(-PULL_CLAIMS_MAX) }, claimed: true }
+}
diff --cc src/core/github/pull-status-tracker.test.ts
index b17029070,000000000..7496f00b6
mode 100644,000000..100644
--- a/src/core/github/pull-status-tracker.test.ts
+++ b/src/core/github/pull-status-tracker.test.ts
@@@ -1,272 -1,0 +1,273 @@@
+import { describe, expect, it } from 'vitest'
+import { GitHubPullStatusTracker } from './pull-status-tracker'
+import { GitHubRequestCoordinator } from './request-coordinator'
+import type { PullStatusRead } from './graphql-pulls'
+import { PULL_CHASE_MAX } from '../../shared/github-pull-status'
+import type { PullStatusFacts } from '../../shared/github-pull-status'
+import { emptyPullMemory, type PullMemory } from './pull-memory'
+
+const HEAD = 'a'.repeat(40)
+const KEY = 'user-1\0o/r'
+
+function facts(number: number, over: Partial<PullStatusFacts> = {}): PullStatusFacts {
+ return {
+ number, headRefName: `feat/${number}`, headRefOid: HEAD, crossRepository: false, isDraft: false, mergeable: 'MERGEABLE',
+ mergeStateStatus: 'CLEAN', rollup: 'SUCCESS', rollupOid: HEAD, closes: [], ...over
+ }
+}
+
+function read(open: PullStatusFacts[], over: Partial<PullStatusRead> = {}): PullStatusRead {
+ return { open, recent: [], access: { ci: true, merge: true }, truncated: false, ...over }
+}
+
+/** An on-disk memory stand-in shared across tracker instances (an app restart = a new tracker). */
+function memoryStore() {
+ const files = new Map<string, PullMemory>()
+ const saves: PullMemory[] = []
+ return {
+ files,
+ saves,
+ load: async (userId: string, repository: string) =>
+ structuredClone(files.get(`${userId}\0${repository}`) ?? emptyPullMemory()),
+ save: async (userId: string, repository: string, memory: PullMemory) => {
+ saves.push(structuredClone(memory))
+ files.set(`${userId}\0${repository}`, structuredClone(memory))
+ }
+ }
+}
+
+function tracker(start = 0, store = memoryStore()) {
+ let now = start
+ const changes: number[][] = []
+ const coordinator = new GitHubRequestCoordinator({ now: () => now })
+ const subject = new GitHubPullStatusTracker({
+ coordinator, now: () => now, onChanged: (_key, numbers) => changes.push(numbers), memory: store
+ })
+ return { subject, coordinator, changes, store, advance: (ms: number) => { now += ms }, at: () => now }
+}
+
+async function settleSaves(): Promise<void> {
+ for (let index = 0; index < 10; index++) await Promise.resolve()
+}
+
+describe('GitHubPullStatusTracker', () => {
+ it('publishes open pull requests and recent merges', async () => {
+ const { subject } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)], {
+ recent: [{ number: 2, headRefName: 'feat/2', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ const board = subject.board(KEY)
+ expect(board.pulls.map((pull) => [pull.number, pull.lifecycle, pull.ci, pull.merge])).toEqual([
+ [1, 'open', 'passed', 'ready'], [2, 'merged', undefined, undefined]
+ ])
+ expect(board.stale).toBe(false)
+ expect(board.observedAt).toBe(0)
++ expect(board.repository).toBe('o/r')
+ })
+
+ it('a failed read keeps the last snapshot and marks it stale instead of going blank', async () => {
+ const { subject, changes } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))
+ changes.length = 0
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => {
+ throw Object.assign(new Error('request-failed'), { code: 'request-failed', status: 502 })
+ })
+ const board = subject.board(KEY)
+ expect(board.stale).toBe(true)
+ expect(board.pulls.map((pull) => pull.ci)).toEqual(['passed'])
+ expect(changes).toEqual([[]])
+ // A stale snapshot is worth re-reading at the next heartbeat even when nothing changed.
+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(true)
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))
+ expect(subject.board(KEY).stale).toBe(false)
+ })
+
+ it('reads after a heartbeat only when something changed, once it knows the repository', async () => {
+ const { subject } = tracker()
+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(true)
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))
+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(false)
+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: true, foreground: false })).toBe(true)
+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: true })).toBe(true)
+ })
+
+ it('chases an undecided PR on the schedule and stops after 12 reads', async () => {
+ const { subject, advance } = tracker()
+ const undecided = async () => read([facts(1, { mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' })])
+ await subject.read(KEY, 'user-1', 'heartbeat', undecided)
+ expect(subject.board(KEY).undecided).toBe(true)
+ let reads = 0
+ for (let tick = 0; tick < 400; tick++) {
+ advance(15_000)
+ if (!subject.claimChase(KEY)) continue
+ reads += 1
+ await subject.read(KEY, 'user-1', 'chase', undecided)
+ }
+ expect(reads).toBe(PULL_CHASE_MAX)
+ expect(subject.board(KEY).undecided).toBe(false)
+ })
+
+ it('does not chase before the first delay, and a failed chase read still spends its attempt', async () => {
+ const { subject, advance } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () =>
+ read([facts(1, { rollup: 'PENDING' })]))
+ advance(29_999)
+ expect(subject.claimChase(KEY)).toBe(false)
+ advance(1)
+ expect(subject.claimChase(KEY)).toBe(true)
+ await subject.read(KEY, 'user-1', 'chase', async () => { throw Object.assign(new Error('x'), { code: 'request-failed' }) })
+ // The next step is one minute after the failed read, not an immediate retry.
+ advance(59_999)
+ expect(subject.claimChase(KEY)).toBe(false)
+ advance(1)
+ expect(subject.claimChase(KEY)).toBe(true)
+ })
+
+ it('stops chasing once the PR settles', async () => {
+ const { subject, advance } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1, { rollup: 'PENDING' })]))
+ advance(30_000)
+ expect(subject.claimChase(KEY)).toBe(true)
+ await subject.read(KEY, 'user-1', 'chase', async () => read([facts(1)]))
+ advance(3_600_000)
+ expect(subject.claimChase(KEY)).toBe(false)
+ })
+
+ it('a background read the graphql budget holds is skipped and owed; REST budget does not hold it', async () => {
+ const { subject, coordinator } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)]))
+ coordinator.noteRateSample('user-1', { resource: 'core', limit: 5_000, remaining: 10, resetAt: 60_000 })
+ let ran = 0
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => { ran += 1; return read([facts(1)]) })
+ expect(ran).toBe(1)
+ coordinator.noteRateSample('user-1', { resource: 'graphql', limit: 5_000, remaining: 10, resetAt: 60_000 })
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => { ran += 1; return read([facts(1)]) })
+ expect(ran).toBe(1)
+ expect(subject.wantsReadAfterHeartbeat(KEY, { changed: false, foreground: false })).toBe(true)
+ // The user's own refresh is not held by the floor — only by a hard limit.
+ await subject.read(KEY, 'user-1', 'foreground', async () => { ran += 1; return read([facts(1)]) })
+ expect(ran).toBe(2)
+ coordinator.noteRateSample('user-1', { resource: 'graphql', limit: 5_000, remaining: 0, resetAt: 60_000 })
+ await subject.read(KEY, 'user-1', 'foreground', async () => { ran += 1; return read([facts(1)]) })
+ expect(ran).toBe(2)
+ })
+
+ it('a token without permission hides CI and mergeability instead of marking anything stale', async () => {
+ const { subject } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => {
+ throw Object.assign(new Error('insufficient-permission'), { code: 'insufficient-permission', status: 403 })
+ })
+ expect(subject.board(KEY)).toMatchObject({ pulls: [], stale: false, access: { ci: false, merge: false } })
+ })
+
+ it('a read in flight when the cache is cleared publishes nothing', async () => {
+ const { subject } = tracker()
+ let release!: (value: PullStatusRead) => void
+ const pending = subject.read(KEY, 'user-1', 'heartbeat', () => new Promise((resolve) => { release = resolve }))
+ subject.forgetRepository('o/r')
+ release(read([facts(1)]))
+ await pending
+ expect(subject.board(KEY).pulls).toEqual([])
+ })
+
+ it('never carries a CI result from an older head across reads', async () => {
+ const { subject } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1, { rollup: 'SUCCESS' })]))
+ const pushed = 'c'.repeat(40)
+ await subject.read(KEY, 'user-1', 'heartbeat', async () =>
+ read([facts(1, { headRefOid: pushed, rollup: 'SUCCESS', rollupOid: HEAD })]))
+ expect(subject.board(KEY).pulls[0]).toMatchObject({ headRefOid: pushed, ci: 'pending' })
+ })
+
+ describe('memory', () => {
+ it('a PR closed without merging stays on the board after it leaves the recent list', async () => {
+ const { subject } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([], {
+ recent: [{ number: 12, headRefName: 'feat/x', crossRepository: false, lifecycle: 'closed' }]
+ }))
+ // Thirty newer PRs closed: #12 is no longer in the read at all.
+ await subject.read(KEY, 'user-1', 'foreground', async () => read([]))
+ expect(subject.board(KEY).pulls).toEqual([
+ { number: 12, lifecycle: 'closed', headRefName: 'feat/x', closes: [] }
+ ])
+ })
+
+ it('marks a merge as observed only when it had seen the PR open, and remembers it across a restart', async () => {
+ const store = memoryStore()
+ const first = tracker(100, store)
+ await first.subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1, { headRefName: 'feat/x' })]))
+ await settleSaves()
+ // An app restart: a new tracker over the same stored memory, and #1 has merged meanwhile.
+ const second = tracker(500, store)
+ await second.subject.read(KEY, 'user-1', 'heartbeat', async () => read([], {
+ recent: [{ number: 1, headRefName: 'feat/x', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ expect(second.subject.board(KEY).pulls[0]).toMatchObject({ number: 1, lifecycle: 'merged', openSeen: true, mergedSeenAt: 500 })
+ // A merge this machine never saw open carries no observation.
+ await second.subject.read(KEY, 'user-1', 'foreground', async () => read([], {
+ recent: [{ number: 2, headRefName: 'feat/y', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ expect(second.subject.board(KEY).pulls.find((pull) => pull.number === 2)).not.toHaveProperty('mergedSeenAt')
+ })
+
+ it('a claim is won once, across concurrent asks and across a restart', async () => {
+ const store = memoryStore()
+ const { subject } = tracker(0, store)
+ const answers = await Promise.all([subject.claim(KEY, 'p\u0000n\u00001'), subject.claim(KEY, 'p\u0000n\u00001')])
+ expect(answers.sort()).toEqual([false, true])
+ await settleSaves()
+ const restarted = tracker(0, store)
+ expect(await restarted.subject.claim(KEY, 'p\u0000n\u00001')).toBe(false)
+ expect(await restarted.subject.claim(KEY, 'p\u0000n\u00002')).toBe(true)
+ })
+
+ it('a save queued behind a slow one is dropped once the repository is forgotten', async () => {
+ const store = memoryStore()
+ let releaseFirst!: () => void
+ const firstSave = new Promise<void>((resolve) => { releaseFirst = resolve })
+ const save = store.save
+ let calls = 0
+ store.save = async (...args) => {
+ calls += 1
+ if (calls === 1) await firstSave
+ return save(...args)
+ }
+ const { subject } = tracker(0, store)
+ expect(await subject.claim(KEY, 'one')).toBe(true)
+ expect(await subject.claim(KEY, 'two')).toBe(true)
+ const forgotten = subject.forgetRepository('o/r')
+ releaseFirst()
+ await forgotten
+ expect(calls).toBe(1)
+ expect(store.saves).toHaveLength(1)
+ })
+
+ it('nothing started before a cache clear writes the memory back', async () => {
+ const store = memoryStore()
+ const { subject } = tracker(0, store)
+ let release!: (value: PullStatusRead) => void
+ const pending = subject.read(KEY, 'user-1', 'heartbeat', () => new Promise((resolve) => { release = resolve }))
+ await subject.forgetRepository('o/r')
+ release(read([facts(1)]))
+ await pending
+ await settleSaves()
+ expect(store.saves).toEqual([])
+ })
+ })
+
+ it('the chase read that spends the last attempt tells the boards at once', async () => {
+ const { subject, advance, changes } = tracker()
+ const undecided = async () => read([facts(1, { mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' })])
+ await subject.read(KEY, 'user-1', 'heartbeat', undecided)
+ for (let attempt = 0; attempt < PULL_CHASE_MAX - 1; attempt++) {
+ advance(300_000)
+ expect(subject.claimChase(KEY)).toBe(true)
+ await subject.read(KEY, 'user-1', 'chase', undecided)
+ }
+ changes.length = 0
+ advance(300_000)
+ expect(subject.claimChase(KEY)).toBe(true)
+ expect(changes).toEqual([[]])
+ expect(subject.board(KEY).undecided).toBe(false)
+ })
+})
diff --cc src/core/github/pull-status-tracker.ts
index 676fba8d3,000000000..142b3fd23
mode 100644,000000..100644
--- a/src/core/github/pull-status-tracker.ts
+++ b/src/core/github/pull-status-tracker.ts
@@@ -1,325 -1,0 +1,327 @@@
+// Pull request CI + mergeability per repository: when to read it, what the board is told, and how
+// an undecided PR is chased without webhooks. The GraphQL read itself is the client's; this module
+// owns only the decisions, so each rule can be pressed by a test without a network.
+//
+// WHEN a read happens — nothing else triggers one:
+// 1. The issues heartbeat reported a change. A push, a merge, a label, a comment all move the
+// repository's most recently updated item; a finished check run does NOT, which is why:
+// 2. An undecided PR (mergeability UNKNOWN, or a rollup still PENDING) is CHASED — 30 s, 1 min,
+// 2 min, then 5 min, at most 12 reads per episode — and only while a board is VISIBLE. The
+// renderer asserts visibility by asking (`claimChase`); a hidden or closed board stops asking.
+// 3. The first heartbeat of an app run (nothing known yet), a user's own refresh, a snapshot that
+// is stale, or a read the rate budget skipped earlier (`owed`).
+//
+// A read the budget holds is skipped, never queued, and remembered as owed; a failed read keeps the
+// last snapshot and marks it stale. Neither blanks what the board shows.
+//
+// Every read is also folded into the repository's persisted MEMORY (pull-memory.ts): what this
+// machine has observed about each PR, and the one-time claims the merge-driven column move takes.
+import {
+ EMPTY_PULL_BOARD,
+ PULL_CHASE_MAX,
+ nextPullChase,
+ pullChaseDue,
+ pullStatusFrom,
+ type GitHubPullBoard,
+ type GitHubPullStatus,
+ type PullChaseState,
+ type PullLifecycle
+} from '../../shared/github-pull-status'
+import type { PullStatusRead } from './graphql-pulls'
+import {
+ claimInMemory,
+ emptyPullMemory,
+ rememberPulls,
+ rememberedForBoard,
+ withObservations,
+ type PullMemory
+} from './pull-memory'
+import type { GitHubRequestCoordinator } from './request-coordinator'
+
+export type PullReadReason = 'heartbeat' | 'foreground' | 'chase'
+
+type PullRepositoryState = {
+ pulls: GitHubPullStatus[]
+ observedAt?: number
+ stale: boolean
+ access: { ci: boolean; merge: boolean }
+ truncated: boolean
+ chase: PullChaseState | null
+ /** A read was skipped by the rate budget; the next opportunity reads even if nothing changed. */
+ owed: boolean
+ inFlight?: Promise<void>
+ /** Bumped by `forgetRepository` so nothing started before a cache clear can publish or persist. */
+ generation: number
+ memory?: PullMemory
+ memoryLoad?: Promise<PullMemory>
+ /** Saves run one after another, so the file always ends at the latest memory. */
+ saving: Promise<void>
+}
+
+type TrackerOptions = {
+ coordinator: GitHubRequestCoordinator
+ now?: () => number
+ /** Something the board shows changed for this repository key. */
+ onChanged: (key: string, changedPullNumbers: number[]) => void
+ /** Persistence for the memory; absent = memory lives for this process only. */
+ memory?: {
+ load(userId: string, repository: string): Promise<PullMemory>
+ save(userId: string, repository: string, memory: PullMemory): Promise<void>
+ }
+ /** Every PR's lifecycle from the REST issues harvest, for remembered PRs the GraphQL read no
+ * longer lists. */
+ harvest?: (key: string) => ReadonlyMap<number, PullLifecycle>
+}
+
+function errorCode(error: unknown): string | undefined {
+ return error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'
+ ? (error as { code: string }).code
+ : undefined
+}
+
+/** Repository keys are `${userId}\0${repository}` — the issue service's own key. */
+function splitKey(key: string): [string, string] {
+ const at = key.indexOf('\0')
+ return [key.slice(0, at), key.slice(at + 1)]
+}
+
+export class GitHubPullStatusTracker {
+ private readonly states = new Map<string, PullRepositoryState>()
+ private readonly now: () => number
+
+ constructor(private readonly options: TrackerOptions) {
+ this.now = options.now ?? Date.now
+ }
+
+ board(key: string): GitHubPullBoard {
+ const state = this.states.get(key)
- if (!state) return { ...EMPTY_PULL_BOARD, access: { ...EMPTY_PULL_BOARD.access } }
++ const repository = splitKey(key)[1]
++ if (!state) return { ...EMPTY_PULL_BOARD, access: { ...EMPTY_PULL_BOARD.access }, repository }
+ return {
++ repository,
+ pulls: state.pulls.map((pull) => ({ ...pull, closes: [...pull.closes] })),
+ ...(state.observedAt !== undefined ? { observedAt: state.observedAt } : {}),
+ stale: state.stale,
+ access: { ...state.access },
+ undecided: !!state.chase && state.chase.attempts < PULL_CHASE_MAX,
+ truncated: state.truncated
+ }
+ }
+
+ /** Should the heartbeat that just ran be followed by a pull status read? */
+ wantsReadAfterHeartbeat(key: string, input: { changed: boolean; foreground: boolean }): boolean {
+ const state = this.states.get(key)
+ return input.changed || input.foreground || !state || state.observedAt === undefined ||
+ state.stale || state.owed
+ }
+
+ /**
+ * Claims one chase read, synchronously, so two boards asking at once cannot both spend it. True
+ * means the caller must now `read(…, 'chase')`. The attempt is counted HERE, before the read: a
+ * chase read that fails still spends one of the twelve. The claim that spends the last one tells
+ * the boards at once, so they stop asking.
+ */
+ claimChase(key: string): boolean {
+ const state = this.states.get(key)
+ if (!state || state.inFlight || !pullChaseDue(state.chase, this.now())) return false
+ state.chase = { ...state.chase!, attempts: state.chase!.attempts + 1, lastReadAt: this.now() }
+ if (state.chase.attempts >= PULL_CHASE_MAX) this.options.onChanged(key, [])
+ return true
+ }
+
+ /**
+ * The one-time permission to move a card for a set of merged PRs. The first caller for a key wins,
+ * whichever window it comes from, and the claim is persisted — a card the user dragged back is not
+ * moved again for the same merges.
+ */
+ async claim(key: string, claimKey: string): Promise<boolean> {
+ const state = this.stateFor(key)
+ const generation = state.generation
+ const memory = await this.memoryFor(key, state)
+ if (generation !== state.generation) return false
+ const { memory: next, claimed } = claimInMemory(state.memory ?? memory, claimKey)
+ if (!claimed) return false
+ state.memory = next
+ this.persist(key, state)
+ return true
+ }
+
+ /**
+ * Drops every repository state for `repository` (a cache clear or revoke). Resolves once any save
+ * already under way has finished, so a caller deleting the file afterwards cannot have it written
+ * back by a save that started before.
+ */
+ forgetRepository(repository: string): Promise<void> {
+ const pending: Promise<void>[] = []
+ for (const [key, state] of this.states) {
+ if (!key.endsWith(`\0${repository}`)) continue
+ state.generation += 1
+ pending.push(state.saving)
+ this.states.delete(key)
+ }
+ return Promise.all(pending).then(() => undefined)
+ }
+
+ /**
+ * Reads now. `run` performs the GraphQL read (through the coordinator and the caller's epoch
+ * checks); `userId` names the identity whose `graphql` budget it spends. Single-flight per key:
+ * a read already in flight answers every caller that arrives meanwhile.
+ */
+ read(
+ key: string,
+ userId: string,
+ reason: PullReadReason,
+ run: () => Promise<PullStatusRead>
+ ): Promise<void> {
+ const state = this.stateFor(key)
+ if (state.inFlight) return state.inFlight
+ // Background reads (heartbeat, chase) respect the whole budget, including the floor kept for
+ // the user's own tools. A read the user asked for respects only a hard limit.
+ const throttle = this.options.coordinator.throttle(userId, this.now(), 'graphql')
+ if (throttle && (reason !== 'foreground' || throttle.kind === 'rate-limited')) {
+ state.owed = true
+ return Promise.resolve()
+ }
+ const generation = state.generation
+ const work = this.perform(key, state, generation, userId, run)
+ state.inFlight = work
+ void work.finally(() => { if (state.inFlight === work) delete state.inFlight })
+ return work
+ }
+
+ private async perform(
+ key: string,
+ state: PullRepositoryState,
+ generation: number,
+ userId: string,
+ run: () => Promise<PullStatusRead>
+ ): Promise<void> {
+ let result: PullStatusRead
+ try {
+ result = await run()
+ } catch (error) {
+ if (generation !== state.generation) return
+ const code = errorCode(error)
+ if (code === 'configuration-changed') return
+ if (code === 'rate-limited') {
+ // The coordinator has recorded the hold; nothing was learned about the pull requests.
+ state.owed = true
+ return
+ }
+ if (code === 'insufficient-permission') {
+ await this.publish(key, state, generation, {
+ open: [], recent: [], access: { ci: false, merge: false }, truncated: false
+ }, userId)
+ return
+ }
+ const wasStale = state.stale
+ state.stale = true
+ // A failed chase read still waits its turn: the next one follows the schedule, not a retry loop.
+ if (state.chase) state.chase = { ...state.chase, lastReadAt: this.now() }
+ if (!wasStale) this.options.onChanged(key, [])
+ return
+ }
+ if (generation !== state.generation) return
+ await this.publish(key, state, generation, result, userId)
+ }
+
+ private async publish(
+ key: string,
+ state: PullRepositoryState,
+ generation: number,
+ result: PullStatusRead,
+ userId: string
+ ): Promise<void> {
+ const memory = await this.memoryFor(key, state)
+ if (generation !== state.generation) return
+ const now = this.now()
+ if (result.rateLimit) {
+ // The body's own reading, in case a proxy stripped the headers the client already fed in.
+ this.options.coordinator.noteRateSample(userId, {
+ resource: 'graphql',
+ limit: result.rateLimit.limit,
+ remaining: result.rateLimit.remaining,
+ resetAt: result.rateLimit.resetAt
+ })
+ }
+ const previous = new Map(state.pulls.map((pull) => [pull.number, pull]))
+ const open = result.open.map((facts) => pullStatusFrom(facts, result.access, previous.get(facts.number)))
+ const openNumbers = new Set(open.map((pull) => pull.number))
+ const finished = result.recent
+ .filter((pull) => !openNumbers.has(pull.number))
+ .map((pull): GitHubPullStatus => ({
+ number: pull.number,
+ lifecycle: pull.lifecycle,
+ headRefName: pull.headRefName,
+ ...(pull.crossRepository ? { crossRepository: true as const } : {}),
+ closes: []
+ }))
+ const listed = [...open, ...finished]
+ const remembered = rememberPulls(memory.pulls, listed, this.options.harvest?.(key) ?? new Map(), now)
+ if (JSON.stringify(remembered) !== JSON.stringify(memory.pulls)) {
+ state.memory = { ...(state.memory ?? memory), pulls: remembered }
+ this.persist(key, state)
+ }
+ const rememberedByNumber = new Map(remembered.map((pull) => [pull.number, pull]))
+ const pulls = [
+ ...listed.map((pull) => withObservations(pull, rememberedByNumber.get(pull.number))),
+ ...rememberedForBoard(remembered, new Set(listed.map((pull) => pull.number)), now)
+ ]
+ const nextNumbers = new Set(pulls.map((pull) => pull.number))
+ const changed = [
+ ...pulls.filter((pull) => JSON.stringify(pull) !== JSON.stringify(previous.get(pull.number)))
+ .map((pull) => pull.number),
+ ...state.pulls.filter((pull) => !nextNumbers.has(pull.number)).map((pull) => pull.number)
+ ]
+ const accessChanged = state.access.ci !== result.access.ci || state.access.merge !== result.access.merge
+ const wasStale = state.stale
+ const chaseBefore = state.chase
+ state.pulls = pulls
+ state.observedAt = now
+ state.stale = false
+ state.owed = false
+ state.access = { ...result.access }
+ state.truncated = result.truncated
+ state.chase = nextPullChase(state.chase, open, now)
+ const chaseChanged = !!chaseBefore !== !!state.chase
+ if (changed.length || accessChanged || wasStale || chaseChanged) this.options.onChanged(key, changed)
+ }
+
+ private memoryFor(key: string, state: PullRepositoryState): Promise<PullMemory> {
+ if (state.memory) return Promise.resolve(state.memory)
+ if (!state.memoryLoad) {
+ const [userId, repository] = splitKey(key)
+ state.memoryLoad = (this.options.memory
+ ? this.options.memory.load(userId, repository)
+ : Promise.resolve(emptyPullMemory())).catch(() => emptyPullMemory())
+ }
+ return state.memoryLoad.then((loaded) => {
+ if (!state.memory) state.memory = loaded
+ return state.memory
+ })
+ }
+
+ private persist(key: string, state: PullRepositoryState): void {
+ const save = this.options.memory?.save
+ if (!save) return
+ const [userId, repository] = splitKey(key)
+ const generation = state.generation
+ state.saving = state.saving.then(async () => {
+ // Written at its turn with the LATEST memory, and never after the repository was forgotten.
+ if (generation !== state.generation || !state.memory) return
+ await save(userId, repository, state.memory)
+ }).catch(() => undefined)
+ }
+
+ private stateFor(key: string): PullRepositoryState {
+ let state = this.states.get(key)
+ if (!state) {
+ state = {
+ pulls: [], stale: false, access: { ci: true, merge: true }, truncated: false,
+ chase: null, owed: false, generation: 0, saving: Promise.resolve()
+ }
+ this.states.set(key, state)
+ }
+ return state
+ }
+}
diff --cc src/core/github/service.pulls.test.ts
index a146e2afe,000000000..f3b89fa9f
mode 100644,000000..100644
--- a/src/core/github/service.pulls.test.ts
+++ b/src/core/github/service.pulls.test.ts
@@@ -1,238 -1,0 +1,239 @@@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { GitHubIssueCache } from './cache'
+import { GitHubIssueService, type GitHubIssueServiceContext, type GitHubIssuesClientLike } from './service'
+import { GitHubRequestCoordinator } from './request-coordinator'
+import type { PullStatusRead } from './graphql-pulls'
+import type { GitHubIssue, IssueHeartbeatResult, NormalisedProjectKanbanGitHub } from '../../shared/github-issues'
+import type { GitHubPullChecksResult, PullStatusFacts } from '../../shared/github-pull-status'
+
+let userDataDir: string
+beforeEach(async () => { userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-pulls-')) })
- afterEach(async () => { await fs.rm(userDataDir, { recursive: true, force: true }) })
++// A claim persists the pull memory asynchronously, so a save can still be landing as a test ends.
++afterEach(async () => { await fs.rm(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 }) })
+
+const HEAD = 'a'.repeat(40)
+const config: NormalisedProjectKanbanGitHub = {
+ repository: 'o/r', columnMappings: [{ columnId: 'done', label: 'done' }], completionColumnId: 'done',
+ revision: 'mapping-1'
+}
+
+function facts(number: number, over: Partial<PullStatusFacts> = {}): PullStatusFacts {
+ return {
+ number, headRefName: `feat/${number}`, headRefOid: HEAD, crossRepository: false, isDraft: false, mergeable: 'MERGEABLE',
+ mergeStateStatus: 'CLEAN', rollup: 'SUCCESS', rollupOid: HEAD, closes: [], ...over
+ }
+}
+
+class PullClient implements GitHubIssuesClientLike {
+ /** The heartbeat's answer: flip `changed` to simulate activity in the repository. */
+ changed = false
+ heartbeats = 0
+ statusReads = 0
+ checkReads = 0
+ open: PullStatusFacts[] = [facts(1)]
+ checks: GitHubPullChecksResult = { status: 'no-checks' }
+ failChecks?: Error
+
+ async listIssues() { return { items: [] as GitHubIssue[] } }
+ /** Runs inside the heartbeat — lets a test change the configuration between the heartbeat and the
+ * pull status read that follows it. */
+ onHeartbeat?: () => void
+ async issuesHeartbeat(_repository: string, etag?: string): Promise<IssueHeartbeatResult> {
+ this.heartbeats += 1
+ this.onHeartbeat?.()
+ if (this.changed || !etag) { this.changed = false; return { notModified: false, etag: `W/"${Math.random()}"` } }
+ return { notModified: true, etag }
+ }
+ async getIssue(): Promise<never> { throw new Error('unused') }
+ async updateIssue(): Promise<never> { throw new Error('unused') }
+ async listRepositoryLabels() { return { items: [] } }
+ async createLabel(): Promise<never> { throw new Error('unused') }
+ async createIssue(): Promise<never> { throw new Error('unused') }
+ async createIssueComment(): Promise<never> { throw new Error('unused') }
+ async pullRequestStatuses(): Promise<PullStatusRead> {
+ this.statusReads += 1
+ return { open: this.open, recent: [], access: { ci: true, merge: true }, truncated: false }
+ }
+ async pullRequestChecks(): Promise<GitHubPullChecksResult> {
+ this.checkReads += 1
+ if (this.failChecks) throw this.failChecks
+ return this.checks
+ }
+}
+
+function context(client: PullClient, revision = config.revision): GitHubIssueServiceContext {
+ return {
+ localApprovalId: 'local-1', projectId: 'project-1', repository: 'o/r', config: { ...config, revision },
+ controlRevision: 1,
+ credentialGeneration: 1, userId: 'user-1', client, columnColors: {}, mappingApproved: true
+ }
+}
+
+/** The poll and the subscribe refresh write the real on-disk cache, so "nothing else happens"
+ * needs a real settle, not a few microtask turns. */
+async function flush(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 40))
+}
+
+function harness(client = new PullClient()) {
+ let now = 1_000_000
+ let poll: (() => void) | undefined
+ let contexts = 0
+ let revision = config.revision
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator({ now: () => now }),
+ contextForProject: async () => { contexts += 1; return context(client, revision) },
+ now: () => now,
+ setInterval: (fn) => { poll = fn; return 1 },
+ clearInterval: () => { poll = undefined }
+ })
+ return {
+ client, service,
+ advance: (ms: number) => { now += ms },
+ poll: async () => { poll?.(); await flush() },
+ contexts: () => contexts,
+ setRevision: (next: string) => { revision = next }
+ }
+}
+
+describe('GitHubIssueService pull status', () => {
+ it('reads pull status on the first heartbeat, then only when the heartbeat reports a change', async () => {
+ const h = harness()
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ expect((await h.service.pullStatus({ projectId: 'project-1' })).pulls[0]).toMatchObject({ number: 1, ci: 'passed' })
+
+ h.advance(60_000)
+ await h.poll()
+ // The poll really ran (its heartbeat was sent) and answered 304: no GraphQL read.
+ await vi.waitFor(() => expect(h.client.heartbeats).toBe(2))
+ await flush()
+ expect(h.client.statusReads).toBe(1)
+
+ h.client.changed = true
+ h.advance(60_000)
+ await h.poll()
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(2))
+ })
+
+ it('a chase ping costs nothing until a read is due, and never resolves a context early', async () => {
+ const h = harness()
+ h.client.open = [facts(1, { rollup: 'PENDING' })]
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await flush()
+ const contextsBefore = h.contexts()
+ expect(await h.service.chasePulls({ projectId: 'project-1' })).toBe(false)
+ expect(h.contexts()).toBe(contextsBefore)
+ h.advance(30_000)
+ expect(await h.service.chasePulls({ projectId: 'project-1' })).toBe(true)
+ expect(h.client.statusReads).toBe(2)
+ })
+
+ it('a chase ping for a project with nothing undecided never reads', async () => {
+ const h = harness()
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await flush()
+ h.advance(3_600_000)
+ expect(await h.service.chasePulls({ projectId: 'project-1' })).toBe(false)
+ expect(h.client.statusReads).toBe(1)
+ })
+
+ it('check detail: hidden for a token that cannot read checks, never a failed board', async () => {
+ const h = harness()
+ h.client.failChecks = Object.assign(new Error('insufficient-permission'), { code: 'insufficient-permission', status: 403 })
+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })).toEqual({ status: 'hidden' })
+ h.client.failChecks = Object.assign(new Error('request-failed'), { code: 'request-failed', status: 502 })
+ h.advance(15_000)
+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })).toEqual({ status: 'unavailable' })
+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: -3 })).toEqual({ status: 'unavailable' })
+ })
+
+ it('bounds check-detail reads: one per PR per 15 s, ten per project per minute', async () => {
+ const h = harness()
+ h.client.checks = { status: 'no-checks' }
+ await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })
+ await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })
+ expect(h.client.checkReads).toBe(1)
+ for (let number = 2; number <= 10; number++) {
+ await h.service.pullChecks({ projectId: 'project-1', pullNumber: number })
+ }
+ expect(h.client.checkReads).toBe(10)
+ const contexts = h.contexts()
+ for (let number = 11; number <= 20; number++) {
+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: number }))
+ .toEqual({ status: 'unavailable' })
+ }
+ expect(h.client.checkReads).toBe(10)
+ // Refused before a context (the credential chain) is resolved.
+ expect(h.contexts()).toBe(contexts)
+ h.advance(60_000)
+ await h.service.pullChecks({ projectId: 'project-1', pullNumber: 21 })
+ expect(h.client.checkReads).toBe(11)
+ })
+
+ it('does not ask for check detail once the list read showed the token cannot read checks', async () => {
+ const h = harness()
+ h.client.pullRequestStatuses = async () => {
+ h.client.statusReads += 1
+ return { open: [facts(1)], recent: [], access: { ci: false, merge: true }, truncated: false }
+ }
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await flush()
+ expect(await h.service.pullChecks({ projectId: 'project-1', pullNumber: 1 })).toEqual({ status: 'hidden' })
+ expect(h.client.checkReads).toBe(0)
+ })
+
+ it('clearing the cache forgets pull status and deletes its memory file', async () => {
+ const h = harness()
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ const memoryDir = path.join(userDataDir, 'github-pull-memory')
+ await vi.waitFor(async () => expect(await fs.readdir(memoryDir).catch(() => [])).toHaveLength(1))
+ await h.service.clearCache({ projectId: 'project-1' })
+ expect(await fs.readdir(memoryDir).catch(() => [])).toEqual([])
+ // Bind the same identity again with a read that never answers: nothing from before the clear may
+ // come back under that key.
+ h.client.pullRequestStatuses = () => new Promise(() => undefined)
+ h.advance(120_000)
+ await h.service.refresh({ projectId: 'project-1' })
+ await flush()
+ expect((await h.service.pullStatus({ projectId: 'project-1' })).pulls).toEqual([])
+ })
+
+ it('a configuration change between the heartbeat and the read is not a failed read', async () => {
+ const h = harness()
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ h.client.changed = true
+ h.client.onHeartbeat = () => h.setRevision('mapping-2')
+ h.advance(120_000)
+ await h.service.refresh({ projectId: 'project-1' })
+ await flush()
+ expect(h.client.statusReads).toBe(1)
+ expect((await h.service.pullStatus({ projectId: 'project-1' })).stale).toBe(false)
+ })
+
+ it('a move claim is won once, and malformed asks are refused', async () => {
+ const h = harness()
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [1] })).toBe(false)
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [2, 1] })).toBe(true)
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [1, 2] })).toBe(false)
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'other', pulls: [1, 2] })).toBe(true)
+ for (const bad of [
+ { projectId: 'project-1', cardId: '', pulls: [1] },
+ { projectId: 'project-1', cardId: 'x'.repeat(300), pulls: [1] },
+ { projectId: 'project-1', cardId: 'n\u0001', pulls: [1] },
+ { projectId: 'project-1', cardId: 'n', pulls: [] },
+ { projectId: 'project-1', cardId: 'n', pulls: [0] },
+ null
+ ]) {
+ expect(await h.service.claimPullAutoMove(bad as never)).toBe(false)
+ }
+ })
+})
diff --cc src/renderer/canvas/Canvas.tsx
index 12fe7f4bd,adaf08aa6..416faa564
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@@ -15009,7 -15204,7 +15235,8 @@@ export function Canvas()
onBrowserNav={browserNavFromKanban}
onSetIcon={setNodeIcon}
accountMenuItems={accountSwitchRows}
+ onAutoMoveFromPulls={autoMoveCardFromPulls}
+ issueAgentMenu={issueAgentMenu}
/>
)}
<UpdateCard />
diff --cc src/renderer/components/kanban/CardPullRequests.test.tsx
index d7c7a8d66,000000000..cbbccab7c
mode 100644,000000..100644
--- a/src/renderer/components/kanban/CardPullRequests.test.tsx
+++ b/src/renderer/components/kanban/CardPullRequests.test.tsx
@@@ -1,95 -1,0 +1,106 @@@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ProjectKanban } from '@shared/types'
+import type { GitHubPullBoard } from '@shared/github-pull-status'
+import { readPullLinks } from '@shared/kanban-pull-links'
+import { useProjects } from '../../state/projects'
+import { useGitHubIssues } from '../../state/githubIssues'
+import { useSettings } from '../../state/settings'
+import { CardPullRequests, PULL_LINK_SSH_REASON } from './CardPullRequests'
+import type { KanbanSession } from './KanbanView'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const board: ProjectKanban = {
+ columns: [{ id: 'doing', title: 'Doing', color: '#fff' }, { id: 'done', title: 'Done', color: '#fff' }],
+ assignments: [],
+ github: { columnMappings: [], repository: 'o/r' }
+}
+
+const session = (over: Partial<KanbanSession> = {}): KanbanSession => ({
+ id: 'card-1', title: 'Agent', color: '#fff', kind: 'terminal', spawn: {}, worktreeBranch: 'feat/x', ...over
+})
+
+const pullBoard: GitHubPullBoard = {
+ pulls: [
+ { number: 12, lifecycle: 'open', headRefName: 'feat/x', headRefOid: 'a'.repeat(40), ci: 'passed', merge: 'ready', closes: [] },
+ { number: 3, lifecycle: 'closed', headRefName: 'feat/x', closes: [] }
+ ],
+ observedAt: 1, stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false
+}
+
+function setup(ssh = false): void {
+ useProjects.setState({
+ activeProjectId: 'p1',
+ projects: [{
+ id: 'p1', name: 'P', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [],
+ ...(ssh ? { ssh: { server: { host: 'h', user: 'u' } as never, remoteCwd: '~' } } : {})
+ }]
+ } as never)
+ useGitHubIssues.setState({ projects: { p1: { pullBoard } as never } })
+ useSettings.setState({
+ settings: { ...useSettings.getState().settings, kanbanPullAutoMove: { projects: { p1: { columnId: 'done', armedAt: 1 } } } }
+ })
+}
+
+function render(k: ProjectKanban, card = session()): { host: HTMLElement; onChange: ReturnType<typeof vi.fn> } {
+ const host = document.createElement('div')
+ const onChange = vi.fn()
+ act(() => createRoot(host).render(<CardPullRequests session={card} board={k} onChangeBoard={onChange} />))
+ return { host, onChange }
+}
+
+beforeEach(() => setup())
+
+describe('CardPullRequests', () => {
+ it('lists the PRs from the card\'s worktree branch', () => {
+ const { host } = render(board)
+ expect(host.textContent).toContain('feat/x')
+ expect(host.textContent).toContain('PR #12')
+ expect(host.textContent).toContain('PR #3')
+ })
+
+ it('unlinking writes a tombstone, so the branch link does not come back', () => {
+ const { host, onChange } = render(board)
+ const unlink = [...host.querySelectorAll('button')].find((button) => button.textContent === 'Unlink')!
+ act(() => unlink.click())
+ const next = onChange.mock.calls[0][0] as ProjectKanban
+ expect(readPullLinks(next).unlinked).toEqual([{ nodeId: 'card-1', pull: 12 }])
+ const again = render(next).host
+ expect(again.textContent).toContain('PR #12 (unlinked)')
+ expect(again.textContent).toContain('Link again')
+ })
+
+ it('says why a closed-unmerged PR blocks the move, and offers the per-card opt-out', () => {
+ const { host, onChange } = render(board)
+ expect(host.textContent).toContain('closed without merging')
+ const optOut = host.querySelector<HTMLInputElement>('input[type="checkbox"]')!
+ expect(optOut.checked).toBe(true)
+ act(() => optOut.click())
+ expect(readPullLinks(onChange.mock.calls[0][0] as ProjectKanban).noAutoMove).toEqual(['card-1'])
+ })
+
+ it('an SSH project says why links are not available instead of showing nothing', () => {
+ setup(true)
+ expect(render(board).host.textContent).toContain(PULL_LINK_SSH_REASON)
+ })
+
++ it('an issue-bound session shows the PRs closing its issue, on SSH too', () => {
++ setup(true)
++ useGitHubIssues.setState({ projects: { p1: { pullBoard: { ...pullBoard, repository: 'o/r', pulls: [
++ { number: 21, lifecycle: 'open', headRefName: 'elsewhere', closes: [4] }
++ ] } } as never } })
++ const host = render(board, session({ worktreeBranch: undefined, issueRef: { owner: 'o', repo: 'r', number: 4 } })).host
++ expect(host.textContent).toContain('PR #21')
++ expect(host.textContent).toContain('closes #4')
++ expect(host.textContent).not.toContain(PULL_LINK_SSH_REASON)
++ })
++
+ it('renders nothing for a board without GitHub or a card outside a worktree group', () => {
+ const { github: _github, ...plain } = board
+ expect(render(plain).host.textContent).toBe('')
+ expect(render(board, session({ worktreeBranch: undefined })).host.textContent).toBe('')
+ })
+})
diff --cc src/renderer/components/kanban/CardPullRequests.tsx
index e5a91fc50,000000000..a203e9032
mode 100644,000000..100644
--- a/src/renderer/components/kanban/CardPullRequests.tsx
+++ b/src/renderer/components/kanban/CardPullRequests.tsx
@@@ -1,111 -1,0 +1,123 @@@
+import { useMemo } from 'react'
+import type { ProjectKanban } from '@shared/types'
+import { pullStatusFreshness } from '@shared/github-pull-status'
+import {
+ readPullLinks,
+ relinkPull,
+ sanitizeKanbanPullAutoMove,
+ setNoAutoMove,
+ unlinkPull
+} from '@shared/kanban-pull-links'
+import { useProjects } from '../../state/projects'
+import { useGitHubIssues } from '../../state/githubIssues'
+import { useSettings } from '../../state/settings'
+import { pullsForCard } from '../../lib/pullLinks'
+import { PullRefChip } from './PullStatusBadges'
+import type { KanbanSession } from './KanbanView'
+
+/** Same reason the worktree affordances give on an SSH project: a branch link needs a worktree
+ * group, and worktree groups are local-only in v1. */
+export const PULL_LINK_SSH_REASON =
+ 'Linking pull requests needs a worktree group, and worktrees are not supported on SSH projects yet.'
+
+/**
- * The card modal's "Pull requests" section: the PRs whose head is this card's worktree branch, each
- * removable (the removal is a git-shared tombstone, so the branch auto-link does not come back),
- * plus this card's auto-move opt-out. Renders nothing for a board without GitHub or a card outside
- * a worktree group — there is nothing to say there.
++ * The card modal's "Pull requests" section: the PRs whose head is this card's worktree branch, and
++ * the PRs that close the issue the session was started on, each removable (the removal is a
++ * git-shared tombstone, so the auto-link does not come back), plus this card's auto-move opt-out.
++ * Renders nothing for a board without GitHub, or a card with neither a worktree group nor an issue.
+ */
+export function CardPullRequests({
+ session,
+ board,
+ onChangeBoard
+}: {
+ session: KanbanSession
+ board: ProjectKanban
+ onChangeBoard: (next: ProjectKanban) => void
+}): React.JSX.Element | null {
+ const projectId = useProjects((state) => state.activeProjectId)
+ const ssh = useProjects((state) => !!state.projects.find((item) => item.id === state.activeProjectId)?.ssh)
+ const pullBoard = useGitHubIssues((state) => state.projects[projectId]?.pullBoard)
+ const autoMoveRaw = useSettings((state) => state.settings.kanbanPullAutoMove)
+ const target = useMemo(() => {
+ const entry = sanitizeKanbanPullAutoMove(autoMoveRaw).projects[projectId]
+ return entry ? board.columns.find((column) => column.id === entry.columnId) : undefined
+ }, [autoMoveRaw, projectId, board.columns])
+ if (!board.github) return null
- if (ssh) {
++ // On SSH only the branch half is unavailable: an issue-bound session still links through its issue.
++ if (ssh && !session.issueRef) {
+ return (
+ <section className="card-pulls" aria-label="Pull requests">
+ <p className="card-pulls__note">{PULL_LINK_SSH_REASON}</p>
+ </section>
+ )
+ }
- if (!session.worktreeBranch) return null
++ if (!session.worktreeBranch && !session.issueRef) return null
+ const links = pullsForCard(session, pullBoard, board)
+ const freshness = pullBoard ? pullStatusFreshness(pullBoard, Date.now()) : 'fresh'
+ const optedOut = readPullLinks(board).noAutoMove.includes(session.id)
+ const abandoned = links.linked.filter((pull) => pull.lifecycle === 'closed')
+ return (
+ <section className="card-pulls" aria-label="Pull requests">
+ <div className="card-pulls__head">
+ <span className="card-pulls__title">Pull requests</span>
- <span className="card-pulls__branch" title="The branch of this card's worktree group">
- {session.worktreeBranch}
- </span>
++ {session.worktreeBranch && (
++ <span className="card-pulls__branch" title="The branch of this card's worktree group">
++ {session.worktreeBranch}
++ </span>
++ )}
++ {session.issueRef && (
++ <span className="card-pulls__branch" title="Pull requests that close the issue this session was started on">
++ closes #{session.issueRef.number}
++ </span>
++ )}
+ </div>
+ {links.linked.length === 0 && links.unlinked.length === 0 && (
+ <p className="card-pulls__note">
- {pullBoard ? 'No pull request from this branch yet.' : 'Pull request status is not available.'}
++ {!pullBoard
++ ? 'Pull request status is not available.'
++ : session.worktreeBranch
++ ? 'No pull request from this branch yet.'
++ : 'No open pull request closes this issue yet.'}
+ </p>
+ )}
+ {links.linked.map((pull) => (
+ <div key={pull.number} className="card-pulls__row">
+ <PullRefChip status={pull} freshness={freshness} />
+ <button
+ className="card-pulls__action"
+ onClick={() => onChangeBoard(unlinkPull(board, session.id, pull.number))}
+ title="This card is not about this pull request. The link will not come back."
+ >
+ Unlink
+ </button>
+ </div>
+ ))}
+ {links.unlinked.map((pull) => (
+ <div key={pull.number} className="card-pulls__row card-pulls__row--unlinked">
+ <span className="pull-ref">PR #{pull.number} (unlinked)</span>
+ <button className="card-pulls__action" onClick={() => onChangeBoard(relinkPull(board, session.id, pull.number))}>
+ Link again
+ </button>
+ </div>
+ ))}
+ {target && links.linked.length > 0 && (
+ <>
+ {abandoned.length > 0 && !optedOut && (
+ <p className="card-pulls__note card-pulls__note--warn">
+ {abandoned.map((pull) => `PR #${pull.number}`).join(', ')} closed without merging, so this card will not move. Unlink it to let the card move when the rest merge.
+ </p>
+ )}
+ <label className="card-pulls__optout">
+ <input
+ type="checkbox"
+ checked={!optedOut}
+ onChange={(event) => onChangeBoard(setNoAutoMove(board, session.id, !event.target.checked))}
+ />
+ Move this card to “{target.title}” when its pull requests merge
+ </label>
+ </>
+ )}
+ </section>
+ )
+}
diff --cc src/renderer/components/kanban/GitHubIssueCard.tsx
index 96575a71c,45341508a..3369c1bb2
--- a/src/renderer/components/kanban/GitHubIssueCard.tsx
+++ b/src/renderer/components/kanban/GitHubIssueCard.tsx
@@@ -1,9 -1,9 +1,11 @@@
import { memo, useState } from 'react'
import type { GitHubIssueCardView } from '@shared/github-issues'
+import type { GitHubPullStatus, PullStatusFreshness } from '@shared/github-pull-status'
import type { KanbanColumn } from '@shared/types'
import { updatedRelative } from '../../lib/relativeTime'
+import { PullRefChip } from './PullStatusBadges'
+ import { NO_ISSUE_RUNS, type IssueRun } from '../../lib/issueRuns'
+ import { IssueRunChips } from './IssueRunChips'
export const GitHubIssueCard = memo(function GitHubIssueCard({
issue,
diff --cc src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
index f3088ffe1,ebaeaac1f..fccf8bbbb
--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
@@@ -1,12 -1,7 +1,13 @@@
import { useEffect, useRef, useState } from 'react'
import type { GitHubIssueCardView } from '@shared/github-issues'
+import type {
+ GitHubPullChecksResult,
+ GitHubPullStatus,
+ PullStatusFreshness
+} from '@shared/github-pull-status'
+import { PullRefChip, PullStatusLine } from './PullStatusBadges'
import type { KanbanColumn } from '@shared/types'
+ import { issueLogId, issueRefFromHtmlUrl } from '@shared/github-issue-ref'
import { useSession } from '../../session/session'
import { Button } from '@renderer/ui/Button'
import { Select } from '@renderer/ui/Select'
@@@ -20,11 -19,10 +25,15 @@@ export function GitHubIssueSummaryModal
kind = 'issue',
onMove,
onClose,
+ projectId,
+ pullStatus,
+ closingPulls = [],
+ pullFreshness = 'fresh',
- pullObservedAt
++ pullObservedAt,
+ startMenu,
+ runs = NO_ISSUE_RUNS,
+ onOpenRun,
+ showRunHistory = false
}: {
issue: GitHubIssueCardView
columns: KanbanColumn[]
@@@ -36,20 -34,23 +45,34 @@@
kind?: 'issue' | 'pull'
onMove: (columnId: string | null) => void
onClose: () => void
+ /** Needed to fetch a PR's check detail; absent = no detail section. */
+ projectId?: string
+ /** Pull kind: the PR's CI/merge state. Issue kind: unused. */
+ pullStatus?: GitHubPullStatus
+ /** Issue kind: open PRs that close this issue on merge. */
+ closingPulls?: GitHubPullStatus[]
+ pullFreshness?: PullStatusFreshness
+ pullObservedAt?: number
+ /** The "Start with agent ▸" rows (the canvas's own agent + account picker, pointed at this
+ * issue). Absent = no button — a pull request, or a board with no canvas behind it. */
+ startMenu?: () => MenuItem[]
+ /** Sessions already working on this issue — the same live chips the card shows. */
+ runs?: readonly IssueRun[]
+ onOpenRun?: (nodeId: string) => void
+ /** Show the issue card's read-only run history (its board-log feed). */
+ showRunHistory?: boolean
}): React.JSX.Element {
const isPull = kind === 'pull'
const { api } = useSession()
+ const [startAt, setStartAt] = useState<{ x: number; y: number } | null>(null)
+ // The run history is filed under the issue card's synthetic board-log id. No id (a card whose
+ // URL did not parse) = no history panel, rather than a panel keyed on something made up.
+ const logId = !isPull && showRunHistory
+ ? issueLogId(issueRefFromHtmlUrl(issue.htmlUrl, issue.number))
+ : undefined
+ const pullOpen = isPull && issue.state === 'open'
+ const checks = usePullChecks(api.githubIssues, pullOpen ? projectId : undefined, issue.number,
+ pullStatus?.headRefOid)
const close = useRef<HTMLButtonElement>(null)
const dialog = useRef<HTMLElement>(null)
const opener = useRef(document.activeElement instanceof HTMLElement ? document.activeElement : null)
diff --cc src/renderer/components/kanban/KanbanView.tsx
index fc104adfc,2c1a8233b..f0d74684d
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@@ -123,11 -123,12 +129,17 @@@ export interface KanbanViewProps
* with no canvas behind it (a test, a future read-only view) simply shows no rows.
*/
accountMenuItems?: (nodeId: string) => MenuItem[]
+ /** The board moving a session card itself because its linked pull requests merged (Canvas owns
+ * the compare-and-set + board-log line). Optional: without it nothing ever auto-moves. */
+ onAutoMoveFromPulls?: (
+ projectId: string, cardId: string, fromColumnId: string | null, toColumnId: string, note: string
+ ) => void
+ /**
+ * "Start with agent ▸" rows for a GitHub issue card — the canvas's own agent + account picker
+ * (`agentCreationEntries`), pointed at starting a bound session on that issue. Optional for the
+ * same reason as `accountMenuItems`: a board with no canvas behind it offers none.
+ */
+ issueAgentMenu?: (issue: GitHubIssueCardView) => MenuItem[]
}
type Drag =
@@@ -197,7 -185,7 +209,7 @@@ function useCanvasCovered(): void
export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
- onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, onAutoMoveFromPulls
- onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, issueAgentMenu
++ onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, onAutoMoveFromPulls, issueAgentMenu
}: KanbanViewProps) {
useCanvasCovered()
const { api } = useSession()
@@@ -371,34 -373,26 +409,53 @@@
[customAgents, disabledAgents]
)
const byId = useMemo(() => new Map(sessions.map((s) => [s.id, s])), [sessions])
+ // Sessions bound to each GitHub issue, keyed case-insensitively. The previous map is handed back
+ // in so an unchanged group keeps its array — `sessions` is re-derived on every canvas change, and
+ // a fresh array per render would re-render every bound issue card.
+ const runsRef = useRef<ReadonlyMap<string, readonly IssueRun[]>>(new Map())
+ const runsByIssue = useMemo(() => {
+ runsRef.current = boundRunsByIssue(sessions, runsRef.current)
+ return runsRef.current
+ }, [sessions])
+ const runsFor = useCallback((issue: GitHubIssueCardView): readonly IssueRun[] => {
+ const key = issueKey(issueRefFromHtmlUrl(issue.htmlUrl, issue.number))
+ return (key && runsByIssue.get(key)) || NO_ISSUE_RUNS
+ }, [runsByIssue])
+ const handleIssueContext = useCallback(
+ (issue: GitHubIssueCardView, x: number, y: number) => setIssueMenu({ issue, x, y }),
+ []
+ )
+ const handleOpenIssueRef = useCallback((ref: IssueRef) => {
+ useViewMode.getState().requestIssue(ref)
+ }, [])
const sessionIds = useMemo(() => sessions.map((s) => s.id), [sessions])
+ // Stable per-card PR arrays (SessionCard is memoized): rebuilt only when the pull board, the
+ // cards or the board's own link tombstones change.
+ const pullLinksKey = JSON.stringify(board.pullLinks ?? null)
+ const pullsByCard = useMemo(() => {
+ const byCard = new Map<string, GitHubPullStatus[]>()
+ if (!board.github) return byCard
+ for (const session of sessions) {
+ const linked = pullsForCard(session, pullBoard, board).linked
+ if (linked.length) byCard.set(session.id, linked)
+ }
+ return byCard
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [sessions, pullBoard, pullLinksKey, !!board.github])
+ usePullChase(api.githubIssues, projectId, !!board.github && !!pullBoard?.undecided)
+ const autoMove = useCallback(
+ (cardId: string, fromColumnId: string | null, toColumnId: string, note: string) =>
+ onAutoMoveFromPulls?.(projectId, cardId, fromColumnId, toColumnId, note),
+ [onAutoMoveFromPulls, projectId]
+ )
+ usePullAutoMove({
+ api: api.githubIssues,
+ projectId,
+ cards: sessions,
+ board,
+ pullBoard: board.github ? pullBoard : undefined,
+ ...(onAutoMoveFromPulls ? { onAutoMove: autoMove } : {})
+ })
// The chips' facts through a DERIVED SIGNATURE (a primitive that changes only when a card's
// running / needs-you / unread fact does) — never `byId`, which changes on every hook event of
// every node and would re-render the whole board each time.
@@@ -971,11 -992,15 +1066,20 @@@
status={github?.issueStatus[modalIssue.item.number]}
onMove={(columnId) => handleMoveGitHub(modalIssue.item, columnId)}
onClose={() => setModalIssue(null)}
+ projectId={projectId}
+ pullStatus={modalIssue.kind === 'pull' ? pullByNumber.get(modalIssue.item.number) : undefined}
+ closingPulls={modalIssue.kind === 'issue' ? pullsByIssue.get(modalIssue.item.number) : undefined}
+ pullFreshness={pullFreshness}
+ pullObservedAt={pullBoard?.observedAt}
+ startMenu={modalIssue.kind === 'issue' && issueAgentMenu
+ ? () => issueAgentMenu(modalIssue.item)
+ : undefined}
+ runs={modalIssue.kind === 'issue' ? runsFor(modalIssue.item) : NO_ISSUE_RUNS}
+ onOpenRun={(nodeId) => {
+ setModalIssue(null)
+ setModalNodeId(nodeId)
+ }}
+ showRunHistory={modalIssue.kind === 'issue'}
/>
)}
{pendingCategory && (
diff --cc src/renderer/components/kanban/SessionCard.tsx
index 3edaf12be,b68ec4ed3..a8c0ddd3d
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@@ -8,8 -8,8 +8,10 @@@ import { NodeIconView } from '../NodeIc
import { LabelChips } from './LabelChips'
import { PRIORITIES } from './CardMetaBar'
import type { KanbanSession } from './KanbanView'
+import type { GitHubPullStatus, PullStatusFreshness } from '@shared/github-pull-status'
+import { PullRefChip } from './PullStatusBadges'
+ import type { IssueRef } from '@shared/github-issue-ref'
+ import { IssueRefChip } from '../IssueRefChip'
import { cardBadge } from '../../lib/kanbanStatusChips'
const PRIO_COLOR = Object.fromEntries(PRIORITIES.map((p) => [p.id, p.color])) as Record<KanbanPriority, string>
@@@ -29,14 -29,12 +31,16 @@@ interface SessionCardProps
onDropAt: (nodeId: string, side: 'before' | 'after') => void
/** Right-click on the card — opens the actions menu at the cursor. */
onContext: (nodeId: string, x: number, y: number) => void
+ /** Pull requests linked to this card through its worktree branch (stable array per card). */
+ pulls?: GitHubPullStatus[]
+ pullFreshness?: PullStatusFreshness
+ /** The session's `#N` chip (it was started on a GitHub issue): open that issue. */
+ onOpenIssue?: (ref: IssueRef) => void
}
export const SessionCard = memo(function SessionCard({
- session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext, onOpenIssue
+ session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext, pulls,
- pullFreshness = 'fresh'
++ pullFreshness = 'fresh', onOpenIssue
}: SessionCardProps) {
// THIS card's agent status, subscribed per card rather than threaded down from the board.
// KanbanView used to hold `useAgentStatus((s) => s.byId)` and pass the map through the column:
diff --cc src/renderer/components/kanban/board-writers.guard.test.ts
index 000000000,70c33379c..0b37a0b0e
mode 000000,100644..100644
--- a/src/renderer/components/kanban/board-writers.guard.test.ts
+++ b/src/renderer/components/kanban/board-writers.guard.test.ts
@@@ -1,0 -1,75 +1,79 @@@
+ import { describe, expect, it } from 'vitest'
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
+ import path from 'node:path'
+
+ /**
+ * "A hook `done` never moves a card" is a property of what DOESN'T exist: nowhere in the renderer
+ * is a board assignment or a GitHub issue move written in response to agent status. A test that
+ * flips an agent to `done` and watches one component cannot prove that — the write it guards
+ * against would live somewhere else (a hook listener in Canvas, a status store subscription). So
+ * this enumerates EVERY call site that writes a board: each one is listed with the human or agent
+ * ACTION that triggers it. A new writer fails this test until someone adds it here and signs for
+ * its trigger — and "an agent's turn ended" is not an acceptable one. `done` means a turn ended,
- * not that the work did: cards move when a person drags them or a session `assign`s itself.
++ * not that the work did: cards move when a person drags them, a session `assign`s itself, or — only
++ * where a person switched it on — every pull request linked to a session card has merged.
+ *
+ * Scope: the renderer, where the agent-status store and every board surface live. The core's relay
+ * verbs (`projects.setCardColumn`) are phone-initiated and are not reachable from a hook.
+ */
+ const RENDERER = path.resolve(__dirname, '../..')
+
+ /** file (relative to src/renderer) → the triggers of its board writes, one entry per call site. */
+ const BOARD_WRITERS: Record<string, string[]> = {
+ 'canvas/Canvas.tsx': [
+ 'onKanbanChange — the per-project board committing a person\'s drag/edit',
+ 'createNodeInColumn — a person\'s "+ New" in a column',
+ 'startIssueAgent — a person\'s "Start with agent" filing the new session under the issue card\'s column',
- 'the `assign` control verb — a session moving its OWN card (the issue-bound contract)'
++ 'the `assign` control verb — a session moving its OWN card (the issue-bound contract)',
++ 'autoMoveCardFromPulls — the merge-driven move: a person switched it on for this machine in ' +
++ 'Settings, and it fires only on a pull request MERGE this machine observed after that (never on ' +
++ 'agent status), after winning the host\'s one-time claim; session cards only'
+ ],
+ 'components/kanban/GlobalKanbanView.tsx': ['onChangeBoard — the Omni board committing a person\'s drag/edit'],
+ 'components/kanban/NodeLabels.tsx': ['a person editing a node\'s labels'],
+ 'components/settings/sections/GitHubIssuesSection.tsx': ['a person editing the board\'s GitHub config'],
+ 'components/kanban/KanbanView.tsx': [
+ 'requestGitHubMove — a person moving an issue card (drag, Move select, summary modal)',
+ 'the close/reopen ConfirmDialog — a person confirming that move'
+ ],
+ 'state/githubIssues.ts': ['the store\'s `move`, called only by the two KanbanView sites above']
+ }
+
+ const WRITER = /\bsetProjectKanban\(|\bmoveGitHubState\(|\.moveIssue\(/g
+ // The store's own declaration/implementation of setProjectKanban is not a call site.
+ const DECLARATION = /setProjectKanban\((id: string|id, kanban\))/
+
+ function sources(dir: string): string[] {
+ const out: string[] = []
+ for (const entry of readdirSync(dir)) {
+ const full = path.join(dir, entry)
+ if (statSync(full).isDirectory()) out.push(...sources(full))
+ else if (/\.(ts|tsx)$/.test(entry) && !/\.test\.(ts|tsx)$/.test(entry)) out.push(full)
+ }
+ return out
+ }
+
+ describe('board writers (why a hook `done` can never move a card)', () => {
+ it('every renderer call site that writes a board assignment or moves an issue is signed for', () => {
+ const found: Record<string, number> = {}
+ for (const file of sources(RENDERER)) {
+ const lines = readFileSync(file, 'utf8').replace(/\r\n/g, '\n').split('\n')
+ let count = 0
+ for (const line of lines) {
+ const t = line.trim()
+ if (t.startsWith('//') || t.startsWith('*') || DECLARATION.test(t)) continue
+ count += (t.match(WRITER) ?? []).length
+ }
+ if (count) found[path.relative(RENDERER, file).split(path.sep).join('/')] = count
+ }
+ const expected = Object.fromEntries(Object.entries(BOARD_WRITERS).map(([f, why]) => [f, why.length]))
+ expect(found).toEqual(expected)
+ })
+
+ it('the agent-status side of the issue binding writes nothing', () => {
+ for (const rel of ['state/agentStatus.ts', 'lib/issueRuns.ts', 'components/kanban/IssueRunChips.tsx']) {
+ const src = readFileSync(path.join(RENDERER, rel), 'utf8')
+ expect(src, rel).not.toMatch(/setProjectKanban|assignNode|moveIssue|moveGitHubState/)
+ }
+ })
+ })
diff --cc src/renderer/components/kanban/usePullAutoMove.ts
index a9b3f47d9,000000000..d499ce3fa
mode 100644,000000..100644
--- a/src/renderer/components/kanban/usePullAutoMove.ts
+++ b/src/renderer/components/kanban/usePullAutoMove.ts
@@@ -1,72 -1,0 +1,73 @@@
+import { useEffect, useMemo, useRef } from 'react'
+import type { ProjectKanban } from '@shared/types'
+import type { GitHubIssuesApi } from '@shared/github-issues'
+import type { GitHubPullBoard } from '@shared/github-pull-status'
++import type { IssueRef } from '@shared/github-issue-ref'
+import { sanitizeKanbanPullAutoMove } from '@shared/kanban-pull-links'
+import { useSettings } from '../../state/settings'
+import { useProjects } from '../../state/projects'
+import { autoMoveNote, planPullAutoMoves } from '../../lib/pullAutoMove'
+import { documentChaseDeps, startPullChase } from '../../lib/pullChase'
+
+/**
+ * Runs the merge-driven move for SESSION cards while the board is open (the pull status it reads is
+ * only fresh while a board is subscribed). All decisions are `planPullAutoMoves`, which writes
+ * nothing; this glue asks the host for each move's one-time claim and applies only the moves it wins,
+ * through `onAutoMove` (a compare-and-set against the latest board + the board-log line). It never
+ * writes settings: a background settings write from one Server Edition tab would overwrite whatever
+ * the user just changed in another.
+ */
+export function usePullAutoMove(input: {
+ api: Pick<GitHubIssuesApi, 'claimPullAutoMove'>
+ projectId: string
- cards: Array<{ id: string; kind: string; worktreeBranch?: string }>
++ cards: Array<{ id: string; kind: string; worktreeBranch?: string; issueRef?: IssueRef }>
+ board: ProjectKanban
+ pullBoard: GitHubPullBoard | undefined
+ onAutoMove?: (cardId: string, fromColumnId: string | null, toColumnId: string, note: string) => void
+}): void {
+ const raw = useSettings((state) => state.settings.kanbanPullAutoMove)
+ // A relay tab is another machine's project: that machine decides whether its board moves itself.
+ // Settings refuses to arm one; this is the backstop for a hand-edited settings.json.
+ const relay = useProjects((state) => !!state.projects.find((item) => item.id === input.projectId)?.remote)
+ const entry = useMemo(
+ () => relay ? undefined : sanitizeKanbanPullAutoMove(raw).projects[input.projectId],
+ [raw, input.projectId, relay]
+ )
+ const { api, projectId, cards, board, pullBoard, onAutoMove } = input
+ // The BOARD's lifetime, not one effect run: the pull board is re-read every minute, and a re-render
+ // landing between a won claim and its answer must not throw the move away — the claim is spent
+ // either way, so dropping it would lose the move for good.
+ const mounted = useRef(true)
+ useEffect(() => {
+ mounted.current = true
+ return () => { mounted.current = false }
+ }, [])
+ const latest = useRef(onAutoMove)
+ latest.current = onAutoMove
+ useEffect(() => {
+ if (!entry || !onAutoMove) return
+ for (const move of planPullAutoMoves({ cards, board, pullBoard, entry }).moves) {
+ void api.claimPullAutoMove({ projectId, cardId: move.cardId, pulls: move.pulls })
+ .then((claimed) => {
+ // A claim that lands after this board closed is spent, not applied: the card stays where it
+ // is, which is the safe side of a lost move. The move itself is a compare-and-set against
+ // the latest board, so a late answer cannot undo a drag made meanwhile.
+ if (claimed && mounted.current) {
+ latest.current?.(move.cardId, move.fromColumnId, entry.columnId, autoMoveNote(move.pulls))
+ }
+ })
+ .catch(() => undefined)
+ }
+ }, [api, entry, cards, board, pullBoard, projectId, onAutoMove])
+}
+
+/** While some PR is undecided, ask the host (only while the page is visible) whether a chase read
+ * is due. The host keeps the schedule and the cap. */
+export function usePullChase(api: GitHubIssuesApi, projectId: string, undecided: boolean): void {
+ useEffect(() => {
+ if (!undecided || !projectId) return
+ return startPullChase(documentChaseDeps(() => {
+ void api.chasePulls(projectId).catch(() => undefined)
+ }))
+ }, [api, projectId, undecided])
+}
diff --cc src/renderer/lib/pullAutoMove.test.ts
index 58fcfd4fa,000000000..41ec34301
mode 100644,000000..100644
--- a/src/renderer/lib/pullAutoMove.test.ts
+++ b/src/renderer/lib/pullAutoMove.test.ts
@@@ -1,155 -1,0 +1,164 @@@
+import { readFileSync } from 'node:fs'
+import path from 'node:path'
+import { describe, expect, it } from 'vitest'
+import type { ProjectKanban } from '@shared/types'
+import type { GitHubPullBoard, GitHubPullStatus } from '@shared/github-pull-status'
+import { setNoAutoMove, unlinkPull } from '@shared/kanban-pull-links'
+import { applyPullAutoMove, autoMoveNote, decidePullAutoMove, planPullAutoMoves } from './pullAutoMove'
+
+const ARMED = 1_000
+
+const board = (over: Partial<ProjectKanban> = {}): ProjectKanban => ({
+ columns: [
+ { id: 'doing', title: 'Doing', color: '#0a84ff' },
+ { id: 'done', title: 'Done', color: '#30d158' }
+ ],
+ assignments: [{ nodeId: 'card-1', columnId: 'doing' }],
+ ...over
+})
+
+/** A PR this machine saw open and then saw merge after the switch went on. */
+const observedMerge = (number: number, over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
+ ({ number, lifecycle: 'merged', headRefName: 'feat/x', closes: [], openSeen: true, mergedSeenAt: ARMED + 5, ...over })
+const pull = (number: number, lifecycle: GitHubPullStatus['lifecycle'], over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
+ ({ number, lifecycle, headRefName: 'feat/x', closes: [], ...over })
+
+const pulls = (items: GitHubPullStatus[], over: Partial<GitHubPullBoard> = {}): GitHubPullBoard => ({
+ pulls: items, observedAt: 1, stale: false, access: { ci: true, merge: true }, undecided: false,
+ truncated: false, ...over
+})
+
+const card = { id: 'card-1', kind: 'terminal', worktreeBranch: 'feat/x' }
+const entry = { columnId: 'done', armedAt: ARMED }
+
++const boardFor = (): ProjectKanban => board()
++
+describe('decidePullAutoMove — the guard order', () => {
+ const base = { optedOut: false, columnId: 'doing', targetColumnId: 'done', armedAt: ARMED }
+ const merged = { number: 1, lifecycle: 'merged' as const, mergedSeenAt: ARMED + 1 }
+
+ it('an opted-out card never moves, even when everything merged', () => {
+ expect(decidePullAutoMove({ ...base, optedOut: true, linked: [merged] }))
+ .toEqual({ kind: 'none', reason: 'opted-out' })
+ })
+
+ it('waits while any linked PR is open or a draft', () => {
+ expect(decidePullAutoMove({ ...base, linked: [merged, { number: 2, lifecycle: 'draft' }] }))
+ .toEqual({ kind: 'none', reason: 'waiting' })
+ })
+
+ it('a PR closed without merging blocks the move', () => {
+ expect(decidePullAutoMove({ ...base, linked: [merged, { number: 2, lifecycle: 'closed' }] }))
+ .toEqual({ kind: 'none', reason: 'blocked' })
+ })
+
+ it('moves only on a merge this machine observed after the switch went on', () => {
+ expect(decidePullAutoMove({ ...base, linked: [merged] })).toEqual({ kind: 'move', pulls: [1] })
+ expect(decidePullAutoMove({ ...base, linked: [{ number: 1, lifecycle: 'merged' }] }))
+ .toEqual({ kind: 'none', reason: 'no-transition' })
+ expect(decidePullAutoMove({ ...base, linked: [{ ...merged, mergedSeenAt: ARMED - 1 }] }))
+ .toEqual({ kind: 'none', reason: 'no-transition' })
+ })
+
+ it('does nothing for a card already in the target column', () => {
+ expect(decidePullAutoMove({ ...base, columnId: 'done', linked: [merged] }))
+ .toEqual({ kind: 'none', reason: 'in-target' })
+ })
+})
+
+describe('applyPullAutoMove — compare-and-set', () => {
+ it('moves the card from the column the decision saw', () => {
+ expect(applyPullAutoMove(board(), 'card-1', 'doing', 'done')?.assignments)
+ .toEqual([{ nodeId: 'card-1', columnId: 'done' }])
+ })
+
+ it('does nothing when the card moved since the decision', () => {
+ expect(applyPullAutoMove(board(), 'card-1', null, 'done')).toBeNull()
+ })
+
+ it('does nothing when the target column is gone', () => {
+ expect(applyPullAutoMove(board(), 'card-1', 'doing', 'deleted')).toBeNull()
+ })
+})
+
+describe('planPullAutoMoves', () => {
+ it('plans the move for a card whose only PR was seen open and then merged', () => {
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: pulls([observedMerge(1)]), entry }).moves)
+ .toEqual([{ cardId: 'card-1', fromColumnId: 'doing', pulls: [1] }])
+ })
+
+ it('a merge first seen already-merged, or seen before arming, moves nothing', () => {
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: pulls([pull(1, 'merged')]), entry }).moves)
+ .toEqual([])
+ expect(planPullAutoMoves({
+ cards: [card], board: board(), pullBoard: pulls([observedMerge(1, { mergedSeenAt: ARMED - 1 })]), entry
+ }).moves).toEqual([])
+ })
+
+ it('does nothing at all while the switch is off, the status is stale, or unknown', () => {
+ const merged = pulls([observedMerge(1)])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: merged, entry: undefined }).moves).toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: { ...merged, stale: true }, entry }).moves)
+ .toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: undefined, entry }).moves).toEqual([])
+ })
+
+ it('an unlinked PR does not count, and an opted-out card stays put', () => {
+ const merged = pulls([observedMerge(1)])
+ expect(planPullAutoMoves({ cards: [card], board: unlinkPull(board(), 'card-1', 1), pullBoard: merged, entry }).moves)
+ .toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: setNoAutoMove(board(), 'card-1', true), pullBoard: merged, entry }).moves)
+ .toEqual([])
+ })
+
+ it('a closed-unmerged sibling blocks until the user removes that link', () => {
+ const both = pulls([observedMerge(1), pull(2, 'closed')])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: both, entry }).moves).toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: unlinkPull(board(), 'card-1', 2), pullBoard: both, entry }).moves)
+ .toEqual([{ cardId: 'card-1', fromColumnId: 'doing', pulls: [1] }])
+ })
+
++ it('moves a session started on an issue once the PR that closes it merged', () => {
++ const issueCard = { id: 'card-1', kind: 'terminal', issueRef: { owner: 'o', repo: 'r', number: 4 } }
++ const board = { ...pulls([observedMerge(9, { closes: [4], headRefName: 'someone/else' })]), repository: 'o/r' }
++ expect(planPullAutoMoves({ cards: [issueCard], board: boardFor(), pullBoard: board, entry }).moves)
++ .toEqual([{ cardId: 'card-1', fromColumnId: 'doing', pulls: [9] }])
++ })
++
+ it("a fork PR on a same-named branch is not this card's work", () => {
+ const plan = planPullAutoMoves({
+ cards: [card], board: board(), pullBoard: pulls([observedMerge(1, { crossRepository: true })]), entry
+ })
+ expect(plan.moves).toEqual([])
+ })
+
+ it('GitHub issue cards are never moved — GitHub closes them itself', () => {
+ const plan = planPullAutoMoves({
+ cards: [{ id: 'github:12', kind: 'github', worktreeBranch: 'feat/x' }],
+ board: board({ assignments: [{ nodeId: 'github:12', columnId: 'doing' }] }),
+ pullBoard: pulls([observedMerge(1, { closes: [12] })]),
+ entry
+ })
+ expect(plan.moves).toEqual([])
+ })
+
+ it('the planner and its hook never reach the GitHub issue write path, and never write settings', () => {
+ for (const file of ['pullAutoMove.ts', '../components/kanban/usePullAutoMove.ts']) {
+ const source = readFileSync(path.join(__dirname, file), 'utf8').replace(/\r\n/g, '\n')
+ expect(source).not.toMatch(/moveIssue|githubIssues\s*\.\s*move|updateIssue/)
+ expect(source).not.toMatch(/\.update\(|settings\.save/)
+ }
+ })
+
+ it('is stable: the same inputs plan the same moves (no hidden state to converge)', () => {
+ const input = { cards: [card], board: board(), pullBoard: pulls([observedMerge(1)]), entry }
+ expect(planPullAutoMoves(input)).toEqual(planPullAutoMoves(input))
+ })
+})
+
+describe('helpers', () => {
+ it('names the PRs in the board-log line', () => {
+ expect(autoMoveNote([12])).toBe('PR #12 merged')
+ expect(autoMoveNote([12, 15])).toBe('PRs #12, #15 merged')
+ })
+})
diff --cc src/renderer/lib/pullAutoMove.ts
index 0af5f6f5f,000000000..4936a8f23
mode 100644,000000..100644
--- a/src/renderer/lib/pullAutoMove.ts
+++ b/src/renderer/lib/pullAutoMove.ts
@@@ -1,122 -1,0 +1,123 @@@
+// Moving a session card when the work it tracks has merged — the decision, pure.
+//
+// SESSION CARDS ONLY. A GitHub issue card is never moved here: GitHub already closes an issue when a
+// PR with "Closes #N" merges, and a second writer would race it (and could overwrite the
+// `state_reason` GitHub records). The board shows that close through its normal sync.
+//
+// The guards, in this order, each a refusal:
+// 1. the card opted out → never
+// 2. no linked PR → nothing to decide
+// 3. any linked PR still open or a draft → wait
+// 4. any linked PR closed WITHOUT merging → blocked until the user removes that link; an
+// abandoned PR is not finished work
+// 5. already in the target column → nothing to do
+// 6. all merged, but none of the merges was OBSERVED by this machine since the switch went on →
+// no move. The host remembers each PR it saw open and when it then saw it merge
+// (core/github/pull-memory.ts); arming the switch, or cloning a repo whose PRs merged long ago,
+// never sweeps old cards across the board.
+//
+// Remembered PRs keep a card blocked: a PR that closed unmerged stays on the host's pull board (and
+// so stays linked) until the user unlinks it — it does not expire when 30 newer PRs close.
+//
+// Nothing here writes. Each planned move must still win the host's one-time claim
+// (`githubIssues.claimPullAutoMove`) — so two windows cannot both move a card, and a card the user
+// dragged back is not moved again for the same merges — and is then applied as a compare-and-set.
+import type { ProjectKanban } from '@shared/types'
+import type { GitHubPullBoard, PullLifecycle } from '@shared/github-pull-status'
++import type { IssueRef } from '@shared/github-issue-ref'
+import { readPullLinks, type KanbanPullAutoMoveEntry } from '@shared/kanban-pull-links'
+import { assignNode, columnForNode } from './kanban'
+import { pullsForCard } from './pullLinks'
+
+export type PullAutoMoveDecision =
+ | { kind: 'move'; pulls: number[] }
+ | {
+ kind: 'none'
+ reason: 'opted-out' | 'no-links' | 'waiting' | 'blocked' | 'in-target' | 'no-transition'
+ }
+
+export function decidePullAutoMove(input: {
+ optedOut: boolean
+ linked: Array<{ number: number; lifecycle: PullLifecycle; mergedSeenAt?: number }>
+ columnId: string | null
+ targetColumnId: string
+ /** When this machine switched the move on; only merges it OBSERVED since then count. */
+ armedAt: number
+}): PullAutoMoveDecision {
+ if (input.optedOut) return { kind: 'none', reason: 'opted-out' }
+ if (input.linked.length === 0) return { kind: 'none', reason: 'no-links' }
+ if (input.linked.some((pull) => pull.lifecycle === 'open' || pull.lifecycle === 'draft')) {
+ return { kind: 'none', reason: 'waiting' }
+ }
+ if (input.linked.some((pull) => pull.lifecycle === 'closed')) return { kind: 'none', reason: 'blocked' }
+ if (input.columnId === input.targetColumnId) return { kind: 'none', reason: 'in-target' }
+ // The host records `mergedSeenAt` only for a PR it had seen open before — a merge first seen
+ // already-merged has none, and never counts.
+ const observed = input.linked.some((pull) =>
+ pull.mergedSeenAt !== undefined && pull.mergedSeenAt >= input.armedAt)
+ if (!observed) return { kind: 'none', reason: 'no-transition' }
+ return { kind: 'move', pulls: input.linked.map((pull) => pull.number).sort((a, b) => a - b) }
+}
+
+/**
+ * The move itself, as a compare-and-set: it applies only if the card is still in the column the
+ * decision saw (a teammate's pull, a drag a moment ago, or another window's move all make it a
+ * no-op) and the target column still exists. Null = nothing to write.
+ */
+export function applyPullAutoMove(
+ board: ProjectKanban,
+ cardId: string,
+ expectedColumnId: string | null,
+ targetColumnId: string
+): ProjectKanban | null {
+ const current = columnForNode(board, cardId)?.id ?? null
+ if (current !== expectedColumnId || current === targetColumnId) return null
+ if (!board.columns.some((column) => column.id === targetColumnId)) return null
+ return assignNode(board, cardId, targetColumnId, null)
+}
+
+/** The board-log line's reason: it names the PRs, so the move can be traced to what caused it. */
+export function autoMoveNote(pulls: number[]): string {
+ const list = pulls.map((number) => `#${number}`).join(', ')
+ return pulls.length === 1 ? `PR ${list} merged` : `PRs ${list} merged`
+}
+
+/** The board cards the auto-move may touch: the SESSION source, and only it. An issue card is not
+ * in this list by construction, and the planner re-checks the kind rather than trusting callers. */
+const SESSION_CARD_KINDS = new Set(['terminal', 'sticky', 'browser'])
+
+export interface PullAutoMovePlan {
+ moves: Array<{ cardId: string; fromColumnId: string | null; pulls: number[] }>
+}
+
+/**
+ * One pass over the board: which cards to move. Nothing moves while the switch is off, while the pull
+ * status is unknown or STALE (a decision on a snapshot GitHub could not confirm is a guess), or while
+ * the target column does not exist. Write-free by design — an earlier version kept "last seen" in
+ * settings.json and could loop against the sanitizer's bounds; observation now lives on the host.
+ */
+export function planPullAutoMoves(input: {
- cards: Array<{ id: string; kind: string; worktreeBranch?: string }>
++ cards: Array<{ id: string; kind: string; worktreeBranch?: string; issueRef?: IssueRef }>
+ board: ProjectKanban
+ pullBoard: GitHubPullBoard | undefined
+ entry: KanbanPullAutoMoveEntry | undefined
+}): PullAutoMovePlan {
+ const { entry, pullBoard, board } = input
+ if (!entry || !pullBoard || pullBoard.observedAt === undefined || pullBoard.stale) return { moves: [] }
+ if (!board.columns.some((column) => column.id === entry.columnId)) return { moves: [] }
+ const optedOut = new Set(readPullLinks(board).noAutoMove)
+ const moves: PullAutoMovePlan['moves'] = []
+ for (const card of input.cards) {
+ if (!SESSION_CARD_KINDS.has(card.kind)) continue
+ const fromColumnId = columnForNode(board, card.id)?.id ?? null
+ const decision = decidePullAutoMove({
+ optedOut: optedOut.has(card.id),
+ linked: pullsForCard(card, pullBoard, board).linked,
+ columnId: fromColumnId,
+ targetColumnId: entry.columnId,
+ armedAt: entry.armedAt
+ })
+ if (decision.kind === 'move') moves.push({ cardId: card.id, fromColumnId, pulls: decision.pulls })
+ }
+ return { moves }
+}
diff --cc src/renderer/lib/pullLinks.test.ts
index e40da7625,000000000..5b4c105ab
mode 100644,000000..100644
--- a/src/renderer/lib/pullLinks.test.ts
+++ b/src/renderer/lib/pullLinks.test.ts
@@@ -1,112 -1,0 +1,135 @@@
+import { describe, expect, it } from 'vitest'
+import type { ProjectKanban } from '@shared/types'
+import type { GitHubPullBoard, GitHubPullStatus } from '@shared/github-pull-status'
+import {
+ prunePullLinks,
+ readPullLinks,
+ relinkPull,
+ sanitizeKanbanPullAutoMove,
+ setNoAutoMove,
+ unlinkPull
+} from '@shared/kanban-pull-links'
+import { pruneAssignments } from './kanban'
+import { pullsClosingIssue, pullsForCard } from './pullLinks'
+
+const empty: ProjectKanban = { columns: [], assignments: [] }
+const pull = (number: number, over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
+ ({ number, lifecycle: 'open', headRefName: 'feat/x', closes: [], ...over })
+const pulls = (items: GitHubPullStatus[]): GitHubPullBoard => ({
++ repository: 'o/r',
+ pulls: items, observedAt: 1, stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false
+})
+
+describe('pullsForCard', () => {
+ it('links PRs whose head is the card\'s worktree branch, newest open first', () => {
+ const links = pullsForCard({ id: 'n', worktreeBranch: 'feat/x' }, pulls([
+ pull(3, { lifecycle: 'merged' }), pull(5), pull(4, { headRefName: 'feat/y' }), pull(7)
+ ]), empty)
+ expect(links.linked.map((item) => item.number)).toEqual([7, 5, 3])
+ })
+
+ it('never links a fork PR, whatever its branch is called', () => {
+ expect(pullsForCard({ id: 'n', worktreeBranch: 'feat/x' }, pulls([pull(5, { crossRepository: true })]), empty).linked)
+ .toEqual([])
+ })
+
+ it('a card outside a worktree group has no links', () => {
+ expect(pullsForCard({ id: 'n' }, pulls([pull(5)]), empty).linked).toEqual([])
+ })
+
+ it('an unlinked PR stays unlinked (and is offered back), even though the branch still matches', () => {
+ const board = unlinkPull(empty, 'n', 5)
+ const links = pullsForCard({ id: 'n', worktreeBranch: 'feat/x' }, pulls([pull(5), pull(6)]), board)
+ expect(links.linked.map((item) => item.number)).toEqual([6])
+ expect(links.unlinked.map((item) => item.number)).toEqual([5])
+ expect(pullsForCard({ id: 'n', worktreeBranch: 'feat/x' }, pulls([pull(5)]), relinkPull(board, 'n', 5))
+ .linked.map((item) => item.number)).toEqual([5])
+ // The tombstone is per card: another card on the same branch still links.
+ expect(pullsForCard({ id: 'other', worktreeBranch: 'feat/x' }, pulls([pull(5)]), board).linked).toHaveLength(1)
+ })
+})
+
++describe('pullsForCard — a session started on an issue', () => {
++ const issueCard = { id: 'n', issueRef: { owner: 'O', repo: 'R', number: 4 } }
++
++ it('links the PRs that close its issue, forks included, from the same repository only', () => {
++ const board = pulls([
++ pull(7, { closes: [4], headRefName: 'anything' }),
++ pull(8, { closes: [4], crossRepository: true, headRefName: 'fork/x' }),
++ pull(9, { closes: [5] })
++ ])
++ expect(pullsForCard(issueCard, board, empty).linked.map((item) => item.number)).toEqual([8, 7])
++ expect(pullsForCard({ ...issueCard, issueRef: { owner: 'else', repo: 'R', number: 4 } }, board, empty).linked)
++ .toEqual([])
++ })
++
++ it('joins with the branch link without duplicates, and honours tombstones', () => {
++ const board = pulls([pull(7, { closes: [4] }), pull(6)])
++ const card = { ...issueCard, worktreeBranch: 'feat/x' }
++ expect(pullsForCard(card, board, empty).linked.map((item) => item.number)).toEqual([7, 6])
++ expect(pullsForCard(card, board, unlinkPull(empty, 'n', 7)).linked.map((item) => item.number)).toEqual([6])
++ })
++})
++
+describe('pullsClosingIssue', () => {
+ it('lists open PRs that close the issue', () => {
+ expect(pullsClosingIssue(12, pulls([
+ pull(1, { closes: [12] }), pull(2, { closes: [13] }), pull(3, { closes: [12], lifecycle: 'merged' })
+ ])).map((item) => item.number)).toEqual([1])
+ })
+})
+
+describe('board pull links (git-shared, hostile input)', () => {
+ it('drops malformed entries instead of trusting them', () => {
+ const hostile = { ...empty, pullLinks: {
+ unlinked: [{ nodeId: 'n', pull: 5 }, { nodeId: 7, pull: 'x' }, null, { nodeId: 'm', pull: -1 }],
+ noAutoMove: ['n', 42, 'n']
+ } } as unknown as ProjectKanban
+ expect(readPullLinks(hostile)).toEqual({ unlinked: [{ nodeId: 'n', pull: 5 }], noAutoMove: ['n'] })
+ expect(readPullLinks({ ...empty, pullLinks: 'nope' } as unknown as ProjectKanban))
+ .toEqual({ unlinked: [], noAutoMove: [] })
+ })
+
+ it('a write keeps keys a newer build stored in the block', () => {
+ const newer = { ...empty, pullLinks: { issueLinks: [{ nodeId: 'n', issue: 4 }] } } as unknown as ProjectKanban
+ const next = unlinkPull(newer, 'n', 5)
+ expect((next.pullLinks as unknown as Record<string, unknown>).issueLinks).toEqual([{ nodeId: 'n', issue: 4 }])
+ expect(readPullLinks(next).unlinked).toEqual([{ nodeId: 'n', pull: 5 }])
+ const cleared = relinkPull(next, 'n', 5)
+ expect(cleared.pullLinks).toEqual({ issueLinks: [{ nodeId: 'n', issue: 4 }] })
+ })
+
+ it('an emptied block leaves no key in the file', () => {
+ const on = setNoAutoMove(empty, 'n', true)
+ expect(on.pullLinks).toEqual({ noAutoMove: ['n'] })
+ expect('pullLinks' in setNoAutoMove(on, 'n', false)).toBe(false)
+ })
+
+ it('pruning a dead card drops its tombstone and opt-out; unchanged returns the same object', () => {
+ const k = setNoAutoMove(unlinkPull(empty, 'dead', 5), 'live', true)
+ expect(prunePullLinks(k, new Set(['live'])).pullLinks).toEqual({ noAutoMove: ['live'] })
+ const settled = prunePullLinks(k, new Set(['live']))
+ expect(prunePullLinks(settled, new Set(['live']))).toBe(settled)
+ expect(pruneAssignments(k, ['live']).pullLinks).toEqual({ noAutoMove: ['live'] })
+ expect(pruneAssignments(settled, ['live'])).toBe(settled)
+ })
+
+ it('survives the card-meta setters, which rebuild meta entries from known fields only', async () => {
+ const { toggleAssignee } = await import('./kanban')
+ const k = toggleAssignee(unlinkPull(empty, 'n', 5), 'n', { name: 'A', color: '#fff' })
+ expect(readPullLinks(k).unlinked).toEqual([{ nodeId: 'n', pull: 5 }])
+ })
+})
+
+describe('the machine-local switch', () => {
+ it('reads hand-edited settings defensively; an entry without a valid arming time is off', () => {
+ expect(sanitizeKanbanPullAutoMove({ projects: {
+ p1: { columnId: 'done', armedAt: 5, seen: { n: { '5': 'open' } } },
+ p2: { columnId: 4, armedAt: 1 },
+ p3: 'no',
+ p4: { columnId: 'done' },
+ p5: { columnId: 'done', armedAt: -1 }
+ } })).toEqual({ projects: { p1: { columnId: 'done', armedAt: 5 } } })
+ expect(sanitizeKanbanPullAutoMove(undefined)).toEqual({ projects: {} })
+ })
+})
diff --cc src/renderer/lib/pullLinks.ts
index 99f3f1844,000000000..56d7dceb4
mode 100644,000000..100644
--- a/src/renderer/lib/pullLinks.ts
+++ b/src/renderer/lib/pullLinks.ts
@@@ -1,64 -1,0 +1,82 @@@
+// Which pull requests belong to which board card — pure, so the card, the card modal and the
+// auto-move all read ONE answer.
+//
+// Two links, both derived from GitHub's own facts rather than guessed from text:
+// - PR → issue: GitHub's `closingIssuesReferences` (a "Closes #N" GitHub will act on at merge).
+// Deliberately NOT unlinkable on the board: GitHub closes the issue on merge whatever the board
+// shows, so hiding the link would only hide what is going to happen. Edit the PR to change it.
+// - PR → session card: the PR's head branch equals the branch of the worktree the card's group is
+// bound to (`data.worktree.branch`, persisted on the group — no git read is needed to know it).
+// A fork's PR never links: 36 of this repository's 50 open PRs come from forks, and a fork's
+// `feat/x` says nothing about this checkout's `feat/x`. The user can remove a link; the
+// tombstone (`ProjectKanban.pullLinks.unlinked`) keeps the auto-link from coming back.
++// - PR → issue → session card: a session started on an issue carries `issueRef`; every PR whose
++// `closingIssuesReferences` name that issue links to the card too. Here a fork's PR DOES count —
++// GitHub's own "Closes #N" is meaningful wherever the PR comes from, unlike a branch name. The
++// host remembers what a PR closed while it was open, so the link survives the merge. The same
++// tombstones apply.
+import type { ProjectKanban } from '@shared/types'
++import type { IssueRef } from '@shared/github-issue-ref'
+import type { GitHubPullBoard, GitHubPullStatus } from '@shared/github-pull-status'
+import { readPullLinks } from '@shared/kanban-pull-links'
+
+const LIFECYCLE_ORDER = { open: 0, draft: 1, merged: 2, closed: 3 } as const
+
+function byRelevance(a: GitHubPullStatus, b: GitHubPullStatus): number {
+ return LIFECYCLE_ORDER[a.lifecycle] - LIFECYCLE_ORDER[b.lifecycle] || b.number - a.number
+}
+
+export interface CardPullLinks {
+ /** PRs whose head is this card's worktree branch, minus the ones the user unlinked. */
+ linked: GitHubPullStatus[]
+ /** Branch matches the user unlinked — offered back as "Link again". */
+ unlinked: GitHubPullStatus[]
+}
+
+const NONE: CardPullLinks = { linked: [], unlinked: [] }
+
++/** The issue a card was started on, when it is in the repository these pull requests belong to —
++ * `closes` numbers mean nothing in any other repository. */
++function sameRepositoryIssue(issueRef: IssueRef | undefined, repository: string | undefined): number | null {
++ if (!issueRef || !repository) return null
++ return `${issueRef.owner}/${issueRef.repo}`.toLocaleLowerCase('en-US') === repository.toLocaleLowerCase('en-US')
++ ? issueRef.number
++ : null
++}
++
+export function pullsForCard(
- card: { id: string; worktreeBranch?: string },
++ card: { id: string; worktreeBranch?: string; issueRef?: IssueRef },
+ pullBoard: GitHubPullBoard | undefined,
+ board: ProjectKanban | undefined
+): CardPullLinks {
- if (!card.worktreeBranch || !pullBoard) return NONE
++ const issue = sameRepositoryIssue(card.issueRef, pullBoard?.repository)
++ if ((!card.worktreeBranch && issue === null) || !pullBoard) return NONE
+ const tombstones = new Set(readPullLinks(board)
+ .unlinked.filter((entry) => entry.nodeId === card.id).map((entry) => entry.pull))
+ const matches = pullBoard.pulls
- .filter((pull) => !pull.crossRepository && pull.headRefName === card.worktreeBranch)
++ .filter((pull) =>
++ (!!card.worktreeBranch && !pull.crossRepository && pull.headRefName === card.worktreeBranch) ||
++ (issue !== null && pull.closes.includes(issue)))
+ .sort(byRelevance)
+ if (!matches.length) return NONE
+ return {
+ linked: matches.filter((pull) => !tombstones.has(pull.number)),
+ unlinked: matches.filter((pull) => tombstones.has(pull.number))
+ }
+}
+
+/** Open pull requests that close this issue when they merge. */
+export function pullsClosingIssue(
+ issueNumber: number,
+ pullBoard: GitHubPullBoard | undefined
+): GitHubPullStatus[] {
+ if (!pullBoard) return []
+ return pullBoard.pulls
+ .filter((pull) => (pull.lifecycle === 'open' || pull.lifecycle === 'draft') &&
+ pull.closes.includes(issueNumber))
+ .sort(byRelevance)
+}
+
+export function pullStatusByNumber(pullBoard: GitHubPullBoard | undefined): Map<number, GitHubPullStatus> {
+ return new Map((pullBoard?.pulls ?? []).map((pull) => [pull.number, pull]))
+}
diff --cc src/shared/github-pull-status.ts
index fa85af400,000000000..356700bd7
mode 100644,000000..100644
--- a/src/shared/github-pull-status.ts
+++ b/src/shared/github-pull-status.ts
@@@ -1,279 -1,0 +1,281 @@@
+// What a pull request's CI and merge state MEAN on the board — one pure place, shared by core (which
+// reads GitHub) and the renderer (which draws it), so the two cannot disagree about a single rule.
+//
+// Every rule here is a bug that has been shipped somewhere before, and the tests pin each one:
+// - a missing check rollup means "no checks", never "passed";
+// - "ready to merge" comes from `mergeStateStatus === 'CLEAN'` alone — `mergeable === 'MERGEABLE'`
+// is also true for a PR that branch protection is still blocking (measured: 2 of 31 MERGEABLE
+// pull requests on this repository were BLOCKED);
+// - a rollup counts only when it was taken at the PR's current head commit;
+// - a failed read keeps the last snapshot and says it is stale, instead of going blank.
+
+/** The PR's checks, summarised. `none` = GitHub reports no rollup at all: the board shows nothing
+ * for CI — not a green tick. */
+export type PullCiState = 'passed' | 'failed' | 'pending' | 'none'
+
+/** Whether the PR can merge. Only `ready` means "ready to merge". */
+export type PullMergeState =
+ | 'ready'
+ | 'conflict'
+ | 'blocked'
+ | 'behind'
+ | 'unstable'
+ | 'hooks'
+ | 'undecided'
+
+/** Where the PR is in its life, as the board needs it. `merged` and `closed` are different facts:
+ * only a merge completes the work. */
+export type PullLifecycle = 'open' | 'draft' | 'merged' | 'closed'
+
+/** GitHub's `StatusState`, the value a commit's check rollup carries. */
+export type GitHubRollupState = 'SUCCESS' | 'FAILURE' | 'ERROR' | 'PENDING' | 'EXPECTED'
+/** GitHub's `MergeableState`. */
+export type GitHubMergeable = 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN'
+
+/** One open PR as GitHub reported it in one read. `rollup` is null when GitHub reports no rollup;
+ * `rollupOid` is the commit that rollup belongs to. `mergeable`/`mergeStateStatus` are null when
+ * the token may not read them (the read is then not an answer about mergeability). */
+export interface PullStatusFacts {
+ number: number
+ headRefName: string
+ headRefOid: string
+ /** The head branch lives in a fork. Its name says nothing about this repository's branches. */
+ crossRepository: boolean
+ isDraft: boolean
+ mergeable: GitHubMergeable | null
+ mergeStateStatus: string | null
+ rollup: GitHubRollupState | null
+ rollupOid: string | null
+ /** Issues in the SAME repository this PR closes on merge (GitHub's own linking). */
+ closes: number[]
+}
+
+/** One PR's state on the board. `ci`/`merge` are ABSENT when unknown — the token cannot read them,
+ * the PR is not open, or the only rollup we have belongs to another commit. Absent renders nothing. */
+export interface GitHubPullStatus {
+ number: number
+ lifecycle: PullLifecycle
+ headRefName: string
+ /** Present (true) when the head branch is in a fork: such a PR never links to a local worktree
+ * branch, however its name matches. */
+ crossRepository?: true
+ /** Open PRs only: the commit the status below was taken at. */
+ headRefOid?: string
+ ci?: PullCiState
+ merge?: PullMergeState
+ /** Open PRs only. */
+ closes: number[]
+ /** This machine has seen the PR open or as a draft (remembered across restarts, per repository). */
+ openSeen?: true
+ /** Epoch ms when this machine first saw the PR merged AFTER having seen it open — an OBSERVED
+ * merge. Absent for a PR that was already merged when this machine first saw it. */
+ mergedSeenAt?: number
+}
+
+/** Everything the board knows about a repository's pull requests beyond the issues harvest. */
+export interface GitHubPullBoard {
++ /** `owner/name` these pull requests belong to (the one `closes` numbers refer to). */
++ repository?: string
+ pulls: GitHubPullStatus[]
+ /** Epoch ms of the last read that succeeded. Absent = none yet in this app run. */
+ observedAt?: number
+ /** The latest read failed: `pulls` is the last snapshot that succeeded, kept on purpose. */
+ stale: boolean
+ /** False = the token may not read checks (ci) / mergeability (merge): hide that region. */
+ access: { ci: boolean; merge: boolean }
+ /** Some open PR is still undecided, so the board should keep chasing while it is visible. */
+ undecided: boolean
+ /** More open PRs exist than one read covers; the oldest-updated ones carry no status. */
+ truncated: boolean
+}
+
+export const EMPTY_PULL_BOARD: GitHubPullBoard = {
+ pulls: [],
+ stale: false,
+ access: { ci: true, merge: true },
+ undecided: false,
+ truncated: false
+}
+
+export function ciState(rollup: GitHubRollupState | null): PullCiState {
+ if (rollup === null) return 'none'
+ if (rollup === 'SUCCESS') return 'passed'
+ if (rollup === 'FAILURE' || rollup === 'ERROR') return 'failed'
+ return 'pending'
+}
+
+/** `mergeStateStatus` decides, except that a conflict reported by `mergeable` is a conflict whatever
+ * the status says, and an unknown `mergeable` is undecided. `MERGEABLE` alone never yields `ready`. */
+export function mergeState(
+ mergeable: GitHubMergeable | null,
+ mergeStateStatus: string | null
+): PullMergeState | undefined {
+ if (mergeable === null || mergeStateStatus === null) return undefined
+ if (mergeable === 'CONFLICTING') return 'conflict'
+ if (mergeable === 'UNKNOWN') return 'undecided'
+ switch (mergeStateStatus) {
+ case 'CLEAN': return 'ready'
+ case 'DIRTY': return 'conflict'
+ case 'BLOCKED': return 'blocked'
+ case 'BEHIND': return 'behind'
+ case 'UNSTABLE': return 'unstable'
+ case 'HAS_HOOKS': return 'hooks'
+ case 'UNKNOWN': return 'undecided'
+ // A value GitHub adds later is not a reason to claim anything, and not a reason to chase.
+ default: return undefined
+ }
+}
+
+/** GitHub is still working something out for this PR, so re-reading soon will likely change it. */
+export function isUndecided(status: Pick<GitHubPullStatus, 'lifecycle' | 'ci' | 'merge'>): boolean {
+ if (status.lifecycle !== 'open' && status.lifecycle !== 'draft') return false
+ return status.merge === 'undecided' || status.ci === 'pending'
+}
+
+/**
+ * The board status for one open PR, from one read plus the previous status for the same PR.
+ *
+ * The rollup counts only when it belongs to the head commit. When this read's rollup is for another
+ * commit (a read that raced a push), the previous CI is kept ONLY if it was taken at this same head;
+ * a CI result from an older head is never carried onto a newer one.
+ */
+export function pullStatusFrom(
+ facts: PullStatusFacts,
+ access: { ci: boolean; merge: boolean },
+ previous?: GitHubPullStatus
+): GitHubPullStatus {
+ const lifecycle: PullLifecycle = facts.isDraft ? 'draft' : 'open'
+ let ci: PullCiState | undefined
+ if (access.ci) {
+ if (facts.rollup === null) ci = 'none'
+ else if (facts.rollupOid === facts.headRefOid) ci = ciState(facts.rollup)
+ else if (previous?.headRefOid === facts.headRefOid && previous.ci !== undefined) ci = previous.ci
+ // The only rollup we have is for another commit. Reading again will settle it.
+ else ci = 'pending'
+ }
+ const merge = access.merge ? mergeState(facts.mergeable, facts.mergeStateStatus) : undefined
+ return {
+ number: facts.number,
+ lifecycle,
+ headRefName: facts.headRefName,
+ ...(facts.crossRepository ? { crossRepository: true as const } : {}),
+ headRefOid: facts.headRefOid,
+ ...(ci !== undefined ? { ci } : {}),
+ ...(merge !== undefined ? { merge } : {}),
+ closes: facts.closes
+ }
+}
+
+/** A key per undecided PR AT ITS HEAD: a push to a stuck PR starts a new chase, while the same stuck
+ * PR read again does not restart the count. */
+export function undecidedKeys(pulls: GitHubPullStatus[]): string[] {
+ return pulls.filter(isUndecided).map((pull) => `${pull.number}@${pull.headRefOid ?? ''}`).sort()
+}
+
+// ── Chase: re-read an undecided PR without webhooks ─────────────────────────────────────────────
+
+/** Nothing can call us when GitHub finishes computing, so an undecided PR is re-read on this
+ * schedule — 30 s, 1 min, 2 min, then every 5 min — and at most this many times per episode. The
+ * first step is 30 s because a first read is what starts GitHub's mergeability computation: on this
+ * repository 40 of 50 open PRs read UNKNOWN, and every one had settled 20 s later. */
+export const PULL_CHASE_DELAYS_MS = [30_000, 60_000, 120_000, 300_000] as const
+export const PULL_CHASE_MAX = 12
+
+export function pullChaseDelay(attempt: number): number {
+ return PULL_CHASE_DELAYS_MS[Math.min(attempt, PULL_CHASE_DELAYS_MS.length - 1)]
+}
+
+export interface PullChaseState {
+ /** `undecidedKeys` of the episode being chased. */
+ keys: string[]
+ /** Chase reads spent in this episode. */
+ attempts: number
+ /** When the last read (of any kind) finished. */
+ lastReadAt: number
+}
+
+/** The chase after a read that SUCCEEDED. A new undecided PR (or a new head) starts a new episode;
+ * the same undecided set keeps counting; nothing undecided ends the chase. */
+export function nextPullChase(
+ previous: PullChaseState | null,
+ pulls: GitHubPullStatus[],
+ now: number
+): PullChaseState | null {
+ const keys = undecidedKeys(pulls)
+ if (keys.length === 0) return null
+ const known = new Set(previous?.keys ?? [])
+ const fresh = !previous || keys.some((key) => !known.has(key))
+ return { keys, attempts: fresh ? 0 : previous.attempts, lastReadAt: now }
+}
+
+/** Is a chase read due? Never past `PULL_CHASE_MAX`, never before the schedule allows. */
+export function pullChaseDue(chase: PullChaseState | null, now: number): boolean {
+ if (!chase || chase.attempts >= PULL_CHASE_MAX) return false
+ return now - chase.lastReadAt >= pullChaseDelay(chase.attempts)
+}
+
+// ── Freshness ───────────────────────────────────────────────────────────────────────────────────
+
+/** A stale snapshot is shown as-is (marked stale) until it is this old, then greyed. */
+export const PULL_STATUS_GREY_AFTER_MS = 15 * 60_000
+
+export type PullStatusFreshness = 'fresh' | 'stale' | 'expired'
+
+export function pullStatusFreshness(
+ board: Pick<GitHubPullBoard, 'stale' | 'observedAt'>,
+ now: number
+): PullStatusFreshness {
+ if (!board.stale) return 'fresh'
+ if (board.observedAt === undefined || now - board.observedAt >= PULL_STATUS_GREY_AFTER_MS) {
+ return 'expired'
+ }
+ return 'stale'
+}
+
+// ── Per-check detail (fetched only when a PR's modal opens) ─────────────────────────────────────
+
+export type PullCheckState = 'passed' | 'failed' | 'pending' | 'skipped' | 'neutral'
+
+export interface GitHubPullCheck {
+ name: string
+ state: PullCheckState
+ /** https only; absent when GitHub gave none or it was not an https URL. */
+ url?: string
+}
+
+export type GitHubPullChecksResult =
+ | { status: 'ok'; headRefOid: string; checks: GitHubPullCheck[]; truncated: boolean }
+ /** GitHub reports no rollup for the head commit: there are no checks to show. */
+ | { status: 'no-checks' }
+ /** The token may not read checks. Nothing is shown. */
+ | { status: 'hidden' }
+ /** The read raced a push: the checks belong to another commit. */
+ | { status: 'moved' }
+ | { status: 'unavailable' }
+
+const CHECK_ORDER: Record<PullCheckState, number> = {
+ failed: 0, pending: 1, passed: 2, neutral: 3, skipped: 4
+}
+
+/** Failures first, then what is still running: the order someone opening a red PR reads in. */
+export function sortChecks(checks: GitHubPullCheck[]): GitHubPullCheck[] {
+ return [...checks].sort((a, b) =>
+ CHECK_ORDER[a.state] - CHECK_ORDER[b.state] || a.name.localeCompare(b.name))
+}
+
+/** A check run's `status` + `conclusion`, or a commit status context's `state`, as one of ours. */
+export function checkRunState(status: string, conclusion: string | null): PullCheckState {
+ if (status !== 'COMPLETED') return 'pending'
+ switch (conclusion) {
+ case 'SUCCESS': return 'passed'
+ case 'SKIPPED': return 'skipped'
+ case 'NEUTRAL': return 'neutral'
+ default: return 'failed'
+ }
+}
+
+export function statusContextState(state: string): PullCheckState {
+ if (state === 'SUCCESS') return 'passed'
+ if (state === 'PENDING' || state === 'EXPECTED') return 'pending'
+ return 'failed'
+}
diff --cc src/shared/types.ts
index 865b9d3fd,09445e43c..24619458f
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@@ -729,11 -734,26 +738,27 @@@ export interface BoardLogEvent
* agent node so it files under that agent's card. Written BEFORE the read (fail-closed): a cookie
* read that happened but was not recorded is the one outcome this trace exists to prevent. */
| 'agent-read-cookies'
+ /** An agent session was started on a GitHub issue. Filed under the issue CARD's board-log
+ * identity (`issueLogId`), not the node's, so the issue keeps its run history after the
+ * session's node is gone. `run` names the session; `title` is the node title at the time. */
+ | 'run-started'
+ /** That session's node was closed. `run.end` is the last agent state observed at that
+ * moment — a turn ending (`done`) is NOT a run ending, which is why this is written only when
+ * the node goes. */
+ | 'run-ended'
from?: string
to?: string
- /** Column title for column-added/deleted; card title for card-created; outcome for agent-message. */
+ /** Column title for column-added/deleted; card title for card-created; outcome for agent-message;
+ * for card-moved, the reason when the board moved the card itself ("PR #12 merged"). */
title?: string
+ /** run-started / run-ended only. No cost or token figure: nodeterm has no cumulative number for
+ * a session, and a context-window reading is not one. */
+ run?: {
+ nodeId: string
+ agentId?: string
+ sessionId?: string
+ end?: 'done' | 'working' | 'waiting' | 'blocked' | 'errored' | 'dropped' | 'unknown'
+ }
}
/** One line of the append-only board history (`.nodeterm/board-log.jsonl`). A `comment`