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.

fix(kanban): a card moves only if IT waited on the PR; no branch links on SSH

reviewbce6910751a8
diff --git a/CLAUDE.md b/CLAUDE.md
index a0dba7d69..46fc757a4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5361,7 +5361,10 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
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
+ (`access`), which is not the same as a null rollup. Enum values (`mergeable`, rollup `state`,
+ `mergeStateStatus`) decode LENIENTLY: a value GitHub adds later claims nothing and is not chased,
+ and an unrecognised rollup state is `UNRECOGNIZED`, never `null` ("no checks") — one new value
+ must not fail every read of the repository (it happened with `state_reason: duplicate`). **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
@@ -5373,8 +5376,9 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
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). PR → issue → session card: a session started on an issue (`data.issueRef`, below) links to
+ next member/due/label edit. On an SSH project NO card carries a worktree branch
+ (`kanbanSessionsFrom` leaves it off where the cards are built), so the card face, the move and
+ the modal — which states the worktree reason — cannot disagree. 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
@@ -5398,10 +5402,17 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
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
+ `mergedSeenAt >= armedAt` → no move (arming never sweeps old merges; `armedAt` is taken from the
+ HOST's clock via the pull board's `now`, because `mergedSeenAt` is stamped there and a Server
+ Edition browser's clock can be off). 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. **The claim is refused unless THIS card was noted waiting on one of those PRs while it
+ was open** (`githubIssues:note-pull-waits`; the host records a note only for a PR it holds as open
+ itself): `mergedSeenAt` is a fact about the PR, and without the per-card note a card that first
+ appeared after the merge — a follow-up terminal in the same group, a teammate's card by git pull,
+ an issue-bound session started later — would win a fresh claim and jump to Done. It is then
+ 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
diff --git a/src/core/github/graphql-pulls.test.ts b/src/core/github/graphql-pulls.test.ts
index f7269df13..126fd701d 100644
--- a/src/core/github/graphql-pulls.test.ts
+++ b/src/core/github/graphql-pulls.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { GitHubIssuesClient, GitHubClientError } from './client'
+import { pullStatusFrom } from '../../shared/github-pull-status'
import {
GraphQLShapeError,
PULL_STATUS_QUERY,
@@ -120,11 +121,22 @@ describe('parsePullStatusResponse', () => {
it('rejects malformed nodes', () => {
expect(() => parsePullStatusResponse(body([node(1, { headRefOid: 'nothex' })]), REPO)).toThrow()
- expect(() => parsePullStatusResponse(body([node(1, { mergeable: 'MAYBE' })]), REPO)).toThrow()
+ expect(() => parsePullStatusResponse(body([node(1, { mergeable: 7 })]), REPO)).toThrow()
expect(() => parsePullStatusResponse(body([node(1, {
- commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: { state: 'GREEN' } } }] }
+ commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: { state: 'not an enum' } } }] }
})]), REPO)).toThrow()
})
+
+ it('an enum value GitHub adds later claims nothing instead of failing the read', () => {
+ const read = parsePullStatusResponse(body([node(1, {
+ mergeable: 'SOMETIMES',
+ commits: { nodes: [{ commit: { oid: HEAD, statusCheckRollup: { state: 'NEW_STATE' } } }] }
+ })]), REPO)
+ expect(read.open[0]).toMatchObject({ mergeable: null, rollup: 'UNRECOGNIZED' })
+ const status = pullStatusFrom(read.open[0], read.access)
+ expect(status.ci).toBeUndefined()
+ expect(status.merge).toBeUndefined()
+ })
})
describe('parsePullChecksResponse', () => {
diff --git a/src/core/github/graphql-pulls.ts b/src/core/github/graphql-pulls.ts
index 70a2c4577..5434528cf 100644
--- a/src/core/github/graphql-pulls.ts
+++ b/src/core/github/graphql-pulls.ts
@@ -188,15 +188,18 @@ export function parsePullStatusResponse(body: unknown, repository: string): Pull
let mergeable: GitHubMergeable | null = null
let mergeStateStatus: string | null = null
if (access.merge) {
- if (node.mergeable !== 'MERGEABLE' && node.mergeable !== 'CONFLICTING' &&
- node.mergeable !== 'UNKNOWN') throw new GraphQLShapeError()
- if (typeof node.mergeStateStatus !== 'string' || !/^[A-Z_]{1,32}$/.test(node.mergeStateStatus)) {
+ // Enum values are decoded LENIENTLY: GitHub adds values (it added `duplicate` to state_reason),
+ // and a value this build does not know must claim nothing — not fail every read of the repo.
+ // A value that is not even an enum-shaped string is still a malformed answer.
+ if (typeof node.mergeable !== 'string' || !/^[A-Z_]{1,32}$/.test(node.mergeable) ||
+ typeof node.mergeStateStatus !== 'string' || !/^[A-Z_]{1,32}$/.test(node.mergeStateStatus)) {
throw new GraphQLShapeError()
}
- mergeable = node.mergeable
+ mergeable = node.mergeable === 'MERGEABLE' || node.mergeable === 'CONFLICTING' ||
+ node.mergeable === 'UNKNOWN' ? node.mergeable : null
mergeStateStatus = node.mergeStateStatus
}
- let rollup: GitHubRollupState | null = null
+ let rollup: GitHubRollupState | 'UNRECOGNIZED' | null = null
let rollupOid: string | null = null
if (access.ci) {
const commits = list(node.commits, 1)
@@ -207,9 +210,9 @@ export function parsePullStatusResponse(body: unknown, repository: string): Pull
rollupOid = commit.oid
if (commit.statusCheckRollup !== null) {
const state = object(commit.statusCheckRollup)?.state
- if (state !== 'SUCCESS' && state !== 'FAILURE' && state !== 'ERROR' && state !== 'PENDING' &&
- state !== 'EXPECTED') throw new GraphQLShapeError()
- rollup = state
+ if (typeof state !== 'string' || !/^[A-Z_]{1,32}$/.test(state)) throw new GraphQLShapeError()
+ rollup = state === 'SUCCESS' || state === 'FAILURE' || state === 'ERROR' || state === 'PENDING' ||
+ state === 'EXPECTED' ? state : 'UNRECOGNIZED'
}
}
}
diff --git a/src/core/github/handlers.test.ts b/src/core/github/handlers.test.ts
index d301abc20..3a979a0b5 100644
--- a/src/core/github/handlers.test.ts
+++ b/src/core/github/handlers.test.ts
@@ -27,7 +27,8 @@ describe('registerGitHubIssueHandlers', () => {
pullChecks: async (...args: unknown[]) => {
calls.push(['checks', ...args]); return { status: 'no-checks' as const }
},
- claimPullAutoMove: async (...args: unknown[]) => { calls.push(['claim', ...args]); return true }
+ claimPullAutoMove: async (...args: unknown[]) => { calls.push(['claim', ...args]); return true },
+ notePullWaits: async (...args: unknown[]) => { calls.push(['wait', ...args]); return 1 }
}
const platform = fakePlatform()
registerGitHubIssueHandlers(platform, service)
@@ -39,6 +40,7 @@ describe('registerGitHubIssueHandlers', () => {
await platform.handlers[IPC.githubIssuesChasePulls]('p1')
await platform.handlers[IPC.githubIssuesPullChecks]('p1', 12)
await platform.handlers[IPC.githubIssuesClaimPullAutoMove]({ projectId: 'p1', cardId: 'n', pulls: [3] })
+ await platform.handlers[IPC.githubIssuesNotePullWaits]({ projectId: 'p1', cardId: 'n', pulls: [3] })
expect(calls).toEqual([
['subscribe', 7, { projectId: 'p1' }],
['unsubscribe', 7, 'p1'],
@@ -46,7 +48,8 @@ describe('registerGitHubIssueHandlers', () => {
['pullStatus', { projectId: 'p1' }],
['chase', { projectId: 'p1' }],
['checks', { projectId: 'p1', pullNumber: 12 }],
- ['claim', { projectId: 'p1', cardId: 'n', pulls: [3] }]
+ ['claim', { projectId: 'p1', cardId: 'n', pulls: [3] }],
+ ['wait', { projectId: 'p1', cardId: 'n', pulls: [3] }]
])
expect(Object.keys(platform.handlers).some((channel) => channel.startsWith('githubControl:'))).toBe(false)
})
diff --git a/src/core/github/handlers.ts b/src/core/github/handlers.ts
index 338a67942..6c3165591 100644
--- a/src/core/github/handlers.ts
+++ b/src/core/github/handlers.ts
@@ -27,6 +27,7 @@ export interface GitHubIssueHandlerService {
chasePulls(request: { projectId: string }): Promise<boolean>
pullChecks(request: { projectId: string; pullNumber: number }): Promise<GitHubPullChecksResult>
claimPullAutoMove(request: { projectId: string; cardId: string; pulls: number[] }): Promise<boolean>
+ notePullWaits(request: { projectId: string; cardId: string; pulls: number[] }): Promise<number>
}
export function registerGitHubIssueHandlers(
@@ -53,4 +54,6 @@ export function registerGitHubIssueHandlers(
service.pullChecks({ projectId, pullNumber }))
platform.handle(IPC.githubIssuesClaimPullAutoMove,
(request: { projectId: string; cardId: string; pulls: number[] }) => service.claimPullAutoMove(request))
+ platform.handle(IPC.githubIssuesNotePullWaits,
+ (request: { projectId: string; cardId: string; pulls: number[] }) => service.notePullWaits(request))
}
diff --git a/src/core/github/pull-memory.test.ts b/src/core/github/pull-memory.test.ts
index 788138bb6..013674c53 100644
--- a/src/core/github/pull-memory.test.ts
+++ b/src/core/github/pull-memory.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import type { GitHubPullStatus, PullLifecycle } from '../../shared/github-pull-status'
import {
PULL_MEMORY_MAX,
+ noteWaitsInMemory,
REMEMBERED_MERGE_VISIBLE_MS,
claimInMemory,
emptyPullMemory,
@@ -52,7 +53,7 @@ describe('rememberPulls', () => {
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)
+ expect(validPullMemory({ version: 1, pulls: kept, claims: [], waits: [] })).toBe(true)
})
})
@@ -72,17 +73,21 @@ describe('rememberedForBoard', () => {
})
describe('claims', () => {
- it('the first claim for a key wins', () => {
- const first = claimInMemory(emptyPullMemory(), 'p|n|1')
+ it('the first claim for a key wins — and only for a card noted waiting on one of its PRs', () => {
+ const noted = noteWaitsInMemory(emptyPullMemory(), ['wait|n|1'])
+ expect(claimInMemory(emptyPullMemory(), 'p|n|1', ['wait|n|1']).claimed).toBe(false)
+ const first = claimInMemory(noted, 'p|n|1', ['wait|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)
+ expect(claimInMemory(first.memory, 'p|n|1', ['wait|n|1']).claimed).toBe(false)
+ expect(claimInMemory(first.memory, 'p|n|1,2', ['wait|n|1', 'wait|n|2']).claimed).toBe(true)
+ expect(noteWaitsInMemory(noted, ['wait|n|1'])).toBe(noted)
})
it('rejects a malformed memory file', () => {
- expect(validPullMemory({ version: 1, pulls: [{ number: -1, headRefName: 'x', lifecycle: 'open' }], claims: [] }))
+ expect(validPullMemory({ version: 1, pulls: [{ number: -1, headRefName: 'x', lifecycle: 'open' }], claims: [], waits: [] }))
.toBe(false)
- expect(validPullMemory({ version: 2, pulls: [], claims: [] })).toBe(false)
- expect(validPullMemory({ version: 1, pulls: [], claims: [3] })).toBe(false)
+ expect(validPullMemory({ version: 2, pulls: [], claims: [], waits: [] })).toBe(false)
+ expect(validPullMemory({ version: 1, pulls: [], claims: [3], waits: [] })).toBe(false)
+ expect(validPullMemory({ version: 1, pulls: [], claims: [] })).toBe(false)
})
})
diff --git a/src/core/github/pull-memory.ts b/src/core/github/pull-memory.ts
index 52b38d3ae..cbf36624e 100644
--- a/src/core/github/pull-memory.ts
+++ b/src/core/github/pull-memory.ts
@@ -16,6 +16,12 @@
// 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.
+//
+// And WAIT NOTES: "card X was linked to PR #N while #N was still open". `mergedSeenAt` is a fact
+// about a PR, not about a card, so on its own it would let a card that first appeared AFTER the
+// merge (a follow-up terminal in the same worktree group, a teammate's card arriving by git pull)
+// win a fresh claim and jump to Done. A claim is only granted for a card that has a wait note for
+// one of the PRs it claims — the transition was observed for THIS card.
import type { GitHubPullStatus, PullLifecycle } from '../../shared/github-pull-status'
export interface RememberedPull {
@@ -34,16 +40,27 @@ export interface PullMemory {
version: 1
pulls: RememberedPull[]
claims: string[]
+ waits: string[]
}
export const PULL_MEMORY_MAX = 500
export const PULL_CLAIMS_MAX = 2_000
+export const PULL_WAITS_MAX = 4_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: [] }
+ return { version: 1, pulls: [], claims: [], waits: [] }
+}
+
+/** The memory keys. `\0` cannot occur in a project id, a card id (both validated) or a number. */
+export function claimKey(projectId: string, cardId: string, pulls: number[]): string {
+ return `${projectId}\0${cardId}\0${[...new Set(pulls)].sort((a, b) => a - b).join(',')}`
+}
+
+export function waitKey(projectId: string, cardId: string, pull: number): string {
+ return `wait\0${projectId}\0${cardId}\0${pull}`
}
const LIFECYCLES = new Set<PullLifecycle>(['open', 'draft', 'merged', 'closed'])
@@ -67,7 +84,9 @@ export function validPullMemory(value: unknown): value is 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)
+ memory.claims.every((claim) => typeof claim === 'string' && claim.length <= 1_024) &&
+ Array.isArray(memory.waits) && memory.waits.length <= PULL_WAITS_MAX &&
+ memory.waits.every((wait) => typeof wait === 'string' && wait.length <= 1_024)
}
const UNFINISHED = new Set<PullLifecycle>(['open', 'draft'])
@@ -154,8 +173,23 @@ export function withObservations(status: GitHubPullStatus, remembered: Remembere
}
}
-/** Records a claim; `claimed` is false when it was already there. */
-export function claimInMemory(memory: PullMemory, key: string): { memory: PullMemory; claimed: boolean } {
+/** Records a claim; `claimed` is false when it was already there, or when none of `waitKeys` was
+ * ever noted (the card was never seen waiting on one of these PRs while it was open). */
+export function claimInMemory(
+ memory: PullMemory,
+ key: string,
+ waitKeys: string[]
+): { memory: PullMemory; claimed: boolean } {
if (memory.claims.includes(key)) return { memory, claimed: false }
+ const noted = new Set(memory.waits)
+ if (!waitKeys.some((wait) => noted.has(wait))) return { memory, claimed: false }
return { memory: { ...memory, claims: [...memory.claims, key].slice(-PULL_CLAIMS_MAX) }, claimed: true }
}
+
+/** Records wait notes; the same memory object back when every one was already there. */
+export function noteWaitsInMemory(memory: PullMemory, keys: string[]): PullMemory {
+ const known = new Set(memory.waits)
+ const fresh = keys.filter((key) => !known.has(key))
+ if (!fresh.length) return memory
+ return { ...memory, waits: [...memory.waits, ...fresh].slice(-PULL_WAITS_MAX) }
+}
diff --git a/src/core/github/pull-status-tracker.test.ts b/src/core/github/pull-status-tracker.test.ts
index 7496f00b6..aeda0a971 100644
--- a/src/core/github/pull-status-tracker.test.ts
+++ b/src/core/github/pull-status-tracker.test.ts
@@ -213,33 +213,63 @@ describe('GitHubPullStatusTracker', () => {
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')])
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1), facts(2)]))
+ expect(await subject.noteWaits(KEY, 'p', 'n', [1, 2])).toBe(2)
+ const answers = await Promise.all([subject.claimMove(KEY, 'p', 'n', [1]), subject.claimMove(KEY, 'p', 'n', [1])])
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)
+ expect(await restarted.subject.claimMove(KEY, 'p', 'n', [1])).toBe(false)
+ expect(await restarted.subject.claimMove(KEY, 'p', 'n', [2])).toBe(true)
+ })
+
+ it('a card that first appears after the merge never wins a claim', async () => {
+ const { subject } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(12, { headRefName: 'feat/x' })]))
+ expect(await subject.noteWaits(KEY, 'p', 'first-card', [12])).toBe(1)
+ await subject.read(KEY, 'user-1', 'foreground', async () => read([], {
+ recent: [{ number: 12, headRefName: 'feat/x', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ // The card that was there while #12 was open moves; one that appears only now (a follow-up
+ // terminal in the same worktree group, a teammate's card via git pull) never does.
+ expect(await subject.claimMove(KEY, 'p', 'first-card', [12])).toBe(true)
+ expect(await subject.noteWaits(KEY, 'p', 'late-card', [12])).toBe(0)
+ expect(await subject.claimMove(KEY, 'p', 'late-card', [12])).toBe(false)
+ })
+
+ it('notes a wait only for a PR the host itself holds as open', async () => {
+ const { subject } = tracker()
+ expect(await subject.noteWaits(KEY, 'p', 'n', [1])).toBe(0)
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1)], {
+ recent: [{ number: 2, headRefName: 'x', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ expect(await subject.noteWaits(KEY, 'p', 'n', [1, 2, 3])).toBe(1)
+ expect(await subject.claimMove(KEY, 'p', 'n', [2])).toBe(false)
})
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 })
+ let releaseSlow!: () => void
+ const slowSave = new Promise<void>((resolve) => { releaseSlow = resolve })
+ let slow = false
const save = store.save
let calls = 0
store.save = async (...args) => {
calls += 1
- if (calls === 1) await firstSave
+ if (slow) await slowSave
return save(...args)
}
const { subject } = tracker(0, store)
- expect(await subject.claim(KEY, 'one')).toBe(true)
- expect(await subject.claim(KEY, 'two')).toBe(true)
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1), facts(2)]))
+ await settleSaves()
+ calls = 0
+ slow = true
+ await subject.noteWaits(KEY, 'p', 'n', [1, 2]) // save #1 starts and hangs
+ expect(await subject.claimMove(KEY, 'p', 'n', [1])).toBe(true) // save #2 queues behind it
const forgotten = subject.forgetRepository('o/r')
- releaseFirst()
+ releaseSlow()
await forgotten
expect(calls).toBe(1)
- expect(store.saves).toHaveLength(1)
})
it('nothing started before a cache clear writes the memory back', async () => {
diff --git a/src/core/github/pull-status-tracker.ts b/src/core/github/pull-status-tracker.ts
index 142b3fd23..2bea02134 100644
--- a/src/core/github/pull-status-tracker.ts
+++ b/src/core/github/pull-status-tracker.ts
@@ -30,8 +30,11 @@ import {
import type { PullStatusRead } from './graphql-pulls'
import {
claimInMemory,
+ claimKey,
emptyPullMemory,
+ noteWaitsInMemory,
rememberPulls,
+ waitKey,
rememberedForBoard,
withObservations,
type PullMemory
@@ -96,9 +99,13 @@ export class GitHubPullStatusTracker {
board(key: string): GitHubPullBoard {
const state = this.states.get(key)
const repository = splitKey(key)[1]
- if (!state) return { ...EMPTY_PULL_BOARD, access: { ...EMPTY_PULL_BOARD.access }, repository }
+ // The host's clock, so a renderer can record when it armed the move in the same clock the host
+ // stamps `mergedSeenAt` with (a Server Edition browser's clock may be minutes off).
+ const now = this.now()
+ if (!state) return { ...EMPTY_PULL_BOARD, access: { ...EMPTY_PULL_BOARD.access }, repository, now }
return {
repository,
+ now,
pulls: state.pulls.map((pull) => ({ ...pull, closes: [...pull.closes] })),
...(state.observedAt !== undefined ? { observedAt: state.observedAt } : {}),
stale: state.stale,
@@ -132,20 +139,48 @@ export class GitHubPullStatusTracker {
/**
* 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.
+ * moved again for the same merges. Refused unless this card was noted WAITING on one of those PRs
+ * while it was open (`noteWaits`): a card that first appeared after the merge never moves.
*/
- async claim(key: string, claimKey: string): Promise<boolean> {
+ async claimMove(key: string, projectId: string, cardId: string, pulls: number[]): 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)
+ const { memory: next, claimed } = claimInMemory(
+ state.memory ?? memory,
+ claimKey(projectId, cardId, pulls),
+ pulls.map((pull) => waitKey(projectId, cardId, pull))
+ )
if (!claimed) return false
state.memory = next
this.persist(key, state)
return true
}
+ /**
+ * "This card is linked to these PRs, and they are still open." Recorded only for PRs the host
+ * itself currently holds as open or a draft — the note is the evidence a later claim rests on, so
+ * the host does not take the caller's word for the state. Returns how many notes were new.
+ */
+ async noteWaits(key: string, projectId: string, cardId: string, pulls: number[]): Promise<number> {
+ const state = this.states.get(key)
+ if (!state) return 0
+ const generation = state.generation
+ const memory = await this.memoryFor(key, state)
+ if (generation !== state.generation) return 0
+ const open = new Set(state.pulls
+ .filter((pull) => pull.lifecycle === 'open' || pull.lifecycle === 'draft')
+ .map((pull) => pull.number))
+ const keys = pulls.filter((pull) => open.has(pull)).map((pull) => waitKey(projectId, cardId, pull))
+ const current = state.memory ?? memory
+ const next = noteWaitsInMemory(current, keys)
+ if (next === current) return 0
+ state.memory = next
+ this.persist(key, state)
+ return next.waits.length - current.waits.length
+ }
+
/**
* 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
diff --git a/src/core/github/service.pulls.test.ts b/src/core/github/service.pulls.test.ts
index f3b89fa9f..5769f31fd 100644
--- a/src/core/github/service.pulls.test.ts
+++ b/src/core/github/service.pulls.test.ts
@@ -222,9 +222,14 @@ describe('GitHubIssueService pull status', () => {
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))
+ // No card was seen waiting on #1 yet: nothing may move.
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [1] })).toBe(false)
+ expect(await h.service.notePullWaits({ projectId: 'project-1', cardId: 'n', pulls: [1] })).toBe(1)
+ expect(await h.service.notePullWaits({ projectId: 'project-1', cardId: 'other', pulls: [1] })).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)
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'never-waited', pulls: [1] })).toBe(false)
for (const bad of [
{ projectId: 'project-1', cardId: '', pulls: [1] },
{ projectId: 'project-1', cardId: 'x'.repeat(300), pulls: [1] },
@@ -234,6 +239,7 @@ describe('GitHubIssueService pull status', () => {
null
]) {
expect(await h.service.claimPullAutoMove(bad as never)).toBe(false)
+ expect(await h.service.notePullWaits(bad as never)).toBe(0)
}
})
})
diff --git a/src/core/github/service.ts b/src/core/github/service.ts
index 2392301e7..50598727e 100644
--- a/src/core/github/service.ts
+++ b/src/core/github/service.ts
@@ -738,15 +738,35 @@ export class GitHubIssueService {
* request and resolves no credential.
*/
async claimPullAutoMove(request: { projectId: string; cardId: string; pulls: number[] }): Promise<boolean> {
+ const key = this.validPullCardRequest(request)
+ if (!key) return false
+ const { projectId, cardId, pulls } = request
+ return this.pulls.claimMove(key, projectId, cardId, pulls)
+ }
+
+ /**
+ * A visible, armed board reports "this card is waiting on these still-open PRs". The host keeps a
+ * note only for PRs it holds as open itself; `claimPullAutoMove` later requires one. Sends no
+ * request and resolves no credential.
+ */
+ async notePullWaits(request: { projectId: string; cardId: string; pulls: number[] }): Promise<number> {
+ const key = this.validPullCardRequest(request)
+ if (!key) return 0
+ return this.pulls.noteWaits(key, request.projectId, request.cardId, request.pulls)
+ }
+
+ /** The repository key for a well-formed card request on a bound project that is not being cleared. */
+ private validPullCardRequest(
+ request: { projectId: string; cardId: string; pulls: number[] } | null | undefined
+ ): string | null {
const { projectId, cardId, pulls } = request ?? {}
if (typeof projectId !== 'string' || typeof cardId !== 'string' || !cardId || cardId.length > 256 ||
/[\u0000-\u001f]/.test(cardId) || !Array.isArray(pulls) || pulls.length === 0 || pulls.length > 100 ||
- pulls.some((pull) => !Number.isSafeInteger(pull) || pull < 1)) return false
+ pulls.some((pull) => !Number.isSafeInteger(pull) || pull < 1)) return null
const key = this.projectKeys.get(projectId)
- if (!key || key.startsWith('unbound:')) return false
- if (this.repositoryControl(key.slice(key.indexOf('\0') + 1)).deletion) return false
- const numbers = [...new Set(pulls)].sort((a, b) => a - b).join(',')
- return this.pulls.claim(key, `${projectId}\0${cardId}\0${numbers}`)
+ if (!key || key.startsWith('unbound:')) return null
+ if (this.repositoryControl(key.slice(key.indexOf('\0') + 1)).deletion) return null
+ return key
}
/** Per-check detail for one PR, read when its modal opens. Never throws: every failure is one of
diff --git a/src/main/remote/relay-project-scope.ts b/src/main/remote/relay-project-scope.ts
index e54828e99..63f81ce76 100644
--- a/src/main/remote/relay-project-scope.ts
+++ b/src/main/remote/relay-project-scope.ts
@@ -49,6 +49,7 @@ const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {
[IPC.githubIssuesChasePulls]: fromFirstArg,
[IPC.githubIssuesPullChecks]: fromFirstArg,
[IPC.githubIssuesClaimPullAutoMove]: fromFirstArgField,
+ [IPC.githubIssuesNotePullWaits]: fromFirstArgField,
[IPC.boardLogAppend]: fromFirstArg,
[IPC.boardLogRead]: fromFirstArg,
[IPC.boardLogSubscribe]: fromFirstArg,
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 53d00f0a9..47b648461 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -233,6 +233,7 @@ const api: NodeTerminalApi = {
pullChecks: (projectId, pullNumber) =>
ipcRenderer.invoke(IPC.githubIssuesPullChecks, projectId, pullNumber),
claimPullAutoMove: (request) => ipcRenderer.invoke(IPC.githubIssuesClaimPullAutoMove, request),
+ notePullWaits: (request) => ipcRenderer.invoke(IPC.githubIssuesNotePullWaits, request),
projectAvatar: (projectId) => ipcRenderer.invoke(IPC.githubProjectAvatar, projectId),
onChanged: (projectId, listener) => {
const channel = IPC.githubIssuesChanged(projectId)
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 7e08c53bf..dda570718 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -464,6 +464,8 @@ export function buildGitHubApi(
>,
claimPullAutoMove: (request) =>
client.request(IPC.githubIssuesClaimPullAutoMove, request) as Promise<boolean>,
+ notePullWaits: (request) =>
+ client.request(IPC.githubIssuesNotePullWaits, request) as Promise<number>,
projectAvatar: (projectId) =>
client.request(IPC.githubProjectAvatar, projectId) as ReturnType<
GitHubIssuesApi['projectAvatar']
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index b2658c33d..9cb4bc57e 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -680,7 +680,7 @@ import {
} from './claude-account-switch'
import type { CodexAccount } from '@shared/codex-account'
import { useSystemCodexAccount } from '../state/systemCodexAccount'
-import { toKanbanSession, worktreeBranchOf } from './toKanbanSession'
+import { kanbanSessionsFrom, toKanbanSession } from './toKanbanSession'
import { applyPullAutoMove } from '../lib/pullAutoMove'
import { useWallpaperBackground, wallpaperLayers } from '../state/wallpaper'
import { showCanvasDots } from '../lib/canvasDots'
@@ -9745,18 +9745,14 @@ export function Canvas() {
// board's own consumer is rendered under the same `kanbanOpen` flag, and the board-log's
// `cardTitle` reads the nodes directly (see onKanbanChange), so nothing else depends on this
// list existing while the canvas is what you are looking at.
- const kanbanSessions = useMemo(() => {
- if (!perProjectKanbanOpen) return NO_KANBAN_SESSIONS
- // The worktree branch a card works on comes from its enclosing bound group — the link a pull
- // request's head branch is matched against (lib/pullLinks.ts).
- const byId = new Map(nodes.map((n) => [n.id, n]))
- return nodes.flatMap((n): KanbanSession[] => {
- const card = toKanbanSession(n)
- if (!card) return []
- const worktreeBranch = worktreeBranchOf(n, byId)
- return [worktreeBranch ? { ...card, worktreeBranch } : card]
- })
- }, [nodes, perProjectKanbanOpen])
+ // The worktree branch a card works on comes from its enclosing bound group — the link a pull
+ // request's head branch is matched against (lib/pullLinks.ts) — except on an SSH project, where
+ // branch links are not supported and no card carries one (kanbanSessionsFrom).
+ const activeProjectSsh = useProjects((s) => !!s.projects.find((p) => p.id === s.activeProjectId)?.ssh)
+ const kanbanSessions = useMemo(
+ () => perProjectKanbanOpen ? kanbanSessionsFrom(nodes, { ssh: activeProjectSsh }) : NO_KANBAN_SESSIONS,
+ [nodes, perProjectKanbanOpen, activeProjectSsh]
+ )
// Create a node from the board's per-column "+ New" menu: it lands on the canvas (view
// center) and, for a real column, is assigned there. The assignment is written directly —
diff --git a/src/renderer/canvas/toKanbanSession.ts b/src/renderer/canvas/toKanbanSession.ts
index c0f0b5729..bbb8c0faa 100644
--- a/src/renderer/canvas/toKanbanSession.ts
+++ b/src/renderer/canvas/toKanbanSession.ts
@@ -83,3 +83,19 @@ export function worktreeBranchOf(n: CanvasNode, byId: ReadonlyMap<string, Canvas
}
return undefined
}
+
+/**
+ * The board's session cards, from the canvas nodes. On an SSH project the cards carry NO worktree
+ * branch: worktree groups are local-only, so a branch link there is not supported — and leaving the
+ * branch off HERE is what keeps the card face, the merge-driven move and the card modal (which says
+ * so) in agreement. An issue-bound card still links through its issue.
+ */
+export function kanbanSessionsFrom(nodes: CanvasNode[], options: { ssh: boolean }): KanbanSession[] {
+ const byId = new Map(nodes.map((n) => [n.id, n]))
+ return nodes.flatMap((n): KanbanSession[] => {
+ const card = toKanbanSession(n)
+ if (!card) return []
+ const worktreeBranch = options.ssh ? undefined : worktreeBranchOf(n, byId)
+ return [worktreeBranch ? { ...card, worktreeBranch } : card]
+ })
+}
diff --git a/src/renderer/canvas/worktreeBranchOf.test.ts b/src/renderer/canvas/worktreeBranchOf.test.ts
index 746d50560..a95a70b9a 100644
--- a/src/renderer/canvas/worktreeBranchOf.test.ts
+++ b/src/renderer/canvas/worktreeBranchOf.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { CanvasNode } from '../state/workspace'
-import { worktreeBranchOf } from './toKanbanSession'
+import { kanbanSessionsFrom, worktreeBranchOf } from './toKanbanSession'
const node = (id: string, over: Partial<CanvasNode> = {}): CanvasNode =>
({ id, type: 'terminal', position: { x: 0, y: 0 }, data: {}, ...over }) as CanvasNode
@@ -31,3 +31,15 @@ describe('worktreeBranchOf', () => {
expect(worktreeBranchOf(byId.get('t')!, byId)).toBeUndefined()
})
})
+
+describe('kanbanSessionsFrom', () => {
+ const nodes = [group('g', 'feat/x'), node('t', { parentId: 'g', data: { title: 'Agent' } as never })]
+
+ it('cards in a worktree group carry its branch', () => {
+ expect(kanbanSessionsFrom(nodes, { ssh: false })[0].worktreeBranch).toBe('feat/x')
+ })
+
+ it('on an SSH project no card carries a branch, so the face, the move and the modal agree', () => {
+ expect(kanbanSessionsFrom(nodes, { ssh: true })[0]).not.toHaveProperty('worktreeBranch')
+ })
+})
diff --git a/src/renderer/components/kanban/usePullAutoMove.test.tsx b/src/renderer/components/kanban/usePullAutoMove.test.tsx
index 38c123c5a..7e4cca01c 100644
--- a/src/renderer/components/kanban/usePullAutoMove.test.tsx
+++ b/src/renderer/components/kanban/usePullAutoMove.test.tsx
@@ -21,13 +21,21 @@ const merged: GitHubPullBoard = {
observedAt: 1, stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false
}
-/** The host's claim: the first ask for a key wins, like GitHubPullStatusTracker.claim. */
-function hostClaims() {
+/** The host's rules, like GitHubPullStatusTracker: a claim needs a wait note for this card, and the
+ * first ask for a key wins. `seedWaits` stands in for notes recorded while the PR was open. */
+function hostClaims(seedWaits: string[] = ['p1:card-1:12']) {
const claimed = new Set<string>()
+ const waits = new Set(seedWaits)
return {
+ waits,
+ notePullWaits: vi.fn(async (request: { projectId: string; cardId: string; pulls: number[] }) => {
+ for (const pull of request.pulls) waits.add(`${request.projectId}:${request.cardId}:${pull}`)
+ return request.pulls.length
+ }),
claimPullAutoMove: vi.fn(async (request: { projectId: string; cardId: string; pulls: number[] }) => {
const key = `${request.projectId}:${request.cardId}:${request.pulls.join(',')}`
if (claimed.has(key)) return false
+ if (!request.pulls.some((pull) => waits.has(`${request.projectId}:${request.cardId}:${pull}`))) return false
claimed.add(key)
return true
})
@@ -84,6 +92,28 @@ describe('usePullAutoMove', () => {
expect(first.mock.calls.length + second.mock.calls.length).toBe(1)
})
+ it('notes the wait while the PR is open, then moves on the merge', async () => {
+ const api = hostClaims([])
+ const onAutoMove = vi.fn()
+ const open: GitHubPullBoard = { ...merged, pulls: [{ number: 12, lifecycle: 'open', headRefName: 'feat/x', closes: [] }] }
+ const root = createRoot(document.createElement('div'))
+ act(() => root.render(<Probe api={api} pullBoard={open} onAutoMove={onAutoMove} />))
+ await settle()
+ expect(api.notePullWaits).toHaveBeenCalledWith({ projectId: 'p1', cardId: 'card-1', pulls: [12] })
+ act(() => root.render(<Probe api={api} pullBoard={merged} onAutoMove={onAutoMove} />))
+ await settle()
+ expect(onAutoMove).toHaveBeenCalledTimes(1)
+ })
+
+ it('a card that first appears after the merge never moves', async () => {
+ const api = hostClaims([])
+ const onAutoMove = vi.fn()
+ act(() => createRoot(document.createElement('div')).render(<Probe api={api} pullBoard={merged} onAutoMove={onAutoMove} />))
+ await settle()
+ expect(api.claimPullAutoMove).toHaveBeenCalled()
+ expect(onAutoMove).not.toHaveBeenCalled()
+ })
+
it('never moves a card on a relay tab — that board belongs to the other machine', async () => {
arm(true)
const api = hostClaims()
diff --git a/src/renderer/components/kanban/usePullAutoMove.ts b/src/renderer/components/kanban/usePullAutoMove.ts
index d499ce3fa..da4e7a257 100644
--- a/src/renderer/components/kanban/usePullAutoMove.ts
+++ b/src/renderer/components/kanban/usePullAutoMove.ts
@@ -18,7 +18,7 @@ import { documentChaseDeps, startPullChase } from '../../lib/pullChase'
* the user just changed in another.
*/
export function usePullAutoMove(input: {
- api: Pick<GitHubIssuesApi, 'claimPullAutoMove'>
+ api: Pick<GitHubIssuesApi, 'claimPullAutoMove' | 'notePullWaits'>
projectId: string
cards: Array<{ id: string; kind: string; worktreeBranch?: string; issueRef?: IssueRef }>
board: ProjectKanban
@@ -44,9 +44,22 @@ export function usePullAutoMove(input: {
}, [])
const latest = useRef(onAutoMove)
latest.current = onAutoMove
+ // Wait notes already sent from this board, so a re-render does not re-send them (the host dedupes
+ // too; this only saves the calls).
+ const noted = useRef(new Set<string>())
useEffect(() => {
if (!entry || !onAutoMove) return
- for (const move of planPullAutoMoves({ cards, board, pullBoard, entry }).moves) {
+ const plan = planPullAutoMoves({ cards, board, pullBoard, entry })
+ for (const wait of plan.waits) {
+ const fresh = wait.pulls.filter((pull) => !noted.current.has(`${projectId}\0${wait.cardId}\0${pull}`))
+ if (!fresh.length) continue
+ for (const pull of fresh) noted.current.add(`${projectId}\0${wait.cardId}\0${pull}`)
+ void api.notePullWaits({ projectId, cardId: wait.cardId, pulls: fresh }).catch(() => {
+ // Not recorded: let a later pass try again.
+ for (const pull of fresh) noted.current.delete(`${projectId}\0${wait.cardId}\0${pull}`)
+ })
+ }
+ for (const move of plan.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
diff --git a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
index e53ac5184..f6194cd89 100644
--- a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
+++ b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
@@ -129,16 +129,29 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
: ''
/** Machine-local on purpose (see @shared/kanban-pull-links): switching it on here never changes
* what a teammate's app does. Every write prunes projects this machine no longer has. */
- const setAutoMoveColumn = (columnId: string): void => {
+ const setAutoMoveColumn = async (columnId: string): Promise<void> => {
if (!projectId) return
- const live = new Set(useProjects.getState().projects.map((item) => item.id))
- const current = prunePullAutoMove(sanitizeKanbanPullAutoMove(autoMoveRaw), live)
- const { [projectId]: previous, ...others } = current.projects
+ const previous = sanitizeKanbanPullAutoMove(autoMoveRaw).projects[projectId]
// Switching it ON starts the clock: only merges observed from now on move a card. Changing only
- // the target column keeps the original time — the switch never went off.
- const armedAt = previous?.armedAt ?? Date.now()
+ // the target column keeps the original time — the switch never went off. The time is the HOST's
+ // (from the pull board, which it answers from memory): `mergedSeenAt` is stamped on the host, and
+ // a Server Edition browser's clock can be minutes off it.
+ let armedAt = previous?.armedAt
+ if (columnId && armedAt === undefined) {
+ const hostNow = await window.nodeTerminal.githubIssues.pullStatus(projectId)
+ .then((board) => board.now)
+ .catch(() => undefined)
+ armedAt = typeof hostNow === 'number' && Number.isSafeInteger(hostNow) ? hostNow : Date.now()
+ }
+ // Re-read after the await: another setting may have changed meanwhile.
+ const live = new Set(useProjects.getState().projects.map((item) => item.id))
+ const current = prunePullAutoMove(
+ sanitizeKanbanPullAutoMove(useSettings.getState().settings.kanbanPullAutoMove), live)
+ const { [projectId]: _previous, ...others } = current.projects
updateSettings({
- kanbanPullAutoMove: { projects: columnId ? { ...others, [projectId]: { columnId, armedAt } } : others }
+ kanbanPullAutoMove: {
+ projects: columnId && armedAt !== undefined ? { ...others, [projectId]: { columnId, armedAt } } : others
+ }
})
}
@@ -620,12 +633,12 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
<FieldRow
label={ROWS.pullAutoMove.title}
htmlFor="github-pull-auto-move"
- description={`${ROWS.pullAutoMove.description} Only session cards in a worktree group move — GitHub closes linked issues itself. Only merges this machine sees after you turn this on count (it must have seen the pull request open first), and a card never moves while one of its pull requests closed without merging. This setting is for this machine only.`}
+ description={`${ROWS.pullAutoMove.description} Session cards move — those in a worktree group, and those started on an issue — never GitHub issue cards, which GitHub closes itself. A card moves only if this machine saw it waiting on the pull request while it was open, only for merges seen after you turn this on, and never while one of its pull requests closed without merging. This setting is for this machine only.`}
control={
<Select
id="github-pull-auto-move"
value={board.columns.some((column) => column.id === autoMoveColumn) ? autoMoveColumn : ''}
- onChange={(event) => setAutoMoveColumn(event.target.value)}
+ onChange={(event) => void setAutoMoveColumn(event.target.value)}
>
<option value="">Off</option>
{board.columns.map((column) => (
diff --git a/src/renderer/lib/pullAutoMove.test.ts b/src/renderer/lib/pullAutoMove.test.ts
index 15ccf07de..d9ab86218 100644
--- a/src/renderer/lib/pullAutoMove.test.ts
+++ b/src/renderer/lib/pullAutoMove.test.ts
@@ -97,6 +97,14 @@ describe('planPullAutoMoves', () => {
}).moves).toEqual([])
})
+ it('reports a card waiting on an open PR, so the host can note that THIS card saw it open', () => {
+ const plan = planPullAutoMoves({
+ cards: [card], board: board(), pullBoard: pulls([pull(3, 'open'), pull(4, 'draft'), observedMerge(1)]), entry
+ })
+ expect(plan.moves).toEqual([])
+ expect(plan.waits).toEqual([{ cardId: 'card-1', pulls: [3, 4] }])
+ })
+
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([])
diff --git a/src/renderer/lib/pullAutoMove.ts b/src/renderer/lib/pullAutoMove.ts
index 4936a8f23..3548a7346 100644
--- a/src/renderer/lib/pullAutoMove.ts
+++ b/src/renderer/lib/pullAutoMove.ts
@@ -88,6 +88,10 @@ const SESSION_CARD_KINDS = new Set(['terminal', 'sticky', 'browser'])
export interface PullAutoMovePlan {
moves: Array<{ cardId: string; fromColumnId: string | null; pulls: number[] }>
+ /** Cards waiting on still-open PRs. The host records these as evidence that THIS card saw the PR
+ * open; its claim for a move later requires one, so a card that first appears after the merge
+ * never moves. */
+ waits: Array<{ cardId: string; pulls: number[] }>
}
/**
@@ -103,21 +107,31 @@ export function planPullAutoMoves(input: {
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 idle: PullAutoMovePlan = { moves: [], waits: [] }
+ if (!entry || !pullBoard || pullBoard.observedAt === undefined || pullBoard.stale) return idle
+ if (!board.columns.some((column) => column.id === entry.columnId)) return idle
const optedOut = new Set(readPullLinks(board).noAutoMove)
const moves: PullAutoMovePlan['moves'] = []
+ const waits: PullAutoMovePlan['waits'] = []
for (const card of input.cards) {
if (!SESSION_CARD_KINDS.has(card.kind)) continue
+ const linked = pullsForCard(card, pullBoard, board).linked
const fromColumnId = columnForNode(board, card.id)?.id ?? null
const decision = decidePullAutoMove({
optedOut: optedOut.has(card.id),
- linked: pullsForCard(card, pullBoard, board).linked,
+ linked,
columnId: fromColumnId,
targetColumnId: entry.columnId,
armedAt: entry.armedAt
})
if (decision.kind === 'move') moves.push({ cardId: card.id, fromColumnId, pulls: decision.pulls })
+ if (decision.kind === 'none' && decision.reason === 'waiting') {
+ waits.push({
+ cardId: card.id,
+ pulls: linked.filter((pull) => pull.lifecycle === 'open' || pull.lifecycle === 'draft')
+ .map((pull) => pull.number)
+ })
+ }
}
- return { moves }
+ return { moves, waits }
}
diff --git a/src/renderer/state/githubIssues.test.ts b/src/renderer/state/githubIssues.test.ts
index 2ffd3912a..3c59db542 100644
--- a/src/renderer/state/githubIssues.test.ts
+++ b/src/renderer/state/githubIssues.test.ts
@@ -38,6 +38,7 @@ function api(): GitHubIssuesApi {
chasePulls: vi.fn(async () => false),
pullChecks: vi.fn(async () => ({ status: 'no-checks' as const })),
claimPullAutoMove: vi.fn(async () => false),
+ notePullWaits: vi.fn(async () => 0),
projectAvatar: vi.fn(async () => null),
onChanged: vi.fn(() => () => {})
}
diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.ts
index d1d35ad8a..415cce6a6 100644
--- a/src/shared/github-issues.ts
+++ b/src/shared/github-issues.ts
@@ -290,6 +290,9 @@ export interface GitHubIssuesApi {
/** The one-time permission to move a session card because its linked PRs merged. The first ask
* across every window wins; the host remembers it. */
claimPullAutoMove(request: { projectId: string; cardId: string; pulls: number[] }): Promise<boolean>
+ /** "This card is waiting on these still-open PRs." The host keeps a note only for PRs it holds as
+ * open; a later claim for this card requires one. Answers how many notes were new. */
+ notePullWaits(request: { projectId: string; cardId: string; pulls: number[] }): Promise<number>
onChanged(projectId: string, listener: (changedIssueNumbers: number[]) => void): () => void
/** Resolve the project's GitHub org/user avatar (owner derived host-side from the project's own
* origin — never a caller-supplied slug). Null when the project has no GitHub origin or the
diff --git a/src/shared/github-pull-status.ts b/src/shared/github-pull-status.ts
index 356700bd7..74d2966fd 100644
--- a/src/shared/github-pull-status.ts
+++ b/src/shared/github-pull-status.ts
@@ -44,7 +44,9 @@ export interface PullStatusFacts {
isDraft: boolean
mergeable: GitHubMergeable | null
mergeStateStatus: string | null
- rollup: GitHubRollupState | null
+ /** `UNRECOGNIZED` = a state GitHub added after this build: it claims nothing (and is NOT "no
+ * checks", which is `null`). */
+ rollup: GitHubRollupState | 'UNRECOGNIZED' | null
rollupOid: string | null
/** Issues in the SAME repository this PR closes on merge (GitHub's own linking). */
closes: number[]
@@ -76,6 +78,8 @@ export interface GitHubPullStatus {
export interface GitHubPullBoard {
/** `owner/name` these pull requests belong to (the one `closes` numbers refer to). */
repository?: string
+ /** The host's clock when it answered (epoch ms) — what `mergedSeenAt` is measured in. */
+ now?: number
pulls: GitHubPullStatus[]
/** Epoch ms of the last read that succeeded. Absent = none yet in this app run. */
observedAt?: number
@@ -146,7 +150,7 @@ export function pullStatusFrom(
): GitHubPullStatus {
const lifecycle: PullLifecycle = facts.isDraft ? 'draft' : 'open'
let ci: PullCiState | undefined
- if (access.ci) {
+ if (access.ci && facts.rollup !== 'UNRECOGNIZED') {
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
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 5e31991af..16898280a 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -416,6 +416,7 @@ export const IPC = {
githubIssuesChasePulls: 'githubIssues:chase-pulls',
githubIssuesPullChecks: 'githubIssues:pull-checks',
githubIssuesClaimPullAutoMove: 'githubIssues:claim-pull-auto-move',
+ githubIssuesNotePullWaits: 'githubIssues:note-pull-waits',
githubIssuesChanged: (projectId: string) => `githubIssues:changed:${projectId}`,
githubProjectAvatar: 'github:projectAvatar',
githubControlStatus: 'githubControl:status',