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.

feat(kanban): two-way GitHub Issues sync on the board (#90)

Matt Kneale9b9ba1f2543a
diff --git a/README.md b/README.md
index 8497ae11f..87d7b9845 100644
--- a/README.md
+++ b/README.md
@@ -139,6 +139,9 @@ opencode / custom) · 📝 **Sticky note** (link to an agent as context) · 🗂
git, and even the board run there while the canvas stays local.
- **Source control** — VS Code-style stage/unstage, discard, branch switch/create,
commit, push/sync/publish, **worktrees**, and `gh` sign-in — backed by system `git`.
+- **GitHub Issues on Kanban** – opt-in issue cards, exact label-to-column mapping,
+ All / GitHub / Sessions filtering, and two-way move, close, and reopen sync. See
+ [setup and security details](./docs/github-issues-kanban.md).
- **AI commit messages & terminal names** — bring-your-own local agent CLI run read-only
on the staged diff or captured output.
- **Your sessions, in your pocket** — **nodeterm mobile** (iOS) attaches to the same live
diff --git a/docs/github-issues-kanban.md b/docs/github-issues-kanban.md
new file mode 100644
index 000000000..8cb648234
--- /dev/null
+++ b/docs/github-issues-kanban.md
@@ -0,0 +1,77 @@
+# GitHub Issues on the Kanban board
+
+nodeterm can show GitHub issues beside live session cards and keep issue state in sync with board movement. GitHub remains the source of truth. GitHub issues are never copied into the shared Kanban assignments.
+
+## Set up
+
+1. Open the project and create its Kanban board if it does not have one.
+2. Open Settings, then GitHub Issues in the Workspace group.
+3. Turn on Include GitHub issues.
+4. Confirm the repository detected from the Git origin, or enter an `owner/repository` override.
+5. Choose an authentication method.
+6. Map each Kanban column to one exact GitHub issue label.
+7. Choose the completion column.
+8. Approve access for this project on this computer.
+9. Create missing labels if needed, then refresh.
+
+Repository overrides and label mappings are shared in `.nodeterm/project.json`. Credentials and the computer approval are local and are never written to the project file.
+
+## Authentication
+
+A resolved credential is reused for up to 30 seconds so that reading issues does not re-run the GitHub CLI and re-validate the token on every request. Saving a token, clearing it, switching provider, or revoking the machine drops that immediately.
+
+Auto uses an authenticated GitHub CLI first and falls back to a saved token. GitHub CLI only and Personal access token only enforce the selected method exactly.
+
+For GitHub CLI, sign in to `github.com` with `gh auth login`.
+
+For a fine-grained personal access token, grant access only to the selected repository with these repository permissions.
+
+- Metadata – read
+- Issues – read and write
+
+The token field is write only. The renderer cannot read the saved value. Electron uses encrypted system storage when a secure backend is available. If it is unavailable, nodeterm shows a warning and stores the token in a local mode `0600` file. Server Edition always uses the restricted local file and shows the same warning.
+
+## Mapping and movement
+
+Each configured column has one exact issue label. Matching is case insensitive, but writes use the spelling shown in Settings.
+
+- Open issues with one mapped label appear in that column.
+- Open issues with no mapped label appear in Ungrouped.
+- Issues with several mapped labels appear in Ungrouped with a conflict warning.
+- Closed issues appear in the completion column.
+- Moving an issue to the completion column closes it.
+- Moving a closed issue outside the completion column reopens it, including a drop on Ungrouped.
+- Closing and reopening ask for confirmation first. Both notify everyone watching the issue and neither can be undone from the board. Moves that only rewrite labels apply immediately, and a card dropped back where it already sits writes nothing.
+- A move never rewrites the GitHub close reason. Re-closing an issue that is already closed leaves a `not planned` close as it is.
+- Unrelated labels are preserved.
+- Pull requests are excluded.
+
+Every card has a Move issue selector, so movement does not depend on drag and drop. Stale writes are not repeated. nodeterm refreshes the current issue and asks for a new action.
+
+## Source filter and paging
+
+Use All, GitHub, or Sessions in the board header to choose which card sources are visible. The selection is temporary and does not change the project configuration.
+
+The label filter groups session labels and GitHub labels separately. GitHub selections are sent to the host with a `github:` namespace, while session selections remain local to the board.
+
+Issues are loaded in pages of up to 50 per column. Use Show more issues at the end of a column for the next page.
+
+## Refresh and cache
+
+One repository poll runs every 60 seconds while at least one board view is visible. Requested refreshes are floored at one every 30 seconds per project, and a full reconciliation at one every 2 minutes, so a repeated request cannot spend the account's hourly API quota. A refresh that fails does not hold the floor, so Retry stays responsive. A complete reconciliation runs at least every 24 hours. Incremental refreshes overlap by two seconds to avoid missing boundary updates.
+
+The private host cache is stored under the nodeterm data directory in `github-issues-cache`. Clear cached data in Settings to remove every identity cache linked to that local project and repository. This remains available while signed out and after revocation. The next authenticated refresh rebuilds it.
+
+nodeterm supports up to 10,000 issues and a 64 MiB cache document per repository. An incomplete refresh never replaces the last complete cache. If the first refresh exceeds a limit, the partial data is read only.
+
+## Local trust and remote sessions
+
+Approval is tied to the local workspace identity, project, and repository. Changing the repository requires a new approval. Revoke this machine in Settings to stop credential use, cache access, and GitHub network access for that project.
+
+GitHub HTTP requests and avatar downloads run only on the trusted project host. Relay tabs send issue queries and movements to that host, but GitHub control remains local and cannot be invoked by a relay peer. Configure a relayed project on the computer that hosts it.
+
+## Current scope
+
+This release supports reading issues, source filtering, paging, mapped label creation, movement, conflict resolution, close, reopen, refresh, and cache controls.
+
+Editing issue titles and bodies, comments, ordinary labels, assignees, milestones, locking, and media rendering are planned for the follow-up issue editor. Until then, Open on GitHub opens the canonical issue page.
diff --git a/docs/superpowers/plans/2026-08-09-github-issues-kanban-sync.md b/docs/superpowers/plans/2026-08-09-github-issues-kanban-sync.md
new file mode 100644
index 000000000..db73953f2
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-09-github-issues-kanban-sync.md
@@ -0,0 +1,670 @@
+# GitHub Issues Kanban Sync Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Add opt-in, two-way GitHub issue synchronisation to the nodeterm Kanban board with GitHub as the canonical store, exact issue-label column mapping, local trust approval, GitHub CLI or write-only token authentication, source filtering, and safe move, close, and reopen actions.
+
+**Architecture:** Shared project files store only validated repository and column-label configuration. A host-owned GitHub service resolves machine-local approval and credentials, discovers the repository, performs bounded REST requests, maintains a private complete cache, and exposes paged domain objects through the existing Electron, Server Edition, and relay platform seam. The renderer combines paged GitHub cards with native session cards without copying GitHub issues into `ProjectKanban.assignments`.
+
+**Tech Stack:** TypeScript, Electron 42, React 18, Zustand 4, Vitest 4, Node `fetch`, the existing `CorePlatform` RPC seam, Electron `safeStorage`, and existing nodeterm Settings and Kanban styles.
+
+## Global Constraints
+
+- This plan implements Pull Request 1 from the approved design. Full issue body editing, comments, ordinary label editing, assignees, milestones, locking, and the full issue modal remain Pull Request 2.
+- GitHub is canonical for every GitHub-backed card. Never persist an issue as a native assignment.
+- Store no secret or local approval in `.nodeterm/project.json`, `settings.json`, cache content exposed to renderers, logs, screenshots, recordings, or pull-request text.
+- Require machine-local approval before credential access, cache read, or network access.
+- Map columns by exact GitHub issue label names. Case-variant duplicate mappings are invalid.
+- Exclude pull requests. Put unmatched open issues in `Ungrouped`. Put closed issues in the completion column.
+- Close on movement into the completion column and reopen on movement out. Preserve unrelated labels.
+- Run GitHub HTTP only in the trusted host. Allow only `api.github.com`; avatar delivery allows only redirect-free `https://avatars.githubusercontent.com` requests.
+- Bound a complete repository to 10,000 issues and a 64 MiB cache document. Never replace the last complete cache with an incomplete refresh.
+- Poll once per repository every 60 seconds while at least one visible subscriber exists. Perform a full reconciliation at least every 24 hours.
+- Keep all UI actions available without pointer drag and usable at 390px in light and dark themes.
+- Use no new runtime dependency.
+- Every implementation task follows red, green, refactor. Observe the focused test fail before adding production code.
+- Do not mutate the upstream nodeterm repository for evidence. Use deterministic fixtures and only an explicitly authorised test repository for live writes.
+
+---
+
+## File map
+
+- `src/shared/github-issues.ts` owns all serialisable GitHub configuration, control, card, page, mutation, status, and API contracts.
+- `src/core/github/config.ts` owns repository parsing and canonical Kanban mapping normalisation.
+- `src/core/github/control-store.ts` owns revision-checked local approvals and provider selection.
+- `src/core/github/credentials.ts` owns GitHub CLI and stored-token selection without returning secrets to the renderer.
+- `src/core/github/client.ts` owns validated GitHub REST requests and response decoding.
+- `src/core/github/avatar-fetcher.ts` owns lazy, redirect-free, bounded avatar delivery.
+- `src/core/github/request-coordinator.ts` owns authenticated-identity concurrency, mutation spacing, and global rate backoff.
+- `src/core/github/cache.ts` owns private atomic cache persistence and complete versus incomplete attempt retention.
+- `src/core/github/service.ts` owns subscriptions, refresh, paging, mapping, and serial issue mutations.
+- `src/core/github/handlers.ts` registers the core-bound issue surface.
+- `src/main/github-control.ts` owns Electron-only credential and approval handlers plus `safeStorage` integration.
+- `src/server/github-control.ts` owns authenticated Server Edition credential and approval handlers with restricted-file token storage.
+- `src/renderer/state/githubIssues.ts` owns bounded renderer pages, subscription state, and mutation state.
+- `src/renderer/components/settings/sections/GitHubIssuesSection.tsx` owns the settings experience.
+- `src/renderer/components/kanban/GitHubIssueCard.tsx` owns issue card rendering and accessible actions.
+- `src/renderer/components/kanban/GitHubIssueSummaryModal.tsx` owns the Pull Request 1 safe summary and canonical link.
+- `src/renderer/components/kanban/KanbanSourceFilter.tsx` owns `All`, `GitHub`, and `Sessions` selection.
+- Existing shared, preload, bridge, boot, Kanban, Settings, and style files connect those focused units.
+
+### Task 1: Shared configuration and local workspace identity
+
+**Files:**
+- Create: `src/shared/github-issues.ts`
+- Create: `src/core/github/config.ts`
+- Create: `src/core/github/config.test.ts`
+- Modify: `src/shared/types.ts`
+- Modify: `src/core/workspace-files.ts`
+- Modify: `src/core/workspace-files.test.ts`
+- Modify: `src/core/workspace-store.ts`
+- Modify: `src/core/workspace-store.test.ts`
+- Modify: `src/renderer/lib/kanban.ts`
+- Modify: `src/renderer/lib/kanban.test.ts`
+
+**Interfaces:**
+- Produces: `normaliseProjectKanbanGitHub(value, columns)`, `parseGitHubRepository(value)`, `ProjectKanbanGitHub`, and a preserved `IndexEntryV3.localApprovalId`.
+- Consumes: existing `ProjectKanban`, `KanbanColumn`, `splitWorkspace`, `validKanban`, and pure board transforms.
+
+- [ ] **Step 1: Write failing configuration and identity tests**
+
+```ts
+it('rejects case-variant duplicate labels and unknown columns', () => {
+ const columns = [{ id: 'todo', title: 'Todo', color: '#8b5cf6' }]
+ expect(normaliseProjectKanbanGitHub({ columnMappings: [
+ { columnId: 'todo', label: 'Status: Todo' },
+ { columnId: 'missing', label: 'status: todo' }
+ ] }, columns)).toEqual({ ok: false, reason: 'invalid-mapping' })
+})
+
+it('preserves localApprovalId through save and reload but never writes it to project.json', async () => {
+ const first = await store.load()
+ const approvalId = store.indexEntry(first.projects[0].id)?.localApprovalId
+ await store.save(first)
+ expect(approvalId).toMatch(/^[0-9a-f-]{36}$/)
+ expect(readSharedProjectFile()).not.toContain('localApprovalId')
+ expect((await store.loadIndex()).entries[0].localApprovalId).toBe(approvalId)
+})
+```
+
+- [ ] **Step 2: Run focused tests and observe the expected failures**
+
+Run `npx vitest run src/core/github/config.test.ts src/core/workspace-files.test.ts src/core/workspace-store.test.ts src/renderer/lib/kanban.test.ts`
+
+Expected result is failure because the new contracts and `localApprovalId` do not exist.
+
+- [ ] **Step 3: Add the shared contracts and strict normaliser**
+
+```ts
+export interface ProjectKanbanGitHub {
+ repository?: string
+ columnMappings: Array<{ columnId: string; label: string }>
+ completionColumnId?: string
+}
+
+export type NormalisedGitHubConfig = {
+ repository?: string
+ mappings: ReadonlyMap<string, string>
+ completionColumnId?: string
+ revision: string
+}
+
+export function normaliseProjectKanbanGitHub(
+ value: unknown,
+ columns: readonly KanbanColumn[]
+): { ok: true; value: NormalisedGitHubConfig } | { ok: false; reason: 'invalid-mapping' } {
+ // Trim strings, reject unknown or duplicate column ids, reject empty or case-duplicate labels,
+ // validate the completion id, canonicalise the repository, and hash canonical JSON as revision.
+}
+```
+
+Extend `ProjectKanban` with `github?: ProjectKanbanGitHub`. Make every board transform spread the existing board before replacing its own property so `github`, `meta`, and `labels` survive.
+
+- [ ] **Step 4: Preserve the machine-local approval id**
+
+Add `localApprovalId?: string` to `IndexEntryV3`. In `WorkspaceStore`, assign `randomUUID()` when an index entry is created or first loaded without one. When `splitWorkspace` creates replacement entries, merge the old entry's `localApprovalId` by project id inside `WorkspaceStore.save`. Do not add the field to `Project`, `ProjectFileV1`, or `projectToFile`.
+
+- [ ] **Step 5: Run focused tests and commit**
+
+Run `npx vitest run src/core/github/config.test.ts src/core/workspace-files.test.ts src/core/workspace-store.test.ts src/renderer/lib/kanban.test.ts src/renderer/state/projects.kanban.test.ts`
+
+```bash
+git add src/shared/github-issues.ts src/shared/types.ts src/core/github/config.ts src/core/github/config.test.ts src/core/workspace-files.ts src/core/workspace-files.test.ts src/core/workspace-store.ts src/core/workspace-store.test.ts src/renderer/lib/kanban.ts src/renderer/lib/kanban.test.ts
+git commit -m "feat: add GitHub Kanban configuration"
+```
+
+### Task 2: Transactional local control and credentials
+
+**Files:**
+- Create: `src/core/github/control-store.ts`
+- Create: `src/core/github/control-store.test.ts`
+- Create: `src/core/github/credentials.ts`
+- Create: `src/core/github/credentials.test.ts`
+- Create: `src/main/github-control.ts`
+- Create: `src/main/github-control.test.ts`
+- Create: `src/server/github-control.ts`
+- Create: `src/server/github-control.test.ts`
+- Modify: `src/shared/github-issues.ts`
+
+**Interfaces:**
+- Produces: `GitHubControlStore`, `GitHubCredentialResolver`, `GitHubSecretCodec`, and status-only `GitHubAuthStatus`.
+- Consumes: `localApprovalId`, normalised repository, host `userDataDir`, injected command runner, and Electron `safeStorage` only through the main adapter.
+
+- [ ] **Step 1: Write failing trust, revision, and fallback tests**
+
+```ts
+it('does not let a stale client restore a revoked approval', async () => {
+ const approved = await store.approve({ expectedRevision: 0, localApprovalId: 'local-a', projectId: 'p', repository: 'o/r' })
+ await store.revoke({ expectedRevision: approved.revision, localApprovalId: 'local-a' })
+ await expect(store.approve({ expectedRevision: approved.revision, localApprovalId: 'local-a', projectId: 'p', repository: 'o/r' }))
+ .rejects.toMatchObject({ code: 'revision-conflict' })
+})
+
+it.each([
+ ['auto', 'gh-ok', 'token-ok', 'gh'],
+ ['auto', 'gh-bad', 'token-ok', 'token'],
+ ['gh', 'gh-bad', 'token-ok', null],
+ ['token', 'gh-ok', 'token-bad', null]
+])('uses the exact provider truth table', async (provider, gh, token, expected) => {
+ expect(await resolveFixture(provider, gh, token)).toBe(expected)
+})
+```
+
+- [ ] **Step 2: Run focused tests and observe failures**
+
+Run `npx vitest run src/core/github/control-store.test.ts src/core/github/credentials.test.ts src/main/github-control.test.ts src/server/github-control.test.ts`
+
+Expected result is failure because the stores and adapters do not exist.
+
+- [ ] **Step 3: Implement revision-checked control state**
+
+```ts
+export interface GitHubControlState {
+ version: 1
+ revision: number
+ authProvider: 'auto' | 'gh' | 'token'
+ approvals: GitHubProjectApproval[]
+}
+
+export class GitHubControlStore {
+ load(): Promise<GitHubControlState>
+ approve(input: ApprovalMutation): Promise<GitHubControlState>
+ revoke(input: RevokeApproval): Promise<GitHubControlState>
+ selectProvider(input: ProviderMutation): Promise<GitHubControlState>
+}
+```
+
+Validate exact fields and bounds, compare `expectedRevision`, write a `0600` temporary file, rename atomically, and increment the revision once. Approval lookup must match `localApprovalId`, project id, and normalised repository.
+
+- [ ] **Step 4: Implement write-only credential adapters and exact resolution**
+
+```ts
+export interface GitHubSecretCodec {
+ availability(): 'encrypted' | 'restricted-file' | 'unavailable'
+ save(token: string): Promise<void>
+ clear(): Promise<void>
+ readForHost(): Promise<string | null>
+}
+
+export class GitHubCredentialResolver {
+ resolve(provider: GitHubAuthProvider): Promise<ResolvedCredential | null>
+ status(provider: GitHubAuthProvider): Promise<GitHubAuthStatus>
+}
+```
+
+Validate `gh auth status --hostname github.com` before `gh auth token --hostname github.com`. For Electron, use `safeStorage.isEncryptionAvailable()` and reject the `basic_text` backend. For Server Edition, use a dedicated mode `0600` file and return a visible restricted-storage warning. Never expose `ResolvedCredential.token` outside core.
+
+- [ ] **Step 5: Run focused tests and commit**
+
+Run `npx vitest run src/core/github/control-store.test.ts src/core/github/credentials.test.ts src/main/github-control.test.ts src/server/github-control.test.ts`
+
+```bash
+git add src/core/github src/main/github-control.ts src/main/github-control.test.ts src/server/github-control.ts src/server/github-control.test.ts src/shared/github-issues.ts
+git commit -m "feat: secure GitHub credentials and approval"
+```
+
+### Task 3: Bounded REST client and identity-wide request coordination
+
+**Files:**
+- Create: `src/core/github/client.ts`
+- Create: `src/core/github/client.test.ts`
+- Create: `src/core/github/avatar-fetcher.ts`
+- Create: `src/core/github/avatar-fetcher.test.ts`
+- Create: `src/core/github/request-coordinator.ts`
+- Create: `src/core/github/request-coordinator.test.ts`
+- Modify: `src/shared/github-issues.ts`
+
+**Interfaces:**
+- Produces: `GitHubIssuesClient`, `GitHubRequestCoordinator`, validated `GitHubIssue`, `GitHubLabel`, and rate metadata.
+- Consumes: a host-only bearer token, authenticated GitHub user id, injected `fetch`, clock, and scheduler.
+
+- [ ] **Step 1: Write failing validation, pagination, and rate tests**
+
+```ts
+it('drops pull requests and rejects an oversized response', async () => {
+ const client = fixtureClient([{ number: 1, pull_request: {} }, issueFixture(2)])
+ expect((await client.listIssues('o/r', { state: 'all', page: 1 })).items.map((i) => i.number)).toEqual([2])
+ await expect(oversizedClient().listIssues('o/r', { state: 'all', page: 1 }))
+ .rejects.toMatchObject({ code: 'response-too-large' })
+})
+
+it('pauses every repository for the same identity after a secondary limit', async () => {
+ const coordinator = fixtureCoordinator()
+ coordinator.noteRateLimit('github-user-1', { kind: 'secondary', retryAt: 5_000 })
+ expect(coordinator.canStart('github-user-1', 'other/repo', 4_999)).toBe(false)
+})
+
+it('blocks avatar redirects and stops at the page aggregate budget', async () => {
+ const fetcher = fixtureAvatarFetcher({ bytesPerAvatar: 120 * 1024 })
+ expect(await fetcher.forPage(userFixtures(6))).toMatchObject({ dataUrls: expect.any(Map), truncated: true })
+ expect(fetcher.fetchOptions()).toEqual(expect.objectContaining({ redirect: 'manual' }))
+})
+```
+
+- [ ] **Step 2: Run tests and observe failures**
+
+Run `npx vitest run src/core/github/client.test.ts src/core/github/avatar-fetcher.test.ts src/core/github/request-coordinator.test.ts`
+
+- [ ] **Step 3: Implement the strict REST surface**
+
+Use `Accept: application/vnd.github+json`, `X-GitHub-Api-Version: 2022-11-28`, `redirect: 'manual'`, a bounded timeout, and endpoint builders that accept only canonical `owner/repository`. Decode only required fields. Implement `listIssues`, `getIssue`, `updateIssue`, `listRepositoryLabels`, and `createLabel` for Pull Request 1. Keep the full contract type ready for Pull Request 2 without registering unused renderer actions.
+
+```ts
+export class GitHubIssuesClient {
+ listIssues(repository: string, options: ListIssueOptions): Promise<IssuePageResult>
+ getIssue(repository: string, issueNumber: number): Promise<GitHubIssue>
+ updateIssue(repository: string, issueNumber: number, input: UpdateIssueInput): Promise<GitHubIssue>
+ listRepositoryLabels(repository: string, page: PageRequest): Promise<LabelPageResult>
+ createLabel(repository: string, input: CreateLabelInput): Promise<GitHubLabel>
+}
+```
+
+Implement `GitHubAvatarFetcher` separately. Accept only exact HTTPS `avatars.githubusercontent.com` URLs supplied by validated user records. Fetch only visible-page users, use `redirect: 'manual'`, accept PNG, JPEG, GIF, or WebP, stop each response at 128 KiB, stop a renderer page at 512 KiB, and return initials for every skipped or failed avatar. Keep only a short bounded memory cache.
+
+- [ ] **Step 4: Implement identity-wide coordination**
+
+Allow four reads per authenticated user id. Serialize writes and start them at least 1,000 ms apart. Apply primary reset and secondary `retry-after` to every repository using that identity. `cancelIdentity` rejects queued work with `configuration-changed`.
+
+- [ ] **Step 5: Run focused tests and commit**
+
+Run `npx vitest run src/core/github/client.test.ts src/core/github/avatar-fetcher.test.ts src/core/github/request-coordinator.test.ts`
+
+```bash
+git add src/core/github/client.ts src/core/github/client.test.ts src/core/github/avatar-fetcher.ts src/core/github/avatar-fetcher.test.ts src/core/github/request-coordinator.ts src/core/github/request-coordinator.test.ts src/shared/github-issues.ts
+git commit -m "feat: add bounded GitHub issues client"
+```
+
+### Task 4: Private cache, reconciliation, and paged issue service
+
+**Files:**
+- Create: `src/core/github/cache.ts`
+- Create: `src/core/github/cache.test.ts`
+- Create: `src/core/github/service.ts`
+- Create: `src/core/github/service.test.ts`
+- Modify: `src/shared/github-issues.ts`
+
+**Interfaces:**
+- Produces: `GitHubIssueService.subscribe`, `unsubscribe`, `query`, `refresh`, `createMissingLabels`, and `moveIssue`.
+- Consumes: approved configuration epoch, resolver, client, coordinator, workspace lookup, cache, clock, and platform broadcaster.
+
+- [ ] **Step 1: Write failing cache and reconciliation tests**
+
+```ts
+it('retains lastComplete when the next refresh exceeds a limit', async () => {
+ await cache.saveComplete('user:o/r', completeSnapshot([issueFixture(1)]))
+ await cache.saveIncompleteAttempt('user:o/r', { reason: 'issue-limit', observedAt: 2 })
+ expect((await cache.load('user:o/r')).lastComplete?.issues.map((i) => i.number)).toEqual([1])
+})
+
+it('shares one poll across visible subscribers', async () => {
+ service.subscribe(1, request)
+ service.subscribe(2, request)
+ expect(clock.activeIntervals()).toHaveLength(1)
+ service.unsubscribe(1, request.projectId)
+ expect(clock.activeIntervals()).toHaveLength(1)
+ service.unsubscribe(2, request.projectId)
+ expect(clock.activeIntervals()).toHaveLength(0)
+})
+```
+
+- [ ] **Step 2: Run tests and observe failures**
+
+Run `npx vitest run src/core/github/cache.test.ts src/core/github/service.test.ts`
+
+- [ ] **Step 3: Implement atomic complete and incomplete cache slots**
+
+Key cache files by a SHA-256 hash of authenticated user id and repository. Persist mode `0600` through temporary-file plus rename. Store bounded issue fields, identity-scoped ETags, rate metadata, `lastSuccessfulRefreshAt`, `lastFullReconciliationAt`, `lastComplete`, and `lastAttempt`. Reject malformed cache files and documents above 64 MiB.
+
+- [ ] **Step 4: Implement refresh, mapping, paging, and deltas**
+
+```ts
+export class GitHubIssueService {
+ subscribe(uiId: number, request: GitHubSubscribeRequest): Promise<GitHubRepositoryStatus>
+ unsubscribe(uiId: number, projectId: string): void
+ query(request: GitHubIssueQuery): Promise<GitHubIssuePage>
+ refresh(request: GitHubRefreshRequest): Promise<GitHubRepositoryStatus>
+ createMissingLabels(request: CreateMappedLabelsRequest): Promise<CreateMappedLabelsResult>
+ moveIssue(request: MoveGitHubIssueRequest): Promise<GitHubMutationResult>
+}
+```
+
+Use complete `state=all` pagination for empty or 24-hour-old full caches. Otherwise use `since = lastSuccessfulRefreshAt - 2 seconds`. Merge by issue number and `updated_at`. A complete refresh may remove absent issues; an incremental or incomplete refresh may not. Query by column, source label filter, search, cursor, and page size up to 50. Resolve avatars lazily only for users on the returned page and enforce the aggregate page budget. Broadcast changed ids, counts, readiness, and timing only.
+
+- [ ] **Step 5: Implement epoch-safe mutations**
+
+Capture `localApprovalId`, project id, repository, mapping revision, control revision, credential generation, and user id. Revalidate inside the issue chain before fetch, before write, and before applying or persisting the confirmed result. Fetch the latest issue and compare `expectedUpdatedAt`. Preserve unrelated labels. Replace all mapped labels with the destination label. Set `state: closed` in the completion column and `state: open` outside it. On a confirmed write followed by cache failure, return `refresh-pending` without repeating the write.
+
+- [ ] **Step 6: Run focused tests and commit**
+
+Run `npx vitest run src/core/github/cache.test.ts src/core/github/service.test.ts`
+
+```bash
+git add src/core/github/cache.ts src/core/github/cache.test.ts src/core/github/service.ts src/core/github/service.test.ts src/shared/github-issues.ts
+git commit -m "feat: sync GitHub issues with Kanban state"
+```
+
+### Task 5: Electron, Server Edition, preload, and relay boundaries
+
+**Files:**
+- Create: `src/core/github/handlers.ts`
+- Create: `src/core/github/handlers.test.ts`
+- Modify: `src/shared/ipc.ts`
+- Modify: `src/shared/types.ts`
+- Modify: `src/preload/index.ts`
+- Modify: `src/preload/index.d.ts`
+- Modify: `src/preload/index.test.ts`
+- Modify: `src/main/index.ts`
+- Modify: `src/main/platform-electron.ts`
+- Modify: `src/main/platform-electron.test.ts`
+- Modify: `src/server/index.ts`
+- Modify: `src/server/handlers/index.ts`
+- Modify: `src/server/platform-server.test.ts`
+- Modify: `src/renderer/bridge/ws-bridge.ts`
+- Modify: `src/renderer/bridge/ws-bridge.test.ts`
+- Modify: `src/renderer/bridge/relay-api.ts`
+- Modify: `src/renderer/bridge/relay-api.test.ts`
+
+**Interfaces:**
+- Produces: `window.nodeTerminal.githubIssues` for core-bound issue operations and `window.nodeTerminal.githubControl` for host-only control operations.
+- Consumes: `GitHubIssueService`, `GitHubControlStore`, credential adapters, workspace lookup, and existing RPC transport.
+
+- [ ] **Step 1: Write failing bridge and security tests**
+
+```ts
+it('denies raw relay calls to githubControl channels', async () => {
+ const result = await electron.dispatch(1_000_001, { t: 'req', id: 1, method: IPC.githubControlApprove, args: [] })
+ expect(result).toMatchObject({ ok: false, error: { code: 'E_FORBIDDEN' } })
+})
+
+it('exposes domain data but never a credential', async () => {
+ const status = await api.githubIssues.status('project-1')
+ expect(JSON.stringify(status)).not.toMatch(/token|bearer|authorization/i)
+})
+```
+
+- [ ] **Step 2: Run contract tests and observe failures**
+
+Run `npx vitest run src/core/github/handlers.test.ts src/preload/index.test.ts src/main/platform-electron.test.ts src/server/platform-server.test.ts src/renderer/bridge/ws-bridge.test.ts src/renderer/bridge/relay-api.test.ts`
+
+- [ ] **Step 3: Add IPC constants and typed APIs**
+
+Register subscribe, unsubscribe, query, refresh, move, mapped-label setup, clear cache, and repository detection through `platform().handle` or `on`. Register control status, approve, revoke, provider select, token save, and token clear as raw local-window Electron handlers. Server Edition registers its control surface for its authenticated browser client.
+
+- [ ] **Step 4: Enforce relay denial and locality**
+
+```ts
+export function isHostControlChannel(method: string): boolean {
+ return method.startsWith('githubControl:')
+}
+```
+
+Return `E_FORBIDDEN` before Electron generic handler lookup for every host-control method. `buildRelayApi` keeps `githubControl` local and routes `githubIssues` through the relay frame transport. Electron-managed SSH repository discovery uses the existing remote Git executor, while credentials, cache, and GitHub HTTP remain on Electron.
+
+- [ ] **Step 5: Run contract tests and commit**
+
+Run the Task 5 focused command again and require all tests to pass.
+
+```bash
+git add src/core/github/handlers.ts src/core/github/handlers.test.ts src/shared/ipc.ts src/shared/types.ts src/preload src/main/index.ts src/main/platform-electron.ts src/main/platform-electron.test.ts src/server src/renderer/bridge
+git commit -m "feat: bridge GitHub issues safely"
+```
+
+### Task 6: Native Settings experience
+
+**Files:**
+- Create: `src/renderer/components/settings/sections/GitHubIssuesSection.tsx`
+- Create: `src/renderer/components/settings/sections/GitHubIssuesSection.test.tsx`
+- Modify: `src/renderer/components/settings/nav.ts`
+- Modify: `src/renderer/components/settings/nav.test.ts`
+- Modify: `src/renderer/components/settings/search.test.ts`
+- Modify: `src/renderer/components/settings/SettingsPage.tsx`
+- Modify: `src/renderer/components/settings/SettingsIcons.tsx`
+- Modify: `src/renderer/styles.css`
+
+**Interfaces:**
+- Produces: project-aware GitHub setup, write-only token actions, approval, mapping, completion choice, label setup, refresh, and cache clear controls.
+- Consumes: active project, `setProjectKanban`, `githubControl`, `githubIssues`, `SettingsSection`, `SearchableRow`, `FieldRow`, `Input`, `Select`, `Button`, and `ConfirmDialog`.
+
+- [ ] **Step 1: Write failing Settings DOM tests**
+
+```tsx
+it('clears the token field after Save and never reads a stored token', async () => {
+ renderGitHubSettings({ auth: { provider: 'token', tokenPresent: true } })
+ await user.type(screen.getByLabelText('Personal access token'), 'github_pat_secret')
+ await user.click(screen.getByRole('button', { name: 'Save token' }))
+ expect(screen.getByLabelText('Personal access token')).toHaveValue('')
+ expect(githubControl.saveToken).toHaveBeenCalledWith('github_pat_secret')
+ expect(JSON.stringify(githubControl.status.mock.results)).not.toContain('github_pat_secret')
+})
+```
+
+Add cases for CLI authenticated, unauthenticated, keyring warning, project approval, repository change reapproval, invalid mappings, permission errors, and label-setup confirmation.
+
+- [ ] **Step 2: Run focused Settings tests and observe failures**
+
+Run `npx vitest run src/renderer/components/settings/sections/GitHubIssuesSection.test.tsx src/renderer/components/settings/nav.test.ts src/renderer/components/settings/search.test.ts`
+
+- [ ] **Step 3: Implement the section in the existing style**
+
+Place `GitHub Issues` in the Workspace Settings group. Use the existing section shell and field rows. Show detected origin plus manual override, `Auto`, `GitHub CLI only`, and `Personal access token only`, write-only token entry, exact permission help, explicit local approval, one mapping row per current column, completion selector, readiness status, `Create missing labels`, `Refresh`, `Clear cached GitHub data`, and `Revoke this machine`.
+
+- [ ] **Step 4: Run focused tests and commit**
+
+```bash
+npx vitest run src/renderer/components/settings/sections/GitHubIssuesSection.test.tsx src/renderer/components/settings/nav.test.ts src/renderer/components/settings/search.test.ts
+git add src/renderer/components/settings src/renderer/styles.css
+git commit -m "feat: add GitHub Issues settings"
+```
+
+### Task 7: Mixed board cards, paging, and source filter
+
+**Files:**
+- Create: `src/renderer/state/githubIssues.ts`
+- Create: `src/renderer/state/githubIssues.test.ts`
+- Create: `src/renderer/components/kanban/GitHubIssueCard.tsx`
+- Create: `src/renderer/components/kanban/GitHubIssueCard.test.tsx`
+- Create: `src/renderer/components/kanban/GitHubIssueSummaryModal.tsx`
+- Create: `src/renderer/components/kanban/KanbanSourceFilter.tsx`
+- Create: `src/renderer/components/kanban/KanbanSourceFilter.test.tsx`
+- Modify: `src/renderer/components/kanban/KanbanView.tsx`
+- Modify: `src/renderer/components/kanban/KanbanColumn.tsx`
+- Modify: `src/renderer/components/kanban/LabelChips.tsx`
+- Modify: `src/renderer/styles.css`
+
+**Interfaces:**
+- Produces: paged GitHub cards mixed into columns, namespaced GitHub label filtering, safe summary modal, `Show more`, and `All`, `GitHub`, `Sessions` filtering.
+- Consumes: `GitHubIssuePage`, native sessions, board columns, source-neutral column counts, and the core API.
+
+- [ ] **Step 1: Write failing renderer tests**
+
+```tsx
+it('filters sources without changing the board configuration', async () => {
+ renderBoard({ sessions: [sessionCard()], github: [issueCard()] })
+ await user.click(screen.getByRole('button', { name: 'GitHub' }))
+ expect(screen.getByText('#42 Fix polling')).toBeVisible()
+ expect(screen.queryByText('Local session')).toBeNull()
+ expect(onChange).not.toHaveBeenCalled()
+})
+```
+
+Add cases for mixed stable order, closed completion placement, unmatched and conflicting issues in `Ungrouped`, namespaced same-name labels, accurate filtered counts, `Show more`, cached and stale states, modal focus restoration, and a 390px DOM layout class.
+
+- [ ] **Step 2: Run renderer tests and observe failures**
+
+Run `npx vitest run src/renderer/state/githubIssues.test.ts src/renderer/components/kanban/GitHubIssueCard.test.tsx src/renderer/components/kanban/KanbanSourceFilter.test.tsx`
+
+- [ ] **Step 3: Implement bounded renderer state**
+
+Subscribe only while the Kanban view is visible. Keep pages keyed by project, column, source, search, and namespaced label filter. Requery affected visible pages on bounded service deltas. Unsubscribe and clear provisional state when the project or configuration epoch changes.
+
+- [ ] **Step 4: Render the approved source-filter design**
+
+Use discriminated cards without changing the native `KanbanSession` contract. A GitHub card shows issue number, title, open or closed state, mapped and ordinary labels, up to three bounded avatars, update age, conflict or sync state, and a GitHub source mark. Opening it shows a safe summary, movement controls, and `Open on GitHub`. Markdown images are links, not images.
+
+- [ ] **Step 5: Run focused tests and commit**
+
+```bash
+npx vitest run src/renderer/state/githubIssues.test.ts src/renderer/components/kanban/GitHubIssueCard.test.tsx src/renderer/components/kanban/KanbanSourceFilter.test.tsx
+git add src/renderer/state/githubIssues.ts src/renderer/state/githubIssues.test.ts src/renderer/components/kanban src/renderer/styles.css
+git commit -m "feat: show GitHub issues on Kanban"
+```
+
+### Task 8: Accessible two-way movement, conflict resolution, close, and reopen
+
+**Files:**
+- Modify: `src/core/github/service.test.ts`
+- Modify: `src/renderer/state/githubIssues.ts`
+- Modify: `src/renderer/state/githubIssues.test.ts`
+- Modify: `src/renderer/components/kanban/GitHubIssueCard.tsx`
+- Modify: `src/renderer/components/kanban/GitHubIssueCard.test.tsx`
+- Modify: `src/renderer/components/kanban/KanbanColumn.tsx`
+- Modify: `src/renderer/components/kanban/KanbanView.tsx`
+- Modify: `src/renderer/styles.css`
+
+**Interfaces:**
+- Produces: pointer drag and `Move to` parity with provisional, confirmed, stale, conflict, failed, and refresh-pending states.
+- Consumes: `GitHubIssueService.moveIssue`, `expectedUpdatedAt`, and mapped column definitions.
+
+- [ ] **Step 1: Write failing end-to-end component and service tests**
+
+```ts
+it('reopens outside completion and preserves unrelated labels', async () => {
+ client.getIssue.mockResolvedValue(issueFixture(42, { state: 'closed', labels: ['status:done', 'bug'] }))
+ await service.moveIssue(moveRequest({ issueNumber: 42, toColumnId: 'todo', expectedUpdatedAt: '2026-08-09T10:00:00Z' }))
+ expect(client.updateIssue).toHaveBeenCalledWith('o/r', 42, {
+ state: 'open', labels: ['bug', 'status:todo']
+ })
+})
+```
+
+Add tests for close, mapped-label conflicts, open issue with completion label, stale data, approval revocation while queued, mapping change before write, failed rollback, successful write plus cache failure, pointer movement, keyboard `Move to`, and focus restoration.
+
+- [ ] **Step 2: Run focused tests and observe failures**
+
+Run `npx vitest run src/core/github/service.test.ts src/renderer/state/githubIssues.test.ts src/renderer/components/kanban/GitHubIssueCard.test.tsx`
+
+- [ ] **Step 3: Implement provisional movement and conflict actions**
+
+On movement, retain the last confirmed card and mark only that card `syncing`. A stale response installs the latest issue and requires a new user action. A failure restores the confirmed column and keeps an actionable error. Conflict cards expose explicit target choices and never silently select among multiple mapped labels.
+
+- [ ] **Step 4: Run focused tests and commit**
+
+```bash
+npx vitest run src/core/github/service.test.ts src/renderer/state/githubIssues.test.ts src/renderer/components/kanban/GitHubIssueCard.test.tsx
+git add src/core/github/service.test.ts src/renderer/state/githubIssues.ts src/renderer/state/githubIssues.test.ts src/renderer/components/kanban src/renderer/styles.css
+git commit -m "feat: sync GitHub issue movement"
+```
+
+### Task 9: Platform integration, privacy regression, and documentation
+
+**Files:**
+- Create: `test/server/github-issues-e2e.test.ts`
+- Create: `test/remote/github-issues-relay.test.ts`
+- Create: `docs/github-issues-kanban.md`
+- Modify: `README.md`
+- Modify: `src/main/platform-electron.test.ts`
+- Modify: `src/server/platform-server.test.ts`
+- Modify: `src/renderer/bridge/ws-bridge.test.ts`
+
+**Interfaces:**
+- Produces: deterministic host fixtures covering Electron, Server Edition, relay, and documented setup and limits.
+- Consumes: completed Pull Request 1 API and user interface.
+
+- [ ] **Step 1: Add failing platform journeys**
+
+Test local Electron handler registration, Server Edition authenticated query and move, relay issue operations with local control denial, Electron-managed SSH repository discovery with desktop credential use, no token in serialised errors, and one poll shared across clients.
+
+- [ ] **Step 2: Run platform journeys and observe failures**
+
+Run `npx vitest run test/server/github-issues-e2e.test.ts test/remote/github-issues-relay.test.ts src/main/platform-electron.test.ts src/server/platform-server.test.ts src/renderer/bridge/ws-bridge.test.ts`
+
+- [ ] **Step 3: Close integration gaps and add user documentation**
+
+Document CLI and token authentication, fine-grained token permissions, local approval, repository override, exact label mapping, completion behaviour, source filter, refresh cadence, cache location and clearing, support limits, conflict recovery, Server Edition restricted-file warning, and the deferred Pull Request 2 editor features.
+
+- [ ] **Step 4: Run platform journeys and commit**
+
+```bash
+npx vitest run test/server/github-issues-e2e.test.ts test/remote/github-issues-relay.test.ts src/main/platform-electron.test.ts src/server/platform-server.test.ts src/renderer/bridge/ws-bridge.test.ts
+git add test/server/github-issues-e2e.test.ts test/remote/github-issues-relay.test.ts docs/github-issues-kanban.md README.md src/main/platform-electron.test.ts src/server/platform-server.test.ts src/renderer/bridge/ws-bridge.test.ts
+git commit -m "test: cover GitHub Kanban integration"
+```
+
+### Task 10: Full verification and visual acceptance evidence
+
+**Files:**
+- Modify only if verification finds a defect: the smallest owning production file and its focused test.
+- Do not commit screenshots or recordings.
+
+**Interfaces:**
+- Produces: current full-suite evidence, live fixture evidence, screenshots, a short recording, and a review-ready branch.
+- Consumes: completed Pull Request 1 implementation.
+
+- [ ] **Step 1: Run static and full automated verification from a clean status**
+
+```bash
+git diff --check
+npm test
+npm run typecheck
+npm run build
+npm run server:build
+```
+
+Every command must exit zero in the current run. If one fails, use the systematic-debugging skill, add a focused regression test, fix the owning code, and rerun both the focused command and this complete block.
+
+- [ ] **Step 2: Run the deterministic fixture journey in the built application**
+
+Verify first approval, CLI and token-present states, repository override, mapped-label setup, initial and manual refresh, source filtering, paging, pointer drag, keyboard `Move to`, close, reopen, conflict resolution, stale response, rate-limited state, failed rollback, cache clearing, approval revocation, and app restart cache recovery.
+
+- [ ] **Step 3: Capture visual evidence**
+
+Capture Settings, mixed board, each source filter, summary modal, conflict, syncing, stale, rate-limited, and error states at desktop and 390px widths in dark and light themes. Record refresh, movement, close, reopen, filtering, failed rollback, and a keyboard-only essential journey. Compress and attach these to the pull request without adding them to Git.
+
+- [ ] **Step 4: Perform a live GitHub check within explicit authority**
+
+If an authorised test repository is available, verify create-missing-labels, read, move, close, and reopen against it and restore its intended final state. Otherwise perform only a live read-only refresh and retain write evidence from the controlled HTTP fixture.
+
+- [ ] **Step 5: Review the final diff and commit any evidence-driven fix**
+
+Run `git status --short`, `git diff --stat origin/main...HEAD`, and `git diff origin/main...HEAD`. Confirm `.superpowers/` and all media captures are untracked and excluded. Commit only source, tests, and documentation.
+
+### Task 11: Sol review, publication, and pull-request checks
+
+**Files:**
+- No planned product changes. Any review fix must add or update the owning focused test.
+
+**Interfaces:**
+- Produces: pushed branch and a checked pull request.
+- Consumes: clean verified branch and visual evidence links.
+
+- [ ] **Step 1: Request a read-only Sol code review**
+
+Ask Sol to review `origin/main...HEAD` for correctness, security, tests, accessibility, and design fidelity. Resolve every Critical and Important finding with a red and green focused test, then repeat full verification.
+
+- [ ] **Step 2: Publish intentionally**
+
+Use the `github:yeet` skill. Confirm the diff scope, push `feat/github-issues-kanban-sync`, and open a pull request against `main` with the approved design summary, security model, automated results, live or fixture limitation, screenshots, and recording.
+
+- [ ] **Step 3: Wait for GitHub checks and address failures**
+
+Use the `github:gh-fix-ci` skill for any failing GitHub Actions check. Do not merge in this task unless the user separately asks for merge.
diff --git a/docs/superpowers/specs/2026-08-09-github-issues-kanban-sync-design.md b/docs/superpowers/specs/2026-08-09-github-issues-kanban-sync-design.md
new file mode 100644
index 000000000..59aab8bf6
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-09-github-issues-kanban-sync-design.md
@@ -0,0 +1,628 @@
+# GitHub Issues Kanban Sync
+
+**Date** 9 August 2026
+
+**Status** Amended after Sol architecture review, awaiting final written specification review
+
+## Purpose
+
+Add an optional, per-project GitHub Issues integration to nodeterm. Repository issues will appear beside native session cards in the existing Kanban. GitHub remains canonical, while nodeterm provides a fast board, a full issue editor, and controlled two-way changes.
+
+The feature must feel native to nodeterm, work through the existing Electron and Server Edition platform seams, keep credentials outside shared project data, and never claim that an unconfirmed GitHub change has synchronised.
+
+## Confirmed product decisions
+
+### Source of truth
+
+- GitHub is canonical for issue title, body, comments, state, state reason, labels, assignees, milestone, lock state, timestamps, and permissions.
+- Nodeterm keeps a machine-local read cache for quick startup and offline reading.
+- Offline writes are not supported.
+- A local mutation is not shown as complete until GitHub confirms it.
+- A newer upstream version produces a visible stale-data conflict instead of an automatic overwrite.
+- GitHub has no atomic compare-and-swap operation for general issue edits. Conflict detection is therefore best effort and must not be described as stronger than the API permits.
+
+### Repository scope
+
+- One GitHub repository may be connected to each nodeterm project.
+- The repository is detected from the project's Git remote.
+- The user may override the detected value with an explicit `owner/repository` value.
+- All repository issues are included, open and closed.
+- Pull requests returned by GitHub's issues endpoint are excluded.
+- Native nodeterm session cards and GitHub issue cards coexist on the same board.
+- A board-wide source filter offers `All`, `GitHub`, and `Sessions`. `All` is the default.
+
+### Authentication
+
+- Reuse an existing authenticated GitHub CLI session when available.
+- Offer a write-only fine-grained personal access token as a fallback.
+- Prefer the GitHub CLI credential when both are available unless the user deliberately chooses the stored token.
+- Store that provider choice as non-secret app configuration with `auto`, `gh`, and `token` values. `auto` is the default and prefers `gh`.
+- Store provider choice in a dedicated machine-local GitHub control store and expose all three values in the GitHub Issues settings section.
+- The token needs repository Metadata read and Issues read and write permissions. The UI must explain that repository permission is also required for labels, assignees, and milestones.
+- A dedicated GitHub App device login is a future enhancement. GitHub recommends device flow for desktop applications [2].
+
+### Column mapping
+
+- Each Kanban column has one explicit GitHub label mapping.
+- A new mapping defaults to the column title.
+- One column is the completion column. The default is the existing `Done` column when present.
+- Renaming a Kanban column does not silently rename a repository-wide GitHub label.
+- A user may update the mapping deliberately in Settings.
+- A confirmed `Create missing labels` action creates absent mapped labels. Routine sync never creates, renames, or deletes repository labels.
+- Adding a Kanban column while this machine has approved the integration creates a suggested local mapping from its title. GitHub issue movement to that column remains disabled until its repository label exists.
+- Deleting a Kanban column removes its mapping. Deleting the completion column marks configuration incomplete, places closed issues in `Ungrouped`, and disables GitHub mutations until another completion column is selected.
+- Closing through nodeterm removes every other mapped label, applies the completion label, and closes the issue in one update.
+- Closed state overrides mapped labels for placement. A closed issue always appears in the completion column.
+- An externally reopened issue that retains the completion label appears in `Ungrouped` as a state-label conflict. Nodeterm does not mutate it automatically.
+- Resolving a state-label conflict through `Move to` removes every mapped label, applies the chosen non-completion label, and keeps the issue open.
+
+### Board placement
+
+- An open issue with exactly one mapped non-completion label appears in that column.
+- An open issue carrying the completion label appears in `Ungrouped` with a state-label conflict.
+- An open issue with no mapped label appears in `Ungrouped`.
+- An open issue with multiple mapped labels appears in `Ungrouped` with a conflict warning.
+- A closed issue appears in the completion column.
+- Moving an issue to a non-completion column removes other mapped labels, preserves unrelated labels, applies the destination label, and reopens the issue when necessary.
+- Moving an issue to the completion column closes it and preserves unrelated labels.
+- Native session ordering remains unchanged.
+- GitHub issue cards sort by most recent `updated_at`, then descending issue number for a stable tie-break.
+- Within a mixed column, native session cards render first in their existing stable assignment order. GitHub issue cards follow in the order above. Source filtering never changes either source's internal order.
+
+## User experience
+
+### Settings
+
+Add `GitHub Issues` under the existing `Workspace` settings group. Build the section from the same `SettingsSection`, `SearchableRow`, `FieldRow`, `Switch`, `Input`, `Select`, and `Button` components used elsewhere.
+
+The section shows
+
+- connection status and authenticated GitHub login without exposing a credential
+- a `Sign in with GitHub CLI` action using nodeterm's existing in-app terminal flow
+- a write-only token field with Save and Clear actions
+- the active project and this machine's approval state
+- detected repository and manual override
+- one label field per current Kanban column
+- completion-column selection
+- `Test connection`, `Create missing labels`, `Refresh now`, and `Clear cached GitHub data` actions
+- a clear warning if OS-backed encryption is unavailable before storing a token in the restricted-file fallback
+
+Configuration follows the active project. Switching project tabs and reopening Settings shows that project's mapping.
+
+Shared configuration never authorises network access. The first enable action on each machine creates a machine-local approval keyed by the local workspace entry, project id, and normalised repository. A repository change invalidates that approval. Opening a cloned or collaborator-supplied `.nodeterm/project.json` may display its proposed mapping, but it cannot use local credentials, read a private repository, or start polling until the local user confirms access.
+
+### Board header
+
+When this machine has approved the GitHub integration, the board header adds
+
+- `All`, `GitHub`, and `Sessions` source controls
+- last successful GitHub refresh time
+- a refresh action and progress state
+- rate-limit, authentication, stale-cache, or configuration warnings when relevant
+
+Column counts follow the active source filter. Existing label filtering continues to apply after source filtering.
+
+Local and GitHub labels occupy separate namespaces. Filter keys use `local:<labelId>` and `github:<normalisedLabelName>`. The picker groups them by source and shows a GitHub mark for GitHub labels, so equal display names never merge implicitly.
+
+### GitHub issue card
+
+A distinct `GitHubIssueCard` uses the existing Kanban spacing, borders, colors, drag affordances, and focus treatment. It shows
+
+- GitHub mark and issue number
+- title
+- mapped and ordinary labels, with overflow count
+- assignee avatars when present
+- milestone when present
+- comment count
+- open, closed, conflict, syncing, stale, or failed state
+- relative update time
+
+The card remains recognisably GitHub-backed without becoming a visually separate lane. Source filtering provides separation when wanted.
+
+### Issue modal
+
+Opening a GitHub card uses a purpose-built `GitHubIssueModal`. It does not reuse the terminal session modal.
+
+The modal supports
+
+- issue creation
+- title and Markdown body editing
+- rendered body preview
+- comment listing and pagination
+- comment creation
+- editing and deleting comments when GitHub permits it
+- label selection
+- assignee selection
+- milestone selection
+- column and state movement
+- supported close reason
+- conversation lock and unlock
+- opening the canonical GitHub page
+
+The main pane holds body and discussion. A metadata sidebar holds status, labels, assignees, milestone, and conversation state. Destructive actions require confirmation. Each mutation has an explicit saving, confirmed, stale, or failed state.
+
+### Large repositories and narrow layouts
+
+- The host issue service retains the complete validated issue set up to a documented support limit of 10,000 issues and a 64 MiB cache document.
+- Exceeding either limit produces an explicit `Repository too large` incomplete state. A failed refresh attempt never replaces or prunes the previous complete cache. That last complete snapshot remains readable, but mutations are disabled because its freshness can no longer be established. If the first refresh crosses a limit, its validated records may be exposed only as an explicitly partial, read-only snapshot and are stored separately from the complete-cache slot.
+- The renderer requests issue cards by column, filter, search query, cursor, and bounded page size. It never receives all issue bodies in one snapshot.
+- Each column initially requests 50 recent issues and offers `Show more`.
+- Search, counts, and filters execute against the complete host cache, not only the rendered page.
+- At 390px, columns retain the existing horizontally scrollable Kanban behaviour.
+- The source filter, non-drag movement control, refresh state, and issue modal remain fully usable at 390px.
+- Pointer drag is an enhancement. Every movement is also available through an accessible `Move to` control.
+
+## Architecture
+
+### Project configuration
+
+Extend `ProjectKanban` with optional non-secret GitHub configuration.
+
+```ts
+export interface ProjectKanbanGitHub {
+ repository?: string
+ columnMappings: Array<{
+ columnId: string
+ label: string
+ }>
+ completionColumnId?: string
+}
+
+export interface ProjectKanban {
+ columns: KanbanColumn[]
+ assignments: KanbanAssignment[]
+ meta?: KanbanCardMeta[]
+ labels?: KanbanLabel[]
+ github?: ProjectKanbanGitHub
+}
+```
+
+This proposed mapping is shared through `.nodeterm/project.json`. Local authorisation is not. Add a stable machine-local `localApprovalId` to each `IndexEntryV3` and keep provider choice plus approvals in a dedicated GitHub control store.
+
+```ts
+export interface GitHubProjectApproval {
+ localApprovalId: string
+ projectId: string
+ repository: string
+ enabled: boolean
+ approvedAt: number
+}
+
+export interface GitHubControlState {
+ version: 1
+ revision: number
+ authProvider: 'auto' | 'gh' | 'token'
+ approvals: GitHubProjectApproval[]
+}
+
+export interface IndexEntryV3 {
+ localApprovalId?: string
+}
+```
+
+The workspace store generates `localApprovalId` when an entry is created or first loaded without one and keeps it only in the machine-local workspace index. It preserves this value across every index save and migration. Approval and issue execution require a non-empty `localApprovalId`; they never substitute the shared project id or `IndexEntryV3.id`. The control store writes atomically, checks an expected revision on every update, and exposes dedicated transactional Approve, Revoke, Select provider, Save token, and Clear token handlers. A stale client receives a conflict and reloads instead of replacing the whole state or resurrecting a revoked approval.
+
+Credentials, approvals for other machines, issue snapshots, comments, ETags, refresh metadata, provisional mutations, and safe errors never enter the shared project file or the general Settings save path.
+
+One canonical `normaliseProjectKanbanGitHub` function validates every read and write. It
+
+- trims and validates `owner/repository`
+- bounds every label to GitHub's supported length and rejects empty names
+- compares labels by trimmed Unicode-normalised case-folded name
+- requires unique column ids and unique normalised labels
+- removes mappings to unknown columns
+- accepts a completion id only when it names a live mapped column
+- returns explicit readiness errors rather than silently inventing a winner
+
+Every board transform must preserve unrelated `ProjectKanban` properties with object spread. Column addition and deletion update mappings through the same normaliser. Round-trip tests cover old project files, malformed shared input, every board transform, duplicate mappings, case variants, unknown columns, and invalid completion ids.
+
+Readers validate every field defensively. A malformed GitHub block disables the integration without dropping the rest of the Kanban. A missing mapping degrades that issue to `Ungrouped`. A repository change invalidates its machine-local approval before any request is made.
+
+### Credential resolver
+
+A focused credential resolver runs only in the trusted host process.
+
+Resolution is exact.
+
+| Selected provider | Behaviour |
+|---|---|
+| `auto` | Validate GitHub CLI authentication first. If unavailable or rejected, validate the stored token. Report authentication required only when neither is valid. |
+| `gh` | Use only a valid GitHub CLI credential. Never fall back to the stored token. |
+| `token` | Use only the stored token. Never fall back to GitHub CLI. |
+
+The renderer may save, clear, select, and query credential presence. It may never read a token. The service must redact bearer values and token-like query parameters from every error before logging or returning it.
+
+Electron stores a pasted token encrypted with `safeStorage` only when encryption is available and `safeStorage.getSelectedStorageBackend()` does not report `basic_text`. Electron documents `basic_text` as an unprotected Linux fallback [6]. If a supported OS keyring is temporarily locked, the intact encrypted value is not overwritten. Server Edition, `basic_text`, and systems without available encryption use an atomic `0600` restricted file after explicit warning. Clearing a token removes the credential file but does not change the GitHub CLI login.
+
+### Execution locality
+
+| Project surface | Repository detection | Credential, cache, and GitHub HTTP | Approval authority |
+|---|---|---|---|
+| Local Electron project | Local Git service | Electron host | Main local window only |
+| Server Edition project | Server Git service | Server host | Authenticated server settings client |
+| Relay-hosted project | Relay host core service | Relay host | Host owner's local settings only |
+| Electron-managed SSH project | Existing remote Git executor reads the SSH repository remote | Electron host, using the desktop user's GitHub identity | Main local window only |
+| Inline project without a working directory | Manual repository override | Owning Electron or Server host | Owning host's settings client |
+
+The GitHub issue data namespace is core-bound, so a relay tab reads and mutates through the relay host. Credential Save, Clear, provider selection, and first-use approval remain host-control operations. Electron registers them through local-window handlers that verify the sender is the main window. Server Edition registers revision-checked handlers for its authenticated settings client. Relay dispatch maintains an explicit deny set for every `githubControl:*` channel before generic RPC dispatch, so an approved peer cannot invoke them by constructing a raw request. An already approved relay-hosted project may expose its bounded issue operations to authorised peers while its credential remains on the host. Electron-managed SSH support deliberately keeps the GitHub token off the SSH host. A future SSH-host credential mode would be a separate design.
+
+### GitHub issues client
+
+Create a focused REST client rather than a general arbitrary-URL proxy. It owns
+
+- authentication headers
+- the current GitHub REST API version header
+- fixed `api.github.com` endpoint construction
+- repository and issue-number validation
+- request and overall-operation timeouts
+- Link-header pagination
+- conditional GET requests with ETags
+- response-size and collection-count bounds
+- runtime response validation
+- rate-limit interpretation and backoff
+- bounded manual redirect handling
+- safe error conversion
+
+Redirects are followed manually for at most three hops. Every target must remain HTTPS on `api.github.com`. The client refuses a cross-host or protocol-changing redirect and never forwards authorisation to another origin.
+
+Its interface exposes issue-domain methods only.
+
+```ts
+interface GitHubIssuesClient {
+ listIssues(repository: string, options: ListIssueOptions): Promise<IssuePageResult>
+ getIssue(repository: string, issueNumber: number): Promise<GitHubIssue>
+ createIssue(repository: string, input: CreateIssueInput): Promise<GitHubIssue>
+ updateIssue(repository: string, issueNumber: number, input: UpdateIssueInput): Promise<GitHubIssue>
+ listComments(repository: string, issueNumber: number, page: PageRequest): Promise<CommentPageResult>
+ getComment(repository: string, commentId: number): Promise<GitHubComment>
+ createComment(repository: string, issueNumber: number, body: string): Promise<GitHubComment>
+ updateComment(repository: string, issueNumber: number, commentId: number, body: string): Promise<GitHubComment>
+ deleteComment(repository: string, issueNumber: number, commentId: number): Promise<void>
+ listRepositoryLabels(repository: string, page: PageRequest): Promise<LabelPageResult>
+ createLabel(repository: string, input: CreateLabelInput): Promise<GitHubLabel>
+ listAssignees(repository: string, page: PageRequest): Promise<UserPageResult>
+ listMilestones(repository: string, page: PageRequest): Promise<MilestonePageResult>
+ lockIssue(repository: string, issueNumber: number): Promise<void>
+ unlockIssue(repository: string, issueNumber: number): Promise<void>
+}
+```
+
+Comment updates and deletes carry project id, issue number, and `expectedCommentUpdatedAt` through the service boundary. Inside the mutation chain, the host calls `getComment` for the specific comment id, validates the response and confirms that its `issue_url` belongs to the expected repository and issue, then compares its `updated_at` with the version shown to the user. A mismatch returns the latest comment as a stale-data result and requires a deliberate retry. Comment id alone is never sufficient authority, and paginated discussion state is never used as proof that a comment is current [5].
+
+GitHub's issue API supports the core issue, label, assignee, milestone, comment, and lock operations in scope [1].
+
+### Issue service
+
+The issue service owns
+
+- per-repository cache loading and atomic persistence
+- one in-flight refresh and one poll schedule per repository
+- subscription reference counting across attached Electron, Server Edition, and relay clients
+- one request coordinator per authenticated GitHub user id across every repository
+- one serial mutation chain per issue
+- full and incremental refresh scheduling
+- mapping issues to Kanban columns
+- provisional mutation state
+- post-mutation verification
+- paged card queries, full-cache search, and bounded change broadcasts through the platform seam
+
+The service accepts injected credential, client, clock, and storage dependencies. Core tests therefore perform no network or keyring access.
+
+The first visible subscriber starts the repository poll and the last unsubscribe stops it. Multiple clients share the same timer and in-flight refresh. Refresh completion broadcasts changed issue ids, totals, readiness, and timing only. Renderers requery affected visible pages rather than receiving the entire repository.
+
+The identity-wide request coordinator permits at most four concurrent reads, serialises mutative requests, and spaces mutations by at least one second. Primary or secondary rate-limit backoff from any repository pauses polls and queued network work for every repository using that GitHub identity. A primary-limit pause lasts until reset. A secondary-limit pause follows `retry-after` or bounded exponential backoff. Identity changes cancel old queued work rather than moving it to a new credential.
+
+### Renderer state
+
+Renderer state is keyed by project id and contains
+
+- bounded visible issue pages and per-column cursors
+- complete counts and active query metadata returned by the host
+- connection and configuration readiness
+- last successful refresh
+- last full reconciliation time
+- current refresh and rate-limit state
+- provisional mutations
+- bounded safe error
+- in-memory comments for the open issue only
+
+Comments are fetched when a modal opens and are not persisted to disk. Closing the modal may keep them only for a short in-memory time-to-live.
+
+### Remote media
+
+The renderer never loads GitHub media directly. The host may fetch assignee avatars only from validated `https://avatars.githubusercontent.com` URLs returned in authenticated GitHub user objects. It fetches lazily for visible cards and the open modal, disables redirects, requests a small display size, accepts only supported image MIME types, enforces a 128 KiB response limit, and caches the result briefly in memory. Each renderer page response has a 512 KiB aggregate avatar-data budget. Users beyond that budget receive initials. The host exposes only bounded data URLs through issue view models, and every failure falls back to the existing initials avatar.
+
+Markdown images in issue bodies and comments render as labelled links rather than remote images in this release. Ordinary links are sanitised, limited to safe schemes, and opened through the existing external-link boundary. This preserves the current renderer CSP and the host-only network rule.
+
+### Components
+
+- `GitHubIssuesSection` owns Settings presentation.
+- `GitHubIssueCard` owns GitHub card presentation and accessible card actions.
+- `GitHubIssueModal` owns the issue editor and discussion.
+- `KanbanSourceFilter` owns `All`, `GitHub`, and `Sessions` selection.
+- `KanbanColumn` renders a discriminated union of native and GitHub cards while keeping source-specific behaviours isolated.
+- Pure mapping and filtering helpers stay outside React.
+
+## Data flow
+
+### Initial load and refresh
+
+1. Opening the Kanban validates shared configuration and checks machine-local approval before reading even a private local cache.
+2. An approved project reads the machine-local cache and renders the first bounded pages immediately.
+3. If configuration and authentication are ready, the host service records a configuration epoch containing `localApprovalId`, project id, normalised repository, mapping revision, control-store revision, credential generation, and authenticated GitHub user id, then starts a refresh.
+4. An empty cache or a cache whose separate `lastFullReconciliationAt` is older than 24 hours receives a complete `state=all` paginated refresh.
+5. A recent full cache receives an incremental refresh using `since = lastSuccessfulRefreshAt - 2 seconds`. Results merge by issue number and `updated_at`, so the overlap is harmless and second-resolution boundary updates are not lost.
+6. Conditional requests use stored ETags where the request identity is stable. The ETag key includes normalised repository, endpoint, API version, complete query, page, and authenticated GitHub user id. It never includes credential material. Correctly authenticated `304` responses do not count against the primary REST limit [3].
+7. Valid issues merge by repository and issue number.
+8. Pull-request records are discarded before reaching the cache or renderer.
+9. Before applying results, the service compares the captured configuration epoch with the current epoch. A repository, mapping, approval, or identity change discards the stale result.
+10. A complete result atomically replaces the complete-cache slot. An incomplete result records bounded attempt metadata separately and does not replace or prune the previous complete snapshot. The service then broadcasts bounded change metadata.
+
+The first visible subscriber starts one host-owned 60-second poll per repository. Refresh also occurs when the owning window regains focus after the snapshot is stale. The last unsubscribe stops polling. A manual refresh forces a complete reconciliation. Only a complete successful fetch may remove cache entries no longer returned upstream, and only a complete successful fetch advances `lastFullReconciliationAt`.
+
+### Mutation flow
+
+1. Validate the project configuration, issue identity, requested fields, and input bounds, then capture the complete configuration epoch.
+2. Enter the issue's local serial mutation chain.
+3. Recompute the epoch inside the chain before any network request. Reject the work if approval, repository, mapping, provider, credential generation, or authenticated identity changed.
+4. Fetch the latest issue through the identity-wide request coordinator.
+5. Compare its `updated_at` with the version shown to the user.
+6. Return a stale-data result when they differ. Refresh the card and require a deliberate retry.
+7. Compute the smallest safe mutation from the fresh record.
+8. Recompute and compare the epoch immediately before the write.
+9. Submit the GitHub request through the identity-wide mutation queue.
+10. Validate the confirmed response and compare fields that GitHub can silently ignore when repository permission is insufficient.
+11. Update the in-memory snapshot as confirmed.
+12. Revalidate the epoch before the post-write refresh. If it changed after GitHub confirmed the write, report the confirmed result without applying it to the new configuration.
+13. Refresh the affected issue, persist the cache, and broadcast the result.
+
+The UI may show a provisional location with a `Syncing` state. Failure restores the last confirmed position. A successful GitHub write followed by a cache failure returns the confirmed issue with `Refresh pending`, then heals on the next refresh without repeating the write.
+
+Every issue, comment, label-setup, creation, lock, unlock, and movement operation follows this epoch protocol. An epoch change cancels queued work before its next request. Multi-request setup actions revalidate immediately before every request and report confirmed partial completion without continuing under a changed epoch.
+
+### Column movement
+
+For an open issue moved between non-completion columns
+
+1. Fetch the current issue.
+2. Preserve all labels not used by a column mapping.
+3. Remove every mapped column label.
+4. Add the destination label.
+5. Send the resulting label set in one issue update.
+
+Moving to completion performs the same preservation and mapped-label replacement, applies the completion label, and sets state to closed in one issue update. Moving out of completion sets state to open, removes the completion and every other mapped label, and applies the destination mapping. An externally reopened issue that still carries the completion label remains an `Ungrouped` conflict until a user chooses a non-completion destination. Closed state always wins placement, even when the issue has no completion label or has stale mapped labels.
+
+### Issue creation and mapped-label setup
+
+The board header offers `New GitHub issue`, defaulting to the first mapped non-completion column. Each non-completion column also offers `New GitHub issue here`. Creation in the completion column is disabled because GitHub's create endpoint creates an open issue and a second close request would introduce a partial-write state.
+
+The create request sends title, body, destination mapped label, selected ordinary labels, assignees, and milestone in one GitHub operation. It is disabled until the destination label exists. If GitHub confirms creation but local cache persistence fails, the confirmed issue number is retained in memory as `Refresh pending` and the create request is never repeated automatically.
+
+`Create missing labels` lists every exact pending label and colour in its confirmation. Each label colour derives from the mapped Kanban column's six-digit hex colour without `#`; an invalid or non-hex column colour uses the fixed fallback `8b5cf6`. The action relists repository labels before every create, compares names case-insensitively, and treats an already-created match as success. Partial completion reports exactly which labels were created and which remain.
+
+## Cache and retention
+
+- Store one cache document per repository under the host's nodeterm user-data directory, with separate `lastComplete` and `lastAttempt` sections.
+- Derive filenames from a stable hash rather than raw repository text.
+- Create and replace cache files atomically with mode `0600` because issue bodies may contain private project information.
+- Store bounded issue fields, identity-scoped ETags, last incremental and full refresh times, and rate-limit metadata in `lastComplete`. An incomplete `lastAttempt` stores only its status, limit reason, timing, and a bounded first-refresh partial snapshot when no complete snapshot exists.
+- Do not store comments, credentials, raw HTTP bodies, arbitrary response headers, provisional changes, or stack traces.
+- `Clear cached GitHub data` removes the active repository cache after confirmation.
+- Revoking this machine's approval stops network activity and cache reads for that project but retains the cache until the user clears it.
+
+## Error handling
+
+| Failure | Behaviour |
+|---|---|
+| Shared configuration lacks local approval | No cache read, credential use, or network request until explicit local confirmation |
+| No GitHub authentication | Cached board remains read-only with a Settings action |
+| Token rejected | Clear authentication guidance without returning token material |
+| Repository unavailable or private without access | Cached board remains and configuration is marked unavailable |
+| Insufficient write permission | Mutation fails, confirmed card remains, and required permission is explained |
+| Network timeout | Cache remains with stale time and manual retry |
+| Malformed or oversized response | Reject that response and preserve the last valid cache |
+| Repository exceeds the 10,000 issue or 64 MiB support limit | Retain the previous complete cache without pruning, record the attempt as incomplete, and disable mutations. A first-refresh partial snapshot is labelled partial and remains read-only |
+| Primary rate limit | Stop polling until `x-ratelimit-reset` |
+| Secondary rate limit | Honour `retry-after` or exponential backoff and stop after a bounded retry count |
+| Stale displayed issue | Refresh the card and require deliberate retry |
+| Multiple mapped labels | Show an `Ungrouped` conflict card and block implicit movement |
+| Open issue retains the completion label | Show an `Ungrouped` state-label conflict until an explicit non-completion move |
+| GitHub write rejected | Restore provisional UI and show persistent actionable error |
+| GitHub write confirmed but cache write fails | Show confirmed data with `Refresh pending` and do not repeat the mutation |
+| Project mapping becomes invalid | Disable sync for that project without damaging native Kanban data |
+
+GitHub warns that continued requests during a rate limit may lead to an integration ban. The service must stop and respect the supplied reset or retry time [4].
+
+## Security and privacy
+
+- All GitHub network requests run in the trusted host process.
+- Shared project configuration is treated as untrusted input and cannot activate credentials, cache reads, or requests without the matching machine-local approval.
+- The renderer receives domain objects, never bearer credentials or arbitrary GitHub responses.
+- IPC validates project id, repository, issue number, comment id, collection sizes, text lengths, enum values, and URLs.
+- Comment edit and delete requests bind project, repository, issue number, and comment id, verify the trusted comment's `issue_url`, and use the issue mutation chain.
+- The client permits only `api.github.com` and validates canonical links against `github.com/<owner>/<repository>`.
+- Redirects remain bounded to HTTPS on `api.github.com`; authorisation is never forwarded across origins.
+- Repository configuration cannot become an arbitrary server-side request URL.
+- HTML and Markdown originating on GitHub are sanitised through the existing renderer boundary before display.
+- Issue titles, bodies, labels, comments, assignee names, and avatars render as untrusted data.
+- Avatars pass through the bounded host fetcher. Markdown images never load remotely in the renderer.
+- Logs may include repository, issue number, operation, HTTP status, and rate-limit timing. They may not include token values, request bodies, issue bodies, comments, authentication headers, or raw GitHub error payloads.
+- Credential status reports presence and provider only.
+- PAT input is cleared from component state immediately after Save.
+- Electron's `basic_text` safeStorage backend is treated as unavailable and triggers the explicit restricted-file warning.
+- The PAT is never written to `settings.json`, `.nodeterm/project.json`, the issue cache, tests, screenshots, recordings, or pull-request text.
+
+## Testing strategy
+
+### Unit tests
+
+- repository parsing for HTTPS, SSH, missing, malformed, non-GitHub, and overridden remotes
+- machine-local approval, repository-change invalidation, and a hostile cloned project that cannot activate cache or network access
+- exact `Auto`, `GitHub CLI only`, and `Personal access token only` fallback behaviour, persisted provider choice, write-only behaviour, locked keyring handling, `basic_text`, restricted-file mode, migration, and redaction
+- control-store revision conflicts, atomic writes, `localApprovalId` generation and preservation through index saves and migrations, rejection when it is absent, repository-change invalidation, and proof that a copied project id or stale client cannot restore a revoked approval
+- canonical mapping normalisation, duplicate column ids, case-variant labels, empty labels, unknown columns, invalid completion id, and property preservation through every board transform
+- issue, comment, label, assignee, and milestone response validation
+- pagination, Link headers, pull-request filtering, periodic full reconciliation, overlapping incremental boundaries, identity-scoped ETags, `304`, epoch invalidation, timeouts, malformed JSON, and bounded responses
+- bounded same-host redirects and rejection of cross-host or protocol-changing redirects
+- identity-wide read concurrency, mutation spacing, primary and secondary rate-limit handling across repositories, identity changes, and queued-work cancellation
+- status mapping for open, closed, unlabelled, single-labelled, mapped-label conflicts, and externally reopened completion-label conflicts
+- unrelated-label preservation and exact mapped-label replacement
+- completion-label close and reopen transitions
+- stable mixed-source ordering and namespaced local and GitHub label filtering
+- cache atomicity, mode, retention, corrupt-file recovery, last-complete preservation after an incomplete refresh, and an explicitly partial first refresh
+- repository support-limit behaviour, paged queries, delta broadcasts, and one poll timer across multiple subscribers
+- direct comment fetch validation, comment-to-issue association checks, comment-level `updated_at` conflicts, deliberate retry, and same-issue serialisation
+- avatar host validation, disabled redirects, lazy loading, per-image and aggregate page limits, fallback initials, and blocked Markdown images
+- issue creation placement, disabled completion creation, missing-label colours, idempotent setup, and partial setup recovery
+- epoch revalidation before every queued network request, before every write, and before applying or persisting post-write data
+- successful write followed by cache failure without duplicate mutation
+
+### Renderer and DOM tests
+
+- Settings navigation and search entry
+- GitHub CLI, token-present, unauthenticated, keyring-warning, and insufficient-permission states
+- explicit first-use approval and repository-change reapproval
+- token field clears after Save and cannot read back a secret
+- project repository override and per-column mapping
+- label setup confirmation
+- mixed card rendering and `All`, `GitHub`, and `Sessions` filtering
+- grouped namespaced label filtering when local and GitHub labels share a display name
+- filtered column counts
+- cached, refreshing, stale, rate-limited, conflict, provisional, confirmed, and failed card states
+- pointer drag and non-drag movement parity
+- open-with-completion-label conflict resolution
+- keyboard access and focus restoration after movement
+- issue creation and editing
+- comment create, edit, delete, and pagination
+- assignee, label, milestone, state, and lock controls
+- desktop and 390px layouts
+
+### Platform and integration tests
+
+- Electron preload contract
+- WebSocket bridge contract
+- Server Edition handler contract
+- remote clients can invoke allowed issue operations while credentials remain host-only
+- local Electron, Server Edition, relay-hosted, Electron-managed SSH, and inline-project locality follow the execution matrix
+- relay peers cannot save credentials or grant first-use approval, including attempts through raw generic RPC dispatch
+- settings and cache paths stay on the host that performs GitHub requests
+- no token appears in serialised RPC results or safe errors
+
+### Fresh verification
+
+Run
+
+```sh
+npm test
+npm run typecheck
+npm run build
+```
+
+Then verify the running application with deterministic fixture data and, when a safe test repository is available, a real authenticated journey covering
+
+- initial and manual refresh
+- issue creation
+- title and body editing
+- comment creation and editing
+- label, assignee, and milestone changes
+- drag movement and `Move to`
+- close and reopen
+- source filtering
+- stale-data conflict
+- failed mutation rollback
+- token clearing and cache clearing
+
+Do not mutate the upstream nodeterm repository merely to obtain test evidence. If no authorised test repository is available, perform a live read-only refresh and keep write verification against the controlled HTTP fixture.
+
+### Visual evidence
+
+Capture screenshots of
+
+- GitHub Settings
+- mixed board and each source filter
+- issue modal
+- conflict, syncing, stale, rate-limited, and error states
+- desktop and 390px widths
+- dark and light application themes
+- existing Kanban before and after the integration
+
+Record a short pointer journey covering refresh, create, edit, comment, move, close, reopen, filtering, and failed-mutation rollback. Record or capture a keyboard-only journey for the essential actions.
+
+Attach compressed screenshots and recordings to the relevant pull request or its test evidence. Do not commit large binary captures. These complement behavioural tests. A new cross-platform pixel-diff framework is outside this feature series because nodeterm has no current visual-regression harness and Electron font rendering would make an initial baseline noisy.
+
+## Delivery
+
+Deliver the approved design as two independently reviewable pull requests. Both remain opt-in through machine-local approval.
+
+### Pull request 1
+
+Build the complete Kanban sync foundation and the core two-way board journey.
+
+1. shared configuration, canonical normalisation, and machine-local trust overlay
+2. credential storage and resolution
+3. GitHub client, cache, paging, reconciliation, and host-owned subscriptions
+4. Electron, Server Edition, relay, and SSH locality contracts
+5. GitHub Settings
+6. read-only issue cards, counts, search, namespaced filters, and source filtering
+7. mapped-label setup, drag and `Move to`, conflict resolution, close, and reopen
+8. accessibility, responsive behaviour, documentation, screenshots, recording, and verification
+
+This pull request satisfies the original two-way Kanban requirement without also asking reviewers to approve the full issue-discussion editor. Opening a card provides its safe summary, movement controls, and canonical GitHub link.
+
+### Pull request 2
+
+Build the full issue modal on the reviewed foundation.
+
+1. issue creation in mapped non-completion columns
+2. title and Markdown body editing
+3. paged comments with create, edit, and delete
+4. labels, assignees, milestone, state reason, and lock controls
+5. remote avatar handling and Markdown media restrictions
+6. complete modal accessibility, responsive behaviour, screenshots, recording, and live verification
+
+Pull request 2 starts only after pull request 1 is reviewed and merged. Each description records authentication behaviour, required permissions, cache retention, best-effort conflict limits, automated checks, live verification boundary, and visual evidence.
+
+## Out of scope
+
+- hosted webhook infrastructure
+- background sync while the Kanban is closed
+- offline mutation queues
+- more than one repository per nodeterm project
+- GitHub Enterprise Server custom API hosts
+- GitHub Projects v2 fields and ordering
+- organisation-specific custom issue fields and issue types
+- issue transfer, pinning, reactions, sub-issues, and dependencies
+- deleting GitHub issues, which the ordinary issue API does not offer
+- automatically renaming or deleting repository labels
+- a dedicated nodeterm GitHub App and device login
+- automated cross-platform pixel-diff infrastructure
+
+## Completion evidence
+
+Pull request 1 is complete only when
+
+- every foundation, trust, cache, paging, sync, mapping, and movement check passes from a fresh run
+- project configuration round-trips without damaging older project files
+- credentials never cross into shared or renderer-readable storage
+- a live GitHub read succeeds
+- a mapped-label move, close, and reopen journey succeeds when an authorised test repository is available
+- conflicts, rate limits, permission failures, network failures, and cache-write failures remain recoverable
+- pointer, keyboard, desktop, 390px, dark-theme, and light-theme evidence for Settings and the board has been reviewed
+- the pull-request diff contains no credentials, cache data, screenshots, recordings, or unrelated changes
+
+The full feature series is complete only when
+
+- every automated check passes from a fresh run
+- all approved issue operations are verified with fixtures
+- a live write journey succeeds when an authorised test repository is available
+- issue-modal pointer, keyboard, desktop, 390px, dark-theme, and light-theme evidence has been reviewed
+- both pull requests contain no credentials, cache data, screenshots, recordings, or unrelated changes
+
+## References
+
+1. GitHub. REST API endpoints for issues [Internet]. 2026 [cited 2026 Aug 9]. Available from: https://docs.github.com/en/rest/issues
+2. GitHub. Generating a user access token for a GitHub App [Internet]. 2026 [cited 2026 Aug 9]. Available from: https://docs.github.com/en/enterprise-cloud@latest/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app
+3. GitHub. Best practices for using the REST API [Internet]. 2026 [cited 2026 Aug 9]. Available from: https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
+4. GitHub. Rate limits for the REST API [Internet]. 2026 [cited 2026 Aug 9]. Available from: https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2026-03-10
+5. GitHub. REST API endpoints for issue comments [Internet]. 2026 [cited 2026 Aug 9]. Available from: https://docs.github.com/en/rest/issues/comments?apiVersion=2026-03-10
+6. Electron. safeStorage [Internet]. 2026 [cited 2026 Aug 9]. Available from: https://www.electronjs.org/docs/latest/api/safe-storage
diff --git a/src/core/git-service.origin.test.ts b/src/core/git-service.origin.test.ts
new file mode 100644
index 000000000..546e60894
--- /dev/null
+++ b/src/core/git-service.origin.test.ts
@@ -0,0 +1,25 @@
+import { execFileSync } from 'node:child_process'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { GitService } from './git-service'
+
+let directory = ''
+
+afterEach(async () => {
+ if (directory) await fs.rm(directory, { recursive: true, force: true })
+})
+
+describe('GitService.originUrl', () => {
+ it('returns the exact origin URL and returns null without an origin', async () => {
+ directory = await fs.mkdtemp(path.join(os.tmpdir(), 'nodeterm-origin-'))
+ execFileSync('git', ['init', '-q'], { cwd: directory })
+ const service = new GitService()
+ await expect(service.originUrl(directory)).resolves.toBeNull()
+ execFileSync('git', ['remote', 'add', 'origin', '[email protected]:owner/repo.git'], {
+ cwd: directory
+ })
+ await expect(service.originUrl(directory)).resolves.toBe('[email protected]:owner/repo.git')
+ })
+})
diff --git a/src/core/git-service.ts b/src/core/git-service.ts
index fc7c8a912..30777b88d 100644
--- a/src/core/git-service.ts
+++ b/src/core/git-service.ts
@@ -537,6 +537,14 @@ export class GitService {
return files
}
+ /** Read the origin through the same local or managed-SSH git executor as every other git read. */
+ async originUrl(cwd: string): Promise<string | null> {
+ if (!cwd) return null
+ const result = await git(cwd, ['remote', 'get-url', 'origin'])
+ const url = result.out.trim()
+ return result.ok && url ? url : null
+ }
+
/** Build a provider web URL for a commit from the origin remote; null if unsupported. */
async remoteCommitUrl(cwd: string, sha: string): Promise<string | null> {
if (!cwd || !/^[0-9a-fA-F]{7,64}$/.test(sha)) return null
diff --git a/src/core/github/avatar-fetcher.test.ts b/src/core/github/avatar-fetcher.test.ts
new file mode 100644
index 000000000..032c2ac70
--- /dev/null
+++ b/src/core/github/avatar-fetcher.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest'
+import { GitHubAvatarFetcher } from './avatar-fetcher'
+
+const users = (count: number) => Array.from({ length: count }, (_, index) => ({
+ id: index + 1,
+ login: `user-${index + 1}`,
+ avatarUrl: `https://avatars.githubusercontent.com/u/${index + 1}?v=4`
+}))
+
+describe('GitHubAvatarFetcher', () => {
+ it('fetches only the validated avatar host without redirects', async () => {
+ const calls: Array<{ url: string; init: RequestInit }> = []
+ const fetcher = new GitHubAvatarFetcher({
+ fetch: async (url, init) => {
+ calls.push({ url: String(url), init: init ?? {} })
+ return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } })
+ }
+ })
+ const result = await fetcher.forPage(users(1))
+ expect(result.dataUrls.get(1)).toBe('data:image/png;base64,AQID')
+ expect(calls[0].init.redirect).toBe('manual')
+
+ const blocked = await fetcher.forPage([{ id: 9, login: 'bad', avatarUrl: 'https://example.com/a.png' }])
+ expect(blocked.dataUrls.size).toBe(0)
+ })
+
+ it('rejects redirects, unsupported MIME types, and images above 128 KiB', async () => {
+ const replies = [
+ new Response(null, { status: 302, headers: { location: 'https://avatars.githubusercontent.com/other' } }),
+ new Response(new Uint8Array([1]), { headers: { 'content-type': 'image/svg+xml' } }),
+ new Response(new Uint8Array(128 * 1024 + 1), { headers: { 'content-type': 'image/png' } })
+ ]
+ const fetcher = new GitHubAvatarFetcher({ fetch: async () => replies.shift()! })
+ expect((await fetcher.forPage(users(3))).dataUrls.size).toBe(0)
+ })
+
+ it('stops at the 512 KiB aggregate page budget', async () => {
+ const bytes = new Uint8Array(120 * 1024)
+ const fetcher = new GitHubAvatarFetcher({
+ fetch: async () => new Response(bytes, { headers: { 'content-type': 'image/webp' } })
+ })
+ const result = await fetcher.forPage(users(6))
+ expect(result.dataUrls.size).toBe(4)
+ expect(result.truncated).toBe(true)
+ })
+})
diff --git a/src/core/github/avatar-fetcher.ts b/src/core/github/avatar-fetcher.ts
new file mode 100644
index 000000000..c2157e0d2
--- /dev/null
+++ b/src/core/github/avatar-fetcher.ts
@@ -0,0 +1,97 @@
+import type { GitHubIssueUser } from '../../shared/github-issues'
+
+const MAX_AVATAR_BYTES = 128 * 1024
+const MAX_PAGE_BYTES = 512 * 1024
+const MIME = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp'])
+
+type AvatarFetcherOptions = {
+ fetch?: typeof fetch
+ cacheTtlMs?: number
+ now?: () => number
+}
+
+type CacheEntry = { dataUrl: string; bytes: number; expiresAt: number }
+
+async function boundedBytes(response: Response): Promise<Uint8Array | null> {
+ const length = Number(response.headers.get('content-length'))
+ if (Number.isFinite(length) && length > MAX_AVATAR_BYTES) return null
+ if (!response.body) return null
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let total = 0
+ while (true) {
+ const next = await reader.read()
+ if (next.done) break
+ total += next.value.byteLength
+ if (total > MAX_AVATAR_BYTES) { await reader.cancel(); return null }
+ chunks.push(next.value)
+ }
+ const bytes = new Uint8Array(total)
+ let offset = 0
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }
+ return bytes
+}
+
+export class GitHubAvatarFetcher {
+ private readonly fetcher: typeof fetch
+ private readonly cache = new Map<number, CacheEntry>()
+ private readonly ttl: number
+ private readonly now: () => number
+
+ constructor(options: AvatarFetcherOptions = {}) {
+ this.fetcher = options.fetch ?? fetch
+ this.ttl = options.cacheTtlMs ?? 5 * 60_000
+ this.now = options.now ?? Date.now
+ }
+
+ async forPage(users: readonly GitHubIssueUser[]): Promise<{
+ dataUrls: Map<number, string>
+ truncated: boolean
+ }> {
+ const dataUrls = new Map<number, string>()
+ let total = 0
+ let truncated = false
+ for (const user of new Map(users.map((item) => [item.id, item])).values()) {
+ const cached = this.cache.get(user.id)
+ if (cached && cached.expiresAt > this.now()) {
+ if (total + cached.bytes > MAX_PAGE_BYTES) { truncated = true; break }
+ total += cached.bytes
+ dataUrls.set(user.id, cached.dataUrl)
+ continue
+ }
+ const loaded = await this.fetchOne(user)
+ if (!loaded) continue
+ if (total + loaded.bytes > MAX_PAGE_BYTES) { truncated = true; break }
+ total += loaded.bytes
+ dataUrls.set(user.id, loaded.dataUrl)
+ }
+ return { dataUrls, truncated }
+ }
+
+ private async fetchOne(user: GitHubIssueUser): Promise<CacheEntry | null> {
+ let url: URL
+ try { url = new URL(user.avatarUrl) } catch { return null }
+ if (url.protocol !== 'https:' || url.hostname !== 'avatars.githubusercontent.com' ||
+ url.username || url.password) return null
+ url.searchParams.set('size', '64')
+ let response: Response
+ try {
+ response = await this.fetcher(url, { method: 'GET', redirect: 'manual' })
+ } catch {
+ return null
+ }
+ if (!response.ok || response.status >= 300) return null
+ const mime = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase()
+ if (!mime || !MIME.has(mime)) return null
+ const bytes = await boundedBytes(response)
+ if (!bytes) return null
+ const entry = {
+ dataUrl: `data:${mime};base64,${Buffer.from(bytes).toString('base64')}`,
+ bytes: bytes.byteLength,
+ expiresAt: this.now() + this.ttl
+ }
+ this.cache.set(user.id, entry)
+ if (this.cache.size > 500) this.cache.delete(this.cache.keys().next().value!)
+ return entry
+ }
+}
diff --git a/src/core/github/cache.test.ts b/src/core/github/cache.test.ts
new file mode 100644
index 000000000..192662238
--- /dev/null
+++ b/src/core/github/cache.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { GitHubIssueCache, type GitHubCompleteSnapshot } from './cache'
+import type { GitHubIssue } from '../../shared/github-issues'
+
+let userDataDir: string
+
+const issue = (number: number): GitHubIssue => ({
+ id: 1_000 + number,
+ number,
+ title: `Issue ${number}`,
+ body: '',
+ state: 'open',
+ stateReason: null,
+ htmlUrl: `https://github.com/o/r/issues/${number}`,
+ apiUrl: `https://api.github.com/repos/o/r/issues/${number}`,
+ labels: [],
+ assignees: [],
+ createdAt: '2026-08-01T10:00:00Z',
+ updatedAt: '2026-08-09T10:00:00Z',
+ locked: false
+})
+
+const complete = (issues: GitHubIssue[]): GitHubCompleteSnapshot => ({
+ issues,
+ etags: {},
+ lastSuccessfulRefreshAt: 1_000,
+ lastFullReconciliationAt: 1_000
+})
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-cache-'))
+})
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+describe('GitHubIssueCache', () => {
+ it('writes a private hashed cache file atomically', async () => {
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveComplete('user-1', 'o/r', complete([issue(1)]))
+ const files = await fs.readdir(path.join(userDataDir, 'github-issues-cache'))
+ expect(files).toHaveLength(1)
+ expect(files[0]).toMatch(/^[0-9a-f]{64}\.json$/)
+ expect((await fs.stat(path.join(userDataDir, 'github-issues-cache', files[0]))).mode & 0o777)
+ .toBe(0o600)
+ expect(await cache.load('user-1', 'o/r')).toMatchObject({
+ lastComplete: { issues: [{ number: 1 }] }
+ })
+ })
+
+ it('retains lastComplete when a later refresh is incomplete', async () => {
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveComplete('user-1', 'o/r', complete([issue(1)]))
+ await cache.saveIncompleteAttempt('user-1', 'o/r', {
+ reason: 'issue-limit', observedAt: 2_000, partialIssues: [issue(2)]
+ })
+ const loaded = await cache.load('user-1', 'o/r')
+ expect(loaded.lastComplete?.issues.map((item) => item.number)).toEqual([1])
+ expect(loaded.lastAttempt).toEqual({ reason: 'issue-limit', observedAt: 2_000 })
+ })
+
+ it('keeps a bounded first-refresh partial snapshot visibly separate', async () => {
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveIncompleteAttempt('user-1', 'o/r', {
+ reason: 'byte-limit', observedAt: 2_000, partialIssues: [issue(1)]
+ })
+ const loaded = await cache.load('user-1', 'o/r')
+ expect(loaded.lastComplete).toBeUndefined()
+ expect(loaded).toMatchObject({
+ lastAttempt: { reason: 'byte-limit', partialIssues: [{ number: 1 }] }
+ })
+ })
+
+ it('rejects an oversized replacement and preserves the previous complete snapshot', async () => {
+ const cache = new GitHubIssueCache(userDataDir, { maximumBytes: 2_000 })
+ await cache.saveComplete('user-1', 'o/r', complete([issue(1)]))
+ await expect(cache.saveComplete('user-1', 'o/r', complete([
+ { ...issue(2), body: 'x'.repeat(3_000) }
+ ]))).rejects.toMatchObject({ code: 'cache-too-large' })
+ expect((await cache.load('user-1', 'o/r')).lastComplete?.issues[0].number).toBe(1)
+ })
+
+ it('refuses to load a stored document larger than the maximum', async () => {
+ // The write path caps size, but a document already on disk can exceed a LOWER cap — an older
+ // build's cache, or a cap tightened later. Loading it anyway would pull the whole file into
+ // memory, which is the reading half of the same budget saveComplete enforces.
+ await new GitHubIssueCache(userDataDir).saveComplete('user-1', 'o/r', complete([
+ { ...issue(1), body: 'x'.repeat(4_000) }
+ ]))
+ const tightened = new GitHubIssueCache(userDataDir, { maximumBytes: 500 })
+ expect(await tightened.load('user-1', 'o/r')).toEqual({ version: 1 })
+ })
+
+ it('clears only the selected identity and repository cache', async () => {
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveComplete('user-1', 'o/r', complete([issue(1)]))
+ await cache.saveComplete('user-2', 'o/r', complete([issue(2)]))
+ await cache.clear('user-1', 'o/r')
+ expect(await cache.load('user-1', 'o/r')).toEqual({ version: 1 })
+ expect((await cache.load('user-2', 'o/r')).lastComplete?.issues[0].number).toBe(2)
+ })
+
+ it('persists a private approval binding so an offline session can locate and delete its cache', async () => {
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveComplete('user-1', 'o/r', complete([issue(1)]))
+ await cache.saveComplete('user-2', 'o/r', complete([issue(2)]))
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ expect(await cache.boundUserId('local-1', 'project-1', 'o/r')).toBe('user-1')
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-2')
+ expect(await cache.boundUserId('local-1', 'project-1', 'o/r')).toBe('user-2')
+ await cache.clearBound('local-1', 'project-1', 'o/r')
+ expect(await cache.boundUserId('local-1', 'project-1', 'o/r')).toBeNull()
+ expect(await cache.load('user-1', 'o/r')).toEqual({ version: 1 })
+ expect(await cache.load('user-2', 'o/r')).toEqual({ version: 1 })
+ })
+})
diff --git a/src/core/github/cache.ts b/src/core/github/cache.ts
new file mode 100644
index 000000000..c211381c0
--- /dev/null
+++ b/src/core/github/cache.ts
@@ -0,0 +1,252 @@
+import { createHash } from 'node:crypto'
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import type { GitHubIssue } from '../../shared/github-issues'
+import { parseGitHubRepository } from './config'
+
+const DIRECTORY = 'github-issues-cache'
+const BINDING_DIRECTORY = 'github-issues-bindings'
+const DEFAULT_MAXIMUM = 64 * 1024 * 1024
+
+export interface GitHubCompleteSnapshot {
+ issues: GitHubIssue[]
+ etags: Record<string, string>
+ lastSuccessfulRefreshAt: number
+ lastFullReconciliationAt: number
+}
+
+export interface GitHubIncompleteAttempt {
+ reason: 'issue-limit' | 'byte-limit'
+ observedAt: number
+ partialIssues?: GitHubIssue[]
+}
+
+export interface GitHubCacheDocument {
+ version: 1
+ lastComplete?: GitHubCompleteSnapshot
+ lastAttempt?: GitHubIncompleteAttempt
+}
+
+export class GitHubCacheError extends Error {
+ constructor(readonly code: 'cache-too-large' | 'invalid-cache-key') {
+ super(code)
+ }
+}
+
+function safeInteger(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+}
+
+function validIssue(value: unknown): value is GitHubIssue {
+ if (!value || typeof value !== 'object') return false
+ const issue = value as GitHubIssue
+ return safeInteger(issue.id) && issue.id > 0 && safeInteger(issue.number) && issue.number > 0 &&
+ typeof issue.title === 'string' && typeof issue.body === 'string' &&
+ (issue.state === 'open' || issue.state === 'closed') &&
+ typeof issue.htmlUrl === 'string' && typeof issue.apiUrl === 'string' &&
+ Array.isArray(issue.labels) && Array.isArray(issue.assignees) &&
+ typeof issue.createdAt === 'string' && typeof issue.updatedAt === 'string' &&
+ typeof issue.locked === 'boolean'
+}
+
+function validComplete(value: unknown): value is GitHubCompleteSnapshot {
+ if (!value || typeof value !== 'object') return false
+ const snapshot = value as GitHubCompleteSnapshot
+ return Array.isArray(snapshot.issues) && snapshot.issues.length <= 10_000 &&
+ snapshot.issues.every(validIssue) &&
+ snapshot.etags !== null && typeof snapshot.etags === 'object' && !Array.isArray(snapshot.etags) &&
+ Object.entries(snapshot.etags).every(([key, etag]) => key.length <= 2_048 && typeof etag === 'string' && etag.length <= 512) &&
+ safeInteger(snapshot.lastSuccessfulRefreshAt) && safeInteger(snapshot.lastFullReconciliationAt)
+}
+
+function validAttempt(value: unknown): value is GitHubIncompleteAttempt {
+ if (!value || typeof value !== 'object') return false
+ const attempt = value as GitHubIncompleteAttempt
+ return (attempt.reason === 'issue-limit' || attempt.reason === 'byte-limit') &&
+ safeInteger(attempt.observedAt) &&
+ (attempt.partialIssues === undefined ||
+ (Array.isArray(attempt.partialIssues) && attempt.partialIssues.length <= 10_000 &&
+ attempt.partialIssues.every(validIssue)))
+}
+
+function validDocument(value: unknown): value is GitHubCacheDocument {
+ if (!value || typeof value !== 'object') return false
+ const document = value as GitHubCacheDocument
+ return document.version === 1 &&
+ (document.lastComplete === undefined || validComplete(document.lastComplete)) &&
+ (document.lastAttempt === undefined || validAttempt(document.lastAttempt))
+}
+
+export class GitHubIssueCache {
+ private readonly maximum: number
+
+ constructor(
+ private readonly userDataDir: string,
+ options: { maximumBytes?: number } = {}
+ ) {
+ this.maximum = options.maximumBytes ?? DEFAULT_MAXIMUM
+ }
+
+ async load(userId: string, repository: string): Promise<GitHubCacheDocument> {
+ const file = this.file(userId, repository)
+ // Measure and read through ONE open handle. Doing it as stat(path) + readFile(path) leaves a
+ // window between the size check and the read, and this cache races itself: `write` publishes
+ // by renaming a fresh file over this path, so a save landing mid-load would hand us a file the
+ // size guard never saw. A handle is bound to the inode it opened, so the bytes we read are the
+ // bytes we measured.
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined
+ try {
+ handle = await fs.open(file, 'r')
+ const stat = await handle.stat()
+ if (stat.size > this.maximum) return { version: 1 }
+ const parsed: unknown = JSON.parse(await handle.readFile('utf-8'))
+ return validDocument(parsed) ? structuredClone(parsed) : { version: 1 }
+ } catch {
+ return { version: 1 }
+ } finally {
+ await handle?.close().catch(() => undefined)
+ }
+ }
+
+ async saveComplete(
+ userId: string,
+ repository: string,
+ snapshot: GitHubCompleteSnapshot
+ ): Promise<void> {
+ if (!validComplete(snapshot)) throw new GitHubCacheError('cache-too-large')
+ await this.write(this.file(userId, repository), {
+ version: 1,
+ lastComplete: structuredClone(snapshot)
+ })
+ }
+
+ async saveIncompleteAttempt(
+ userId: string,
+ repository: string,
+ attempt: GitHubIncompleteAttempt
+ ): Promise<void> {
+ if (!validAttempt(attempt)) throw new GitHubCacheError('cache-too-large')
+ const current = await this.load(userId, repository)
+ const metadata: GitHubIncompleteAttempt = {
+ reason: attempt.reason,
+ observedAt: attempt.observedAt,
+ ...(!current.lastComplete && attempt.partialIssues
+ ? { partialIssues: structuredClone(attempt.partialIssues) }
+ : {})
+ }
+ let next: GitHubCacheDocument = {
+ version: 1,
+ ...(current.lastComplete ? { lastComplete: current.lastComplete } : {}),
+ lastAttempt: metadata
+ }
+ if (Buffer.byteLength(JSON.stringify(next), 'utf-8') > this.maximum && metadata.partialIssues) {
+ next = {
+ version: 1,
+ lastAttempt: { reason: metadata.reason, observedAt: metadata.observedAt }
+ }
+ }
+ await this.write(this.file(userId, repository), next)
+ }
+
+ async clear(userId: string, repository: string): Promise<void> {
+ await fs.rm(this.file(userId, repository), { force: true })
+ }
+
+ async bind(
+ localApprovalId: string,
+ projectId: string,
+ repository: string,
+ userId: string
+ ): Promise<void> {
+ if (!userId || userId.length > 256) throw new GitHubCacheError('invalid-cache-key')
+ const file = this.bindingFile(localApprovalId, projectId, repository)
+ const existing = await this.readBinding(file)
+ const userIds = [...new Set([...(existing?.userIds ?? []), userId])]
+ await this.writePrivate(file, JSON.stringify({
+ version: 1,
+ activeUserId: userId,
+ userIds
+ }))
+ }
+
+ async boundUserId(
+ localApprovalId: string,
+ projectId: string,
+ repository: string
+ ): Promise<string | null> {
+ const binding = await this.readBinding(this.bindingFile(localApprovalId, projectId, repository))
+ return binding?.activeUserId ?? null
+ }
+
+ async clearBound(localApprovalId: string, projectId: string, repository: string): Promise<void> {
+ const binding = this.bindingFile(localApprovalId, projectId, repository)
+ const value = await this.readBinding(binding)
+ for (const userId of value?.userIds ?? []) await this.clear(userId, repository)
+ await fs.rm(binding, { force: true })
+ }
+
+ private file(userId: string, repository: string): string {
+ if (!userId || userId.length > 256 || parseGitHubRepository(repository) !== repository) {
+ throw new GitHubCacheError('invalid-cache-key')
+ }
+ const digest = createHash('sha256').update(`${userId}\0${repository}`).digest('hex')
+ return path.join(this.userDataDir, DIRECTORY, `${digest}.json`)
+ }
+
+ private bindingFile(localApprovalId: string, projectId: string, repository: string): string {
+ if (!localApprovalId || localApprovalId.length > 256 || !projectId || projectId.length > 256 ||
+ parseGitHubRepository(repository) !== repository) {
+ throw new GitHubCacheError('invalid-cache-key')
+ }
+ const digest = createHash('sha256')
+ .update(`${localApprovalId}\0${projectId}\0${repository}`)
+ .digest('hex')
+ return path.join(this.userDataDir, BINDING_DIRECTORY, `${digest}.json`)
+ }
+
+ private async readBinding(file: string): Promise<{
+ activeUserId: string
+ userIds: string[]
+ } | null> {
+ try {
+ const parsed: unknown = JSON.parse(await fs.readFile(file, 'utf-8'))
+ if (!parsed || typeof parsed !== 'object') return null
+ const value = parsed as {
+ version?: unknown
+ userId?: unknown
+ activeUserId?: unknown
+ userIds?: unknown
+ }
+ if (value.version !== 1) return null
+ const legacy = typeof value.userId === 'string' ? value.userId : undefined
+ const activeUserId = typeof value.activeUserId === 'string' ? value.activeUserId : legacy
+ const candidates = Array.isArray(value.userIds) ? value.userIds : legacy ? [legacy] : []
+ if (!activeUserId || activeUserId.length > 256 ||
+ candidates.some((userId) => typeof userId !== 'string' || !userId || userId.length > 256)) {
+ return null
+ }
+ const userIds = [...new Set(candidates as string[])]
+ if (!userIds.includes(activeUserId)) userIds.push(activeUserId)
+ return { activeUserId, userIds }
+ } catch {
+ return null
+ }
+ }
+
+ private async write(file: string, document: GitHubCacheDocument): Promise<void> {
+ const content = JSON.stringify(document)
+ if (Buffer.byteLength(content, 'utf-8') > this.maximum) {
+ throw new GitHubCacheError('cache-too-large')
+ }
+ await this.writePrivate(file, content)
+ }
+
+ private async writePrivate(file: string, content: string): Promise<void> {
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ const temporary = `${file}.tmp`
+ await fs.writeFile(temporary, content, { encoding: 'utf-8', mode: 0o600 })
+ await fs.chmod(temporary, 0o600)
+ await fs.rename(temporary, file)
+ await fs.chmod(file, 0o600)
+ }
+}
diff --git a/src/core/github/client.test.ts b/src/core/github/client.test.ts
new file mode 100644
index 000000000..c9e4f2a49
--- /dev/null
+++ b/src/core/github/client.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from 'vitest'
+import { GitHubIssuesClient } from './client'
+
+const issue = (number: number, over: Record<string, unknown> = {}) => ({
+ id: 1_000 + number,
+ number,
+ title: `Issue ${number}`,
+ body: 'Body',
+ state: 'open',
+ state_reason: null,
+ html_url: `https://github.com/nodeterm/nodeterm/issues/${number}`,
+ url: `https://api.github.com/repos/nodeterm/nodeterm/issues/${number}`,
+ labels: [{ id: 1, name: 'bug', color: 'd73a4a' }],
+ assignees: [{ id: 2, login: 'octocat', avatar_url: 'https://avatars.githubusercontent.com/u/2?v=4' }],
+ created_at: '2026-08-01T10:00:00Z',
+ updated_at: '2026-08-09T10:00:00Z',
+ locked: false,
+ ...over
+})
+
+function response(body: unknown, init: ResponseInit = {}): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'content-type': 'application/json', ...init.headers },
+ ...init
+ })
+}
+
+describe('GitHubIssuesClient', () => {
+ it('validates the authenticated user identity used for global coordination', async () => {
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async () => response({ id: 123, login: 'octocat' })
+ })
+ expect(await client.getAuthenticatedUser()).toEqual({ userId: '123', login: 'octocat' })
+ })
+
+ it('uses the fixed API host and required version headers', async () => {
+ const calls: Array<{ url: string; init: RequestInit }> = []
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async (url, init) => {
+ calls.push({ url: String(url), init: init ?? {} })
+ return response([issue(1)])
+ }
+ })
+ await client.listIssues('nodeterm/nodeterm', { state: 'all', page: 1, perPage: 50 })
+ expect(calls[0].url).toBe('https://api.github.com/repos/nodeterm/nodeterm/issues?state=all&page=1&per_page=50')
+ expect(calls[0].init).toMatchObject({ redirect: 'manual' })
+ expect(new Headers(calls[0].init.headers).get('x-github-api-version')).toBe('2022-11-28')
+ expect(new Headers(calls[0].init.headers).get('authorization')).toBe('Bearer secret')
+ })
+
+ it('filters pull requests before returning validated issues', async () => {
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async () => response([issue(1, { pull_request: { url: 'x' } }), issue(2)])
+ })
+ const page = await client.listIssues('nodeterm/nodeterm', { state: 'all', page: 1, perPage: 50 })
+ expect(page.items.map((item) => item.number)).toEqual([2])
+ })
+
+ it('rejects a pull request returned by the single issue endpoint', async () => {
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async () => response(issue(7, { pull_request: { url: 'x' } }))
+ })
+ await expect(client.getIssue('nodeterm/nodeterm', 7))
+ .rejects.toMatchObject({ code: 'invalid-request' })
+ })
+
+ it('distinguishes permissions from primary and secondary rate limits', async () => {
+ const forbidden = new GitHubIssuesClient({
+ token: 'secret', fetch: async () => response({ message: 'forbidden' }, { status: 403 })
+ })
+ await expect(forbidden.getIssue('nodeterm/nodeterm', 1))
+ .rejects.toMatchObject({ code: 'insufficient-permission', status: 403 })
+
+ const primary = new GitHubIssuesClient({
+ token: 'secret', fetch: async () => response({ message: 'rate limit' }, {
+ status: 403, headers: { 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': '2000000000' }
+ })
+ })
+ await expect(primary.getIssue('nodeterm/nodeterm', 1))
+ .rejects.toMatchObject({ code: 'rate-limited', status: 403, retryAt: 2_000_000_000_000 })
+
+ const before = Date.now()
+ const secondary = new GitHubIssuesClient({
+ token: 'secret', fetch: async () => response({ message: 'slow down' }, { status: 429 })
+ })
+ await expect(secondary.getIssue('nodeterm/nodeterm', 1)).rejects.toMatchObject({
+ code: 'rate-limited', status: 429
+ })
+ try {
+ await secondary.getIssue('nodeterm/nodeterm', 1)
+ } catch (error) {
+ expect((error as { retryAt: number }).retryAt).toBeGreaterThanOrEqual(before + 2_000)
+ }
+
+ const documentedSecondary = new GitHubIssuesClient({
+ token: 'secret', fetch: async () => response({
+ message: 'You have exceeded a secondary rate limit. Please wait a few minutes before you try again.',
+ documentation_url: 'https://docs.github.com/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits'
+ }, { status: 403, headers: { 'x-ratelimit-remaining': '42' } })
+ })
+ await expect(documentedSecondary.getIssue('nodeterm/nodeterm', 1)).rejects.toMatchObject({
+ code: 'rate-limited', status: 403
+ })
+ })
+
+ it('returns the next page and ETag without arbitrary headers', async () => {
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async () => response([issue(1)], {
+ headers: {
+ etag: '"abc"',
+ link: '<https://api.github.com/repos/nodeterm/nodeterm/issues?page=2>; rel="next"',
+ 'x-private-value': 'must-not-pass'
+ }
+ })
+ })
+ expect(await client.listIssues('nodeterm/nodeterm', { state: 'all', page: 1, perPage: 50 }))
+ .toMatchObject({ nextPage: 2, etag: '"abc"' })
+ })
+
+ it('rejects malformed and oversized responses', async () => {
+ const malformed = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async () => response([{ id: 1, title: 'missing fields' }])
+ })
+ await expect(malformed.listIssues('nodeterm/nodeterm', { state: 'all', page: 1, perPage: 50 }))
+ .rejects.toMatchObject({ code: 'malformed-response' })
+
+ const oversized = new GitHubIssuesClient({
+ token: 'secret',
+ maxResponseBytes: 32,
+ fetch: async () => response([issue(1)])
+ })
+ await expect(oversized.listIssues('nodeterm/nodeterm', { state: 'all', page: 1, perPage: 50 }))
+ .rejects.toMatchObject({ code: 'response-too-large' })
+ })
+
+ it('decodes a confirmed issue update and sends only supported fields', async () => {
+ let request: { url: string; init: RequestInit } | null = null
+ const client = new GitHubIssuesClient({
+ token: 'secret',
+ fetch: async (url, init) => {
+ request = { url: String(url), init: init ?? {} }
+ return response(issue(42, { state: 'closed', labels: [{ id: 4, name: 'status:done', color: '30d158' }] }))
+ }
+ })
+ const updated = await client.updateIssue('nodeterm/nodeterm', 42, {
+ state: 'closed',
+ labels: ['bug', 'status:done']
+ })
+ expect(updated).toMatchObject({ number: 42, state: 'closed' })
+ expect(request).not.toBeNull()
+ expect(JSON.parse(String((request as unknown as { init: RequestInit }).init.body)))
+ .toEqual({ state: 'closed', labels: ['bug', 'status:done'] })
+ })
+})
diff --git a/src/core/github/client.ts b/src/core/github/client.ts
new file mode 100644
index 000000000..90c9ce4f1
--- /dev/null
+++ b/src/core/github/client.ts
@@ -0,0 +1,393 @@
+import type {
+ GitHubIssue,
+ GitHubIssueLabel,
+ GitHubIssueUser,
+ GitHubRepositoryLabel,
+ IssuePageResult,
+ LabelPageResult,
+ ListIssueOptions,
+ UpdateIssueInput
+} from '../../shared/github-issues'
+import { parseGitHubRepository } from './config'
+
+const API_ORIGIN = 'https://api.github.com'
+const API_VERSION = '2022-11-28'
+const DEFAULT_MAX_RESPONSE = 8 * 1024 * 1024
+const MAX_ERROR_METADATA_BYTES = 4 * 1024
+
+export class GitHubClientError extends Error {
+ constructor(
+ readonly code: 'invalid-request' | 'malformed-response' | 'response-too-large' |
+ 'request-failed' | 'rate-limited' | 'insufficient-permission',
+ readonly status?: number,
+ readonly retryAt?: number
+ ) {
+ super(code)
+ }
+}
+
+type ClientOptions = {
+ token: string
+ fetch?: typeof fetch
+ maxResponseBytes?: number
+ timeoutMs?: number
+}
+
+function safeRepository(repository: string): string {
+ if (parseGitHubRepository(repository) !== repository) throw new GitHubClientError('invalid-request')
+ return repository
+}
+
+function positiveInteger(value: number, maximum: number): boolean {
+ return Number.isSafeInteger(value) && value > 0 && value <= maximum
+}
+
+function string(value: unknown, maximum: number): value is string {
+ return typeof value === 'string' && value.length <= maximum
+}
+
+function isoDate(value: unknown): value is string {
+ return string(value, 64) && !Number.isNaN(Date.parse(value))
+}
+
+function object(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+function issueLabel(value: unknown): GitHubIssueLabel | null {
+ const item = object(value)
+ if (!item || !positiveInteger(Number(item.id), Number.MAX_SAFE_INTEGER) ||
+ !string(item.name, 50) || !string(item.color, 6) || !/^[0-9a-fA-F]{6}$/.test(item.color)) {
+ return null
+ }
+ return { id: Number(item.id), name: item.name, color: item.color.toLowerCase() }
+}
+
+function issueUser(value: unknown): GitHubIssueUser | null {
+ const item = object(value)
+ if (!item || !positiveInteger(Number(item.id), Number.MAX_SAFE_INTEGER) ||
+ !string(item.login, 128) || !string(item.avatar_url, 2_048)) return null
+ let avatar: URL
+ try { avatar = new URL(item.avatar_url) } catch { return null }
+ if (avatar.protocol !== 'https:' || avatar.hostname !== 'avatars.githubusercontent.com') return null
+ return { id: Number(item.id), login: item.login, avatarUrl: avatar.toString() }
+}
+
+function issueFrom(value: unknown): GitHubIssue | null {
+ const item = object(value)
+ if (!item || !positiveInteger(Number(item.id), Number.MAX_SAFE_INTEGER) ||
+ !positiveInteger(Number(item.number), Number.MAX_SAFE_INTEGER) ||
+ !string(item.title, 1_024) || !(item.body === null || string(item.body, 1_000_000)) ||
+ (item.state !== 'open' && item.state !== 'closed') ||
+ !(item.state_reason === null || item.state_reason === undefined ||
+ item.state_reason === 'completed' || item.state_reason === 'not_planned' ||
+ item.state_reason === 'reopened') ||
+ !string(item.html_url, 2_048) || !string(item.url, 2_048) ||
+ !Array.isArray(item.labels) || item.labels.length > 100 ||
+ !Array.isArray(item.assignees) || item.assignees.length > 100 ||
+ !isoDate(item.created_at) || !isoDate(item.updated_at) ||
+ typeof item.locked !== 'boolean') return null
+ const labels = item.labels.map(issueLabel)
+ const assignees = item.assignees.map(issueUser)
+ if (labels.some((entry) => !entry) || assignees.some((entry) => !entry)) return null
+ let html: URL
+ let api: URL
+ try {
+ html = new URL(item.html_url)
+ api = new URL(item.url)
+ } catch {
+ return null
+ }
+ if (html.protocol !== 'https:' || html.hostname !== 'github.com' ||
+ api.origin !== API_ORIGIN) return null
+ return {
+ id: Number(item.id),
+ number: Number(item.number),
+ title: item.title,
+ body: item.body ?? '',
+ state: item.state,
+ stateReason: (item.state_reason ?? null) as GitHubIssue['stateReason'],
+ htmlUrl: html.toString(),
+ apiUrl: api.toString(),
+ labels: labels as GitHubIssueLabel[],
+ assignees: assignees as GitHubIssueUser[],
+ createdAt: item.created_at,
+ updatedAt: item.updated_at,
+ locked: item.locked
+ }
+}
+
+function nextPage(link: string | null): number | undefined {
+ if (!link) return undefined
+ for (const part of link.split(',')) {
+ if (!/;\s*rel="next"\s*$/.test(part)) continue
+ const match = part.match(/^\s*<([^>]+)>/)
+ if (!match) continue
+ try {
+ const url = new URL(match[1])
+ if (url.origin !== API_ORIGIN) return undefined
+ const page = Number(url.searchParams.get('page'))
+ return positiveInteger(page, 100_000) ? page : undefined
+ } catch {
+ return undefined
+ }
+ }
+ return undefined
+}
+
+async function boundedErrorMetadata(response: Response): Promise<string> {
+ const length = Number(response.headers.get('content-length'))
+ if (Number.isFinite(length) && length > MAX_ERROR_METADATA_BYTES) return ''
+ if (!response.body) return ''
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let total = 0
+ while (true) {
+ const next = await reader.read()
+ if (next.done) break
+ total += next.value.byteLength
+ if (total > MAX_ERROR_METADATA_BYTES) {
+ await reader.cancel()
+ return ''
+ }
+ chunks.push(next.value)
+ }
+ const bytes = new Uint8Array(total)
+ let offset = 0
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }
+ try {
+ const value = object(JSON.parse(new TextDecoder().decode(bytes)))
+ const message = value && string(value.message, 2_048) ? value.message : ''
+ const documentation = value && string(value.documentation_url, 2_048)
+ ? value.documentation_url
+ : ''
+ return `${message}\n${documentation}`.toLocaleLowerCase('en-US')
+ } catch {
+ return ''
+ }
+}
+
+export class GitHubIssuesClient {
+ private readonly fetcher: typeof fetch
+ private readonly maximum: number
+ private readonly timeoutMs: number
+ private secondaryBackoffMs = 1_000
+
+ constructor(private readonly options: ClientOptions) {
+ this.fetcher = options.fetch ?? fetch
+ this.maximum = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE
+ this.timeoutMs = options.timeoutMs ?? 15_000
+ }
+
+ async getAuthenticatedUser(): Promise<{ userId: string; login: string }> {
+ const value = object(await this.json(await this.request('/user', { method: 'GET' })))
+ if (!value || !positiveInteger(Number(value.id), Number.MAX_SAFE_INTEGER) ||
+ !string(value.login, 128) || !value.login) {
+ throw new GitHubClientError('malformed-response')
+ }
+ return { userId: String(value.id), login: value.login }
+ }
+
+ async listIssues(repository: string, options: ListIssueOptions): Promise<IssuePageResult> {
+ safeRepository(repository)
+ if (!positiveInteger(options.page, 100_000) || !positiveInteger(options.perPage, 100) ||
+ !['open', 'closed', 'all'].includes(options.state)) throw new GitHubClientError('invalid-request')
+ const query = new URLSearchParams({
+ state: options.state,
+ page: String(options.page),
+ per_page: String(options.perPage)
+ })
+ if (options.since) {
+ if (!isoDate(options.since)) throw new GitHubClientError('invalid-request')
+ query.set('since', options.since)
+ }
+ const response = await this.request(`/repos/${repository}/issues?${query}`, {
+ method: 'GET',
+ ...(options.etag ? { headers: { 'if-none-match': options.etag } } : {})
+ })
+ if (response.status === 304) return { items: [], notModified: true, etag: options.etag }
+ const value = await this.json(response)
+ if (!Array.isArray(value) || value.length > 100) throw new GitHubClientError('malformed-response')
+ const items: GitHubIssue[] = []
+ for (const candidate of value) {
+ if (object(candidate)?.pull_request !== undefined) continue
+ const decoded = issueFrom(candidate)
+ if (!decoded) throw new GitHubClientError('malformed-response')
+ items.push(decoded)
+ }
+ return {
+ items,
+ ...(nextPage(response.headers.get('link')) ? { nextPage: nextPage(response.headers.get('link')) } : {}),
+ ...(response.headers.get('etag') ? { etag: response.headers.get('etag')! } : {})
+ }
+ }
+
+ async getIssue(repository: string, issueNumber: number): Promise<GitHubIssue> {
+ safeRepository(repository)
+ if (!positiveInteger(issueNumber, Number.MAX_SAFE_INTEGER)) throw new GitHubClientError('invalid-request')
+ const value = await this.json(await this.request(`/repos/${repository}/issues/${issueNumber}`, { method: 'GET' }))
+ if (object(value)?.pull_request !== undefined) throw new GitHubClientError('invalid-request')
+ const decoded = issueFrom(value)
+ if (!decoded) throw new GitHubClientError('malformed-response')
+ return decoded
+ }
+
+ async updateIssue(
+ repository: string,
+ issueNumber: number,
+ input: UpdateIssueInput
+ ): Promise<GitHubIssue> {
+ safeRepository(repository)
+ if (!positiveInteger(issueNumber, Number.MAX_SAFE_INTEGER) ||
+ (input.state !== undefined && input.state !== 'open' && input.state !== 'closed') ||
+ (input.labels !== undefined && (!Array.isArray(input.labels) || input.labels.length > 100 ||
+ input.labels.some((label) => !string(label, 50) || !label.trim())))) {
+ throw new GitHubClientError('invalid-request')
+ }
+ const body = {
+ ...(input.state ? { state: input.state } : {}),
+ ...(input.labels ? { labels: input.labels } : {})
+ }
+ const response = await this.request(`/repos/${repository}/issues/${issueNumber}`, {
+ method: 'PATCH',
+ body: JSON.stringify(body)
+ })
+ const decoded = issueFrom(await this.json(response))
+ if (!decoded) throw new GitHubClientError('malformed-response')
+ return decoded
+ }
+
+ async listRepositoryLabels(
+ repository: string,
+ options: { page: number; perPage: number; etag?: string }
+ ): Promise<LabelPageResult> {
+ safeRepository(repository)
+ if (!positiveInteger(options.page, 100_000) || !positiveInteger(options.perPage, 100)) {
+ throw new GitHubClientError('invalid-request')
+ }
+ const response = await this.request(
+ `/repos/${repository}/labels?page=${options.page}&per_page=${options.perPage}`,
+ { method: 'GET', ...(options.etag ? { headers: { 'if-none-match': options.etag } } : {}) }
+ )
+ if (response.status === 304) return { items: [], notModified: true, etag: options.etag }
+ const value = await this.json(response)
+ if (!Array.isArray(value) || value.length > 100) throw new GitHubClientError('malformed-response')
+ const items = value.map((candidate): GitHubRepositoryLabel | null => {
+ const base = issueLabel(candidate)
+ const item = object(candidate)
+ if (!base || !item || !(item.description === null || string(item.description, 1_000))) return null
+ return { ...base, description: item.description }
+ })
+ if (items.some((item) => !item)) throw new GitHubClientError('malformed-response')
+ return {
+ items: items as GitHubRepositoryLabel[],
+ ...(nextPage(response.headers.get('link')) ? { nextPage: nextPage(response.headers.get('link')) } : {}),
+ ...(response.headers.get('etag') ? { etag: response.headers.get('etag')! } : {})
+ }
+ }
+
+ async createLabel(
+ repository: string,
+ input: { name: string; color: string; description?: string }
+ ): Promise<GitHubRepositoryLabel> {
+ safeRepository(repository)
+ if (!string(input.name, 50) || !input.name.trim() || !/^[0-9a-fA-F]{6}$/.test(input.color) ||
+ (input.description !== undefined && !string(input.description, 100))) {
+ throw new GitHubClientError('invalid-request')
+ }
+ const response = await this.request(`/repos/${repository}/labels`, {
+ method: 'POST', body: JSON.stringify(input)
+ })
+ const value = await this.json(response)
+ const base = issueLabel(value)
+ const item = object(value)
+ if (!base || !item || !(item.description === null || string(item.description, 1_000))) {
+ throw new GitHubClientError('malformed-response')
+ }
+ return { ...base, description: item.description }
+ }
+
+ private async request(path: string, init: RequestInit): Promise<Response> {
+ const url = new URL(path, API_ORIGIN)
+ if (url.origin !== API_ORIGIN) throw new GitHubClientError('invalid-request')
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs)
+ let response: Response
+ try {
+ response = await this.fetcher(url, {
+ ...init,
+ redirect: 'manual',
+ signal: controller.signal,
+ headers: {
+ accept: 'application/vnd.github+json',
+ authorization: `Bearer ${this.options.token}`,
+ 'x-github-api-version': API_VERSION,
+ ...(init.body ? { 'content-type': 'application/json' } : {}),
+ ...init.headers
+ }
+ })
+ } catch {
+ throw new GitHubClientError('request-failed')
+ } finally {
+ clearTimeout(timer)
+ }
+ if (response.status === 304) return response
+ if (response.status === 403 || response.status === 429) {
+ const retryAfter = Number(response.headers.get('retry-after'))
+ const reset = Number(response.headers.get('x-ratelimit-reset')) * 1_000
+ const remaining = response.headers.get('x-ratelimit-remaining')
+ const metadata = response.status === 403 ? await boundedErrorMetadata(response) : ''
+ const primary = response.status === 403 && remaining === '0'
+ const secondaryEvidence = /secondary rate limit|abuse detection|secondary-rate-limits/.test(metadata)
+ const secondary = response.status === 429 ||
+ (response.status === 403 && !primary && (
+ (Number.isFinite(retryAfter) && retryAfter > 0) || secondaryEvidence
+ ))
+ if (!primary && !secondary) {
+ throw new GitHubClientError('insufficient-permission', response.status)
+ }
+ const retryAt = Number.isFinite(retryAfter) && retryAfter > 0
+ ? Date.now() + retryAfter * 1_000
+ : primary && Number.isFinite(reset) && reset > 0
+ ? reset
+ : Date.now() + this.secondaryBackoffMs
+ if (secondary && !(Number.isFinite(retryAfter) && retryAfter > 0)) {
+ this.secondaryBackoffMs = Math.min(this.secondaryBackoffMs * 2, 60_000)
+ }
+ throw new GitHubClientError('rate-limited', response.status, retryAt)
+ }
+ if (!response.ok) throw new GitHubClientError('request-failed', response.status)
+ return response
+ }
+
+ private async json(response: Response): Promise<unknown> {
+ const length = Number(response.headers.get('content-length'))
+ if (Number.isFinite(length) && length > this.maximum) {
+ throw new GitHubClientError('response-too-large')
+ }
+ if (!response.body) throw new GitHubClientError('malformed-response')
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let total = 0
+ while (true) {
+ const next = await reader.read()
+ if (next.done) break
+ total += next.value.byteLength
+ if (total > this.maximum) {
+ await reader.cancel()
+ throw new GitHubClientError('response-too-large')
+ }
+ chunks.push(next.value)
+ }
+ const bytes = new Uint8Array(total)
+ let offset = 0
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }
+ try {
+ return JSON.parse(new TextDecoder().decode(bytes)) as unknown
+ } catch {
+ throw new GitHubClientError('malformed-response')
+ }
+ }
+}
diff --git a/src/core/github/config.test.ts b/src/core/github/config.test.ts
new file mode 100644
index 000000000..572278eef
--- /dev/null
+++ b/src/core/github/config.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest'
+import { normaliseProjectKanbanGitHub, parseGitHubRepository } from './config'
+
+const columns = [
+ { id: 'todo', title: 'To Do', color: '#0a84ff' },
+ { id: 'done', title: 'Done', color: '#30d158' }
+]
+
+describe('parseGitHubRepository', () => {
+ it.each([
+ ['https://github.com/nodeterm/nodeterm.git', 'nodeterm/nodeterm'],
+ ['[email protected]:nodeterm/nodeterm.git', 'nodeterm/nodeterm'],
+ ['ssh://[email protected]/nodeterm/nodeterm.git', 'nodeterm/nodeterm'],
+ [' Nodeterm/NodeTerm ', 'Nodeterm/NodeTerm']
+ ])('normalises %s', (input, expected) => {
+ expect(parseGitHubRepository(input)).toBe(expected)
+ })
+
+ it.each(['', 'owner', 'https://gitlab.com/o/r', 'https://github.com/o/r/issues', '-o/r'])
+ ('rejects %s', (input) => {
+ expect(parseGitHubRepository(input)).toBeNull()
+ })
+})
+
+describe('normaliseProjectKanbanGitHub', () => {
+ it('trims mappings and returns a stable canonical value', () => {
+ const result = normaliseProjectKanbanGitHub({
+ repository: ' https://github.com/nodeterm/nodeterm.git ',
+ columnMappings: [
+ { columnId: 'todo', label: ' status:todo ' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done'
+ }, columns)
+
+ expect(result).toMatchObject({
+ ok: true,
+ value: {
+ repository: 'nodeterm/nodeterm',
+ columnMappings: [
+ { columnId: 'todo', label: 'status:todo' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done'
+ }
+ })
+ if (result.ok) expect(result.value.revision).toMatch(/^[0-9a-f]{64}$/)
+ })
+
+ it('normalises Unicode labels before duplicate checks and persistence', () => {
+ const result = normaliseProjectKanbanGitHub({
+ columnMappings: [
+ { columnId: 'todo', label: ' status:cafe\u0301 ' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done'
+ }, columns)
+ expect(result).toMatchObject({ ok: true, value: {
+ columnMappings: [
+ { columnId: 'todo', label: 'status:café' },
+ { columnId: 'done', label: 'status:done' }
+ ]
+ } })
+ })
+
+ it.each([
+ [{ columnMappings: [{ columnId: 'missing', label: 'status:todo' }] }, 'unknown-column'],
+ [{ columnMappings: [{ columnId: 'todo', label: '' }] }, 'empty-label'],
+ [{ columnMappings: [
+ { columnId: 'todo', label: 'Status:Todo' },
+ { columnId: 'done', label: 'status:todo' }
+ ] }, 'duplicate-label'],
+ [{ columnMappings: [
+ { columnId: 'todo', label: 'status:todo' },
+ { columnId: 'todo', label: 'status:backlog' }
+ ] }, 'duplicate-column'],
+ [{ columnMappings: [], completionColumnId: 'missing' }, 'invalid-completion-column'],
+ [{ columnMappings: [{ columnId: 'todo', label: 'status:todo' }], completionColumnId: 'done' }, 'invalid-completion-column'],
+ [{ repository: 'https://gitlab.com/o/r', columnMappings: [] }, 'invalid-repository'],
+ [{ columnMappings: [{ columnId: 'todo', label: 'x'.repeat(51) }] }, 'label-too-long']
+ ])('rejects invalid configuration with %s', (input, reason) => {
+ expect(normaliseProjectKanbanGitHub(input, columns)).toEqual({ ok: false, reason })
+ })
+})
diff --git a/src/core/github/config.ts b/src/core/github/config.ts
new file mode 100644
index 000000000..fa1de8bfa
--- /dev/null
+++ b/src/core/github/config.ts
@@ -0,0 +1,104 @@
+import { createHash } from 'node:crypto'
+import type { KanbanColumn } from '../../shared/types'
+import type {
+ GitHubConfigResult,
+ NormalisedProjectKanbanGitHub
+} from '../../shared/github-issues'
+
+const OWNER = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?'
+const REPOSITORY = '[A-Za-z0-9_.-]+'
+const REPOSITORY_PATH = new RegExp(`^(${OWNER})/(${REPOSITORY})$`)
+
+export function parseGitHubRepository(input: unknown): string | null {
+ if (typeof input !== 'string') return null
+ let value = input.trim()
+ if (!value) return null
+
+ const scp = value.match(/^git@github\.com:([^/]+\/[^/]+)$/i)
+ if (scp) value = scp[1]
+ else if (/^https?:\/\//i.test(value) || /^ssh:\/\//i.test(value)) {
+ let url: URL
+ try {
+ url = new URL(value)
+ } catch {
+ return null
+ }
+ if (url.hostname.toLowerCase() !== 'github.com' || url.search || url.hash) return null
+ value = url.pathname.replace(/^\//, '')
+ }
+
+ value = value.replace(/\.git$/i, '')
+ const match = value.match(REPOSITORY_PATH)
+ if (!match) return null
+ const [, owner, repository] = match
+ if (repository === '.' || repository === '..' || repository.startsWith('-')) return null
+ return `${owner}/${repository}`
+}
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null
+}
+
+export function normaliseProjectKanbanGitHub(
+ input: unknown,
+ columns: readonly KanbanColumn[]
+): GitHubConfigResult {
+ const value = record(input)
+ if (!value || !Array.isArray(value.columnMappings)) {
+ return { ok: false, reason: 'invalid-shape' }
+ }
+
+ let repository: string | undefined
+ if (value.repository !== undefined) {
+ repository = parseGitHubRepository(value.repository) ?? undefined
+ if (!repository) return { ok: false, reason: 'invalid-repository' }
+ }
+
+ const columnIds = new Set(columns.map((column) => column.id))
+ const seenColumns = new Set<string>()
+ const seenLabels = new Set<string>()
+ const mappings: Array<{ columnId: string; label: string }> = []
+ for (const candidate of value.columnMappings) {
+ const mapping = record(candidate)
+ if (!mapping || typeof mapping.columnId !== 'string' || typeof mapping.label !== 'string') {
+ return { ok: false, reason: 'invalid-shape' }
+ }
+ const columnId = mapping.columnId.trim()
+ const label = mapping.label.trim().normalize('NFKC')
+ if (!columnIds.has(columnId)) return { ok: false, reason: 'unknown-column' }
+ if (seenColumns.has(columnId)) return { ok: false, reason: 'duplicate-column' }
+ if (!label) return { ok: false, reason: 'empty-label' }
+ if (label.length > 50) return { ok: false, reason: 'label-too-long' }
+ const folded = label.toLocaleLowerCase('en-US')
+ if (seenLabels.has(folded)) return { ok: false, reason: 'duplicate-label' }
+ seenColumns.add(columnId)
+ seenLabels.add(folded)
+ mappings.push({ columnId, label })
+ }
+
+ let completionColumnId: string | undefined
+ if (value.completionColumnId !== undefined) {
+ if (typeof value.completionColumnId !== 'string') {
+ return { ok: false, reason: 'invalid-completion-column' }
+ }
+ completionColumnId = value.completionColumnId.trim()
+ if (!columnIds.has(completionColumnId) || !seenColumns.has(completionColumnId)) {
+ return { ok: false, reason: 'invalid-completion-column' }
+ }
+ }
+
+ const order = new Map(columns.map((column, index) => [column.id, index]))
+ mappings.sort((a, b) => order.get(a.columnId)! - order.get(b.columnId)!)
+ const canonical = {
+ ...(repository ? { repository } : {}),
+ columnMappings: mappings,
+ ...(completionColumnId ? { completionColumnId } : {})
+ }
+ const normalised: NormalisedProjectKanbanGitHub = {
+ ...canonical,
+ revision: createHash('sha256').update(JSON.stringify(canonical)).digest('hex')
+ }
+ return { ok: true, value: normalised }
+}
diff --git a/src/core/github/control-store.test.ts b/src/core/github/control-store.test.ts
new file mode 100644
index 000000000..e2da63bb8
--- /dev/null
+++ b/src/core/github/control-store.test.ts
@@ -0,0 +1,110 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { GitHubControlStore } from './control-store'
+
+let userDataDir: string
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-control-'))
+})
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+describe('GitHubControlStore', () => {
+ it('persists an approval with a revision and mode 0600', async () => {
+ const store = new GitHubControlStore(userDataDir)
+ const state = await store.approve({
+ expectedRevision: 0,
+ localApprovalId: 'local-a',
+ projectId: 'project-a',
+ repository: 'nodeterm/nodeterm'
+ })
+
+ expect(state).toMatchObject({
+ version: 1,
+ revision: 1,
+ approvals: [{
+ localApprovalId: 'local-a',
+ projectId: 'project-a',
+ repository: 'nodeterm/nodeterm',
+ enabled: true
+ }]
+ })
+ const stat = await fs.stat(path.join(userDataDir, 'github-issues-control.json'))
+ expect(stat.mode & 0o777).toBe(0o600)
+ })
+
+ it('does not let a stale client restore a revoked approval', async () => {
+ const store = new GitHubControlStore(userDataDir)
+ const approved = await store.approve({
+ expectedRevision: 0,
+ localApprovalId: 'local-a',
+ projectId: 'project-a',
+ repository: 'nodeterm/nodeterm'
+ })
+ const revoked = await store.revoke({
+ expectedRevision: approved.revision,
+ localApprovalId: 'local-a'
+ })
+
+ await expect(store.approve({
+ expectedRevision: approved.revision,
+ localApprovalId: 'local-a',
+ projectId: 'project-a',
+ repository: 'nodeterm/nodeterm'
+ })).rejects.toMatchObject({ code: 'revision-conflict' })
+ expect(revoked.approvals).toEqual([])
+ expect((await store.load()).approvals).toEqual([])
+ })
+
+ it('requires the local identity and canonical repository', async () => {
+ const store = new GitHubControlStore(userDataDir)
+ await expect(store.approve({
+ expectedRevision: 0,
+ localApprovalId: '',
+ projectId: 'project-a',
+ repository: 'nodeterm/nodeterm'
+ })).rejects.toMatchObject({ code: 'invalid-control-input' })
+ await expect(store.approve({
+ expectedRevision: 0,
+ localApprovalId: 'local-a',
+ projectId: 'project-a',
+ repository: 'https://gitlab.com/a/b'
+ })).rejects.toMatchObject({ code: 'invalid-control-input' })
+ })
+
+ it('changes provider without replacing approvals', async () => {
+ const store = new GitHubControlStore(userDataDir)
+ const approved = await store.approve({
+ expectedRevision: 0,
+ localApprovalId: 'local-a',
+ projectId: 'project-a',
+ repository: 'nodeterm/nodeterm'
+ })
+ const selected = await store.selectProvider({
+ expectedRevision: approved.revision,
+ provider: 'token'
+ })
+ expect(selected.authProvider).toBe('token')
+ expect(selected.approvals).toEqual(approved.approvals)
+ })
+
+ it('treats a malformed file as empty instead of trusting its approvals', async () => {
+ await fs.writeFile(path.join(userDataDir, 'github-issues-control.json'), JSON.stringify({
+ version: 1,
+ revision: 7,
+ authProvider: 'auto',
+ approvals: [{ localApprovalId: '', projectId: 'p', repository: 'o/r', enabled: true }]
+ }))
+ expect(await new GitHubControlStore(userDataDir).load()).toEqual({
+ version: 1,
+ revision: 0,
+ authProvider: 'auto',
+ approvals: []
+ })
+ })
+})
diff --git a/src/core/github/control-store.ts b/src/core/github/control-store.ts
new file mode 100644
index 000000000..731e298d6
--- /dev/null
+++ b/src/core/github/control-store.ts
@@ -0,0 +1,164 @@
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import type {
+ GitHubAuthProvider,
+ GitHubControlState,
+ GitHubProjectApproval
+} from '../../shared/github-issues'
+import { parseGitHubRepository } from './config'
+
+const FILE_NAME = 'github-issues-control.json'
+const EMPTY_STATE: GitHubControlState = {
+ version: 1,
+ revision: 0,
+ authProvider: 'auto',
+ approvals: []
+}
+
+export class GitHubControlError extends Error {
+ constructor(readonly code: 'revision-conflict' | 'invalid-control-input') {
+ super(code)
+ }
+}
+
+type ApprovalInput = {
+ expectedRevision: number
+ localApprovalId: string
+ projectId: string
+ repository: string
+}
+
+function validString(value: unknown, max = 512): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= max
+}
+
+function validApproval(value: unknown): value is GitHubProjectApproval {
+ if (!value || typeof value !== 'object') return false
+ const approval = value as GitHubProjectApproval
+ return validString(approval.localApprovalId, 128) &&
+ validString(approval.projectId, 256) &&
+ parseGitHubRepository(approval.repository) === approval.repository &&
+ approval.enabled === true &&
+ Number.isSafeInteger(approval.approvedAt) && approval.approvedAt > 0
+}
+
+function validState(value: unknown): value is GitHubControlState {
+ if (!value || typeof value !== 'object') return false
+ const state = value as GitHubControlState
+ return state.version === 1 &&
+ Number.isSafeInteger(state.revision) && state.revision >= 0 &&
+ (state.authProvider === 'auto' || state.authProvider === 'gh' || state.authProvider === 'token') &&
+ Array.isArray(state.approvals) && state.approvals.every(validApproval)
+}
+
+export class GitHubControlStore {
+ private writeQueue: Promise<void> = Promise.resolve()
+
+ constructor(private readonly userDataDir: string) {}
+
+ private get filePath(): string {
+ return path.join(this.userDataDir, FILE_NAME)
+ }
+
+ async load(): Promise<GitHubControlState> {
+ try {
+ const parsed: unknown = JSON.parse(await fs.readFile(this.filePath, 'utf-8'))
+ return validState(parsed) ? structuredClone(parsed) : structuredClone(EMPTY_STATE)
+ } catch {
+ return structuredClone(EMPTY_STATE)
+ }
+ }
+
+ approve(input: ApprovalInput): Promise<GitHubControlState> {
+ return this.mutate(input.expectedRevision, (state) => {
+ if (!validString(input.localApprovalId, 128) ||
+ !validString(input.projectId, 256) ||
+ parseGitHubRepository(input.repository) !== input.repository) {
+ throw new GitHubControlError('invalid-control-input')
+ }
+ const approval: GitHubProjectApproval = {
+ localApprovalId: input.localApprovalId,
+ projectId: input.projectId,
+ repository: input.repository,
+ enabled: true,
+ approvedAt: Date.now()
+ }
+ return {
+ ...state,
+ approvals: [
+ ...state.approvals.filter((item) => item.localApprovalId !== input.localApprovalId),
+ approval
+ ]
+ }
+ })
+ }
+
+ revoke(input: { expectedRevision: number; localApprovalId: string }): Promise<GitHubControlState> {
+ return this.mutate(input.expectedRevision, (state) => {
+ if (!validString(input.localApprovalId, 128)) {
+ throw new GitHubControlError('invalid-control-input')
+ }
+ return {
+ ...state,
+ approvals: state.approvals.filter((item) => item.localApprovalId !== input.localApprovalId)
+ }
+ })
+ }
+
+ selectProvider(input: {
+ expectedRevision: number
+ provider: GitHubAuthProvider
+ }): Promise<GitHubControlState> {
+ return this.mutate(input.expectedRevision, (state) => {
+ if (input.provider !== 'auto' && input.provider !== 'gh' && input.provider !== 'token') {
+ throw new GitHubControlError('invalid-control-input')
+ }
+ return { ...state, authProvider: input.provider }
+ })
+ }
+
+ isApproved(
+ state: GitHubControlState,
+ input: { localApprovalId: string; projectId: string; repository: string }
+ ): boolean {
+ return state.approvals.some((approval) => approval.enabled &&
+ approval.localApprovalId === input.localApprovalId &&
+ approval.projectId === input.projectId &&
+ approval.repository === input.repository)
+ }
+
+ private mutate(
+ expectedRevision: number,
+ change: (state: GitHubControlState) => GitHubControlState
+ ): Promise<GitHubControlState> {
+ let resolveResult: (state: GitHubControlState) => void
+ let rejectResult: (error: unknown) => void
+ const result = new Promise<GitHubControlState>((resolve, reject) => {
+ resolveResult = resolve
+ rejectResult = reject
+ })
+ this.writeQueue = this.writeQueue.then(async () => {
+ try {
+ const current = await this.load()
+ if (!Number.isSafeInteger(expectedRevision) || current.revision !== expectedRevision) {
+ throw new GitHubControlError('revision-conflict')
+ }
+ const next = { ...change(current), revision: current.revision + 1 }
+ await this.write(next)
+ resolveResult(structuredClone(next))
+ } catch (error) {
+ rejectResult(error)
+ }
+ })
+ return result
+ }
+
+ private async write(state: GitHubControlState): Promise<void> {
+ await fs.mkdir(this.userDataDir, { recursive: true })
+ const temporary = `${this.filePath}.tmp`
+ await fs.writeFile(temporary, JSON.stringify(state), { encoding: 'utf-8', mode: 0o600 })
+ await fs.chmod(temporary, 0o600)
+ await fs.rename(temporary, this.filePath)
+ await fs.chmod(this.filePath, 0o600)
+ }
+}
diff --git a/src/core/github/credentials.test.ts b/src/core/github/credentials.test.ts
new file mode 100644
index 000000000..0196ff586
--- /dev/null
+++ b/src/core/github/credentials.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from 'vitest'
+import {
+ CREDENTIAL_CACHE_MS,
+ GitHubCredentialResolver,
+ type CommandRunner,
+ type GitHubSecretStore
+} from './credentials'
+import type { GitHubAuthProvider } from '../../shared/github-issues'
+
+function fixture(options: {
+ gh?: 'valid' | 'invalid' | 'missing'
+ storedToken?: string | null
+ validTokens?: Record<string, string>
+ storage?: GitHubSecretStore['availability']
+}) {
+ const calls: string[] = []
+ const run: CommandRunner = async (_command, args) => {
+ calls.push(args.join(' '))
+ if (options.gh === 'missing') return { ok: false, stdout: '', stderr: 'not found' }
+ if (args[1] === 'status') {
+ return options.gh === 'valid'
+ ? { ok: true, stdout: '', stderr: '' }
+ : { ok: false, stdout: '', stderr: 'not logged in' }
+ }
+ return { ok: true, stdout: 'gh-token\n', stderr: '' }
+ }
+ const secret: GitHubSecretStore = {
+ availability: options.storage ?? 'encrypted',
+ readForHost: async () => options.storedToken ?? null,
+ save: async () => undefined,
+ clear: async () => undefined
+ }
+ const resolver = new GitHubCredentialResolver({
+ run,
+ secret,
+ validate: async (token) => {
+ const userId = options.validTokens?.[token]
+ return userId ? { userId, login: `login-${userId}` } : null
+ }
+ })
+ return { resolver, calls }
+}
+
+describe('GitHubCredentialResolver caching', () => {
+ function counted(now: () => number) {
+ let ghCalls = 0
+ let validations = 0
+ const run: CommandRunner = async (_command, args) => {
+ ghCalls += 1
+ if (args[1] === 'status') return { ok: true, stdout: '', stderr: '' }
+ return { ok: true, stdout: 'gh-token\n', stderr: '' }
+ }
+ const secret: GitHubSecretStore = {
+ availability: 'encrypted',
+ readForHost: async () => null,
+ save: async () => undefined,
+ clear: async () => undefined
+ }
+ const resolver = new GitHubCredentialResolver({
+ run,
+ secret,
+ validate: async () => {
+ validations += 1
+ return { userId: 'gh-user', login: 'octocat' }
+ },
+ now
+ })
+ return { resolver, counts: () => ({ ghCalls, validations }) }
+ }
+
+ it('resolves once for repeated calls inside the cache window', async () => {
+ // Every epoch re-check in the service calls resolve(). Uncached, each one spawns two `gh`
+ // processes AND spends a /user request that no rate-limit accounting can see.
+ let clock = 1_000
+ const { resolver, counts } = counted(() => clock)
+
+ await resolver.resolve('gh')
+ const first = counts()
+ expect(first.ghCalls).toBe(2)
+ expect(first.validations).toBe(1)
+
+ clock += 1_000
+ await resolver.resolve('gh')
+ await resolver.resolve('gh')
+ expect(counts()).toEqual(first)
+
+ clock += CREDENTIAL_CACHE_MS
+ await resolver.resolve('gh')
+ expect(counts().validations).toBe(2)
+ })
+
+ it('re-resolves immediately after the credential boundary moves', async () => {
+ let clock = 1_000
+ const { resolver, counts } = counted(() => clock)
+ await resolver.resolve('gh')
+ expect(counts().validations).toBe(1)
+
+ resolver.invalidate()
+
+ await resolver.resolve('gh')
+ expect(counts().validations).toBe(2)
+ })
+
+ it('caches each provider separately', async () => {
+ let clock = 1_000
+ const { resolver, counts } = counted(() => clock)
+ await resolver.resolve('gh')
+ await resolver.resolve('auto')
+ expect(counts().validations).toBe(2)
+ })
+})
+
+describe('GitHubCredentialResolver', () => {
+ const providerCases = [
+ ['auto', { gh: 'valid', storedToken: 'pat', validTokens: { 'gh-token': 'gh-user', pat: 'pat-user' } }, 'gh'],
+ ['auto', { gh: 'invalid', storedToken: 'pat', validTokens: { pat: 'pat-user' } }, 'token'],
+ ['gh', { gh: 'invalid', storedToken: 'pat', validTokens: { pat: 'pat-user' } }, null],
+ ['token', { gh: 'valid', storedToken: 'bad', validTokens: { 'gh-token': 'gh-user' } }, null]
+ ] satisfies Array<[GitHubAuthProvider, Parameters<typeof fixture>[0], 'gh' | 'token' | null]>
+
+ it.each(providerCases)('uses the exact %s provider fallback rule', async (provider, options, expected) => {
+ const { resolver } = fixture(options)
+ expect((await resolver.resolve(provider))?.provider ?? null).toBe(expected)
+ })
+
+ it('does not read the stored token when GitHub CLI succeeds in auto mode', async () => {
+ let secretReads = 0
+ const secret: GitHubSecretStore = {
+ availability: 'encrypted',
+ readForHost: async () => { secretReads += 1; return 'pat' },
+ save: async () => undefined,
+ clear: async () => undefined
+ }
+ const resolver = new GitHubCredentialResolver({
+ run: async (_command, args) => args[1] === 'status'
+ ? { ok: true, stdout: '', stderr: '' }
+ : { ok: true, stdout: 'gh-token', stderr: '' },
+ secret,
+ validate: async () => ({ userId: '1', login: 'octocat' })
+ })
+ expect((await resolver.resolve('auto'))?.provider).toBe('gh')
+ expect(secretReads).toBe(0)
+ })
+
+ it('returns presence and provider status without credential material', async () => {
+ const { resolver } = fixture({
+ gh: 'invalid',
+ storedToken: 'super-secret-token',
+ validTokens: { 'super-secret-token': 'pat-user' },
+ storage: 'restricted-file'
+ })
+ const status = await resolver.status('auto')
+ expect(status).toEqual({
+ selectedProvider: 'auto',
+ activeProvider: 'token',
+ ghAuthenticated: false,
+ tokenPresent: true,
+ storage: 'restricted-file',
+ login: 'login-pat-user'
+ })
+ expect(JSON.stringify(status)).not.toContain('super-secret-token')
+ })
+
+ it('validates GitHub CLI auth before asking it for a token', async () => {
+ const { resolver, calls } = fixture({ gh: 'invalid', storedToken: null })
+ await resolver.resolve('gh')
+ expect(calls).toEqual(['auth status --hostname github.com'])
+ })
+})
diff --git a/src/core/github/credentials.ts b/src/core/github/credentials.ts
new file mode 100644
index 000000000..e37dd04f9
--- /dev/null
+++ b/src/core/github/credentials.ts
@@ -0,0 +1,140 @@
+import type {
+ GitHubAuthProvider,
+ GitHubAuthStatus,
+ GitHubSecretAvailability
+} from '../../shared/github-issues'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+
+export type CommandResult = { ok: boolean; stdout: string; stderr: string }
+export type CommandRunner = (command: string, args: string[]) => Promise<CommandResult>
+
+const execute = promisify(execFile)
+
+export const runGitHubCliCommand: CommandRunner = async (command, args) => {
+ if (command !== 'gh') return { ok: false, stdout: '', stderr: 'unsupported command' }
+ try {
+ const result = await execute(command, args, {
+ timeout: 15_000,
+ maxBuffer: 1024 * 1024,
+ env: {
+ ...process.env,
+ PATH: `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin${process.env.PATH ? `:${process.env.PATH}` : ''}`
+ }
+ })
+ return { ok: true, stdout: result.stdout, stderr: result.stderr }
+ } catch (error) {
+ const failure = error as { stdout?: string; stderr?: string; message?: string }
+ return {
+ ok: false,
+ stdout: failure.stdout ?? '',
+ stderr: failure.stderr || failure.message || 'GitHub CLI failed'
+ }
+ }
+}
+
+export interface GitHubSecretStore {
+ readonly availability: GitHubSecretAvailability
+ readForHost(): Promise<string | null>
+ save(token: string): Promise<void>
+ clear(): Promise<void>
+}
+
+export interface ValidatedGitHubIdentity {
+ userId: string
+ login: string
+}
+
+export interface ResolvedGitHubCredential extends ValidatedGitHubIdentity {
+ provider: 'gh' | 'token'
+ token: string
+}
+
+type ResolverDependencies = {
+ run: CommandRunner
+ secret: GitHubSecretStore
+ validate(token: string): Promise<ValidatedGitHubIdentity | null>
+ now?: () => number
+}
+
+/** How long one resolved credential is reused. The service re-checks its epoch before every read
+ * and around every write, and each check calls resolve() — which, uncached, spawns `gh auth
+ * status` + `gh auth token` AND spends a GET /user request. Those /user calls never pass through
+ * the request coordinator, so they are neither rate-limited nor backed off: a single full sync of
+ * a large repository could fire hundreds of them, trip GitHub's secondary limiter, and surface as
+ * "not authenticated" to a user who is signed in perfectly well. Short enough that an external
+ * `gh auth logout` is noticed promptly; every in-app credential change calls invalidate() instead
+ * of waiting for it. */
+export const CREDENTIAL_CACHE_MS = 30_000
+
+type CacheEntry = { at: number; value: ResolvedGitHubCredential | null }
+
+export class GitHubCredentialResolver {
+ private readonly cache = new Map<GitHubAuthProvider, CacheEntry>()
+ private readonly now: () => number
+
+ constructor(private readonly dependencies: ResolverDependencies) {
+ this.now = dependencies.now ?? Date.now
+ }
+
+ async resolve(provider: GitHubAuthProvider): Promise<ResolvedGitHubCredential | null> {
+ const cached = this.cache.get(provider)
+ const at = this.now()
+ if (cached && at - cached.at < CREDENTIAL_CACHE_MS) return cached.value
+ const value = await this.resolveUncached(provider)
+ // A null answer is cached too: "gh is logged out" is exactly the state that would otherwise
+ // re-spawn two processes on every epoch check of every failing refresh.
+ this.cache.set(provider, { at, value })
+ return value
+ }
+
+ /** Drop the memo the moment the credential boundary moves (token saved/cleared, provider
+ * switched, project revoked) so the next resolve reflects the new reality immediately. */
+ invalidate(): void {
+ this.cache.clear()
+ }
+
+ private async resolveUncached(provider: GitHubAuthProvider): Promise<ResolvedGitHubCredential | null> {
+ if (provider === 'gh') return this.fromGitHubCli()
+ if (provider === 'token') return this.fromStoredToken()
+ return (await this.fromGitHubCli()) ?? this.fromStoredToken()
+ }
+
+ async status(provider: GitHubAuthProvider): Promise<GitHubAuthStatus> {
+ const gh = await this.fromGitHubCli()
+ const stored = await this.dependencies.secret.readForHost()
+ const tokenIdentity = stored ? await this.dependencies.validate(stored) : null
+ const active = provider === 'gh'
+ ? gh
+ : provider === 'token'
+ ? tokenIdentity && stored ? { ...tokenIdentity, provider: 'token' as const, token: stored } : null
+ : gh ?? (tokenIdentity && stored
+ ? { ...tokenIdentity, provider: 'token' as const, token: stored }
+ : null)
+ return {
+ selectedProvider: provider,
+ activeProvider: active?.provider ?? null,
+ ghAuthenticated: gh !== null,
+ tokenPresent: stored !== null,
+ storage: this.dependencies.secret.availability,
+ ...(active ? { login: active.login } : {})
+ }
+ }
+
+ private async fromGitHubCli(): Promise<ResolvedGitHubCredential | null> {
+ const status = await this.dependencies.run('gh', ['auth', 'status', '--hostname', 'github.com'])
+ if (!status.ok) return null
+ const result = await this.dependencies.run('gh', ['auth', 'token', '--hostname', 'github.com'])
+ const token = result.ok ? result.stdout.trim() : ''
+ if (!token) return null
+ const identity = await this.dependencies.validate(token)
+ return identity ? { ...identity, provider: 'gh', token } : null
+ }
+
+ private async fromStoredToken(): Promise<ResolvedGitHubCredential | null> {
+ const token = await this.dependencies.secret.readForHost()
+ if (!token) return null
+ const identity = await this.dependencies.validate(token)
+ return identity ? { ...identity, provider: 'token', token } : null
+ }
+}
diff --git a/src/core/github/handlers.test.ts b/src/core/github/handlers.test.ts
new file mode 100644
index 000000000..24b5d37ef
--- /dev/null
+++ b/src/core/github/handlers.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest'
+import { fakePlatform } from '../platform-fake'
+import { IPC } from '../../shared/ipc'
+import { registerGitHubIssueHandlers } from './handlers'
+
+describe('registerGitHubIssueHandlers', () => {
+ it('attributes subscriptions to the sender and exposes only domain operations', async () => {
+ const calls: unknown[][] = []
+ const page = { items: [], counts: {}, partial: false, readOnly: false }
+ const service = {
+ subscribe: async (...args: unknown[]) => { calls.push(['subscribe', ...args]); return page },
+ unsubscribe: (...args: unknown[]) => { calls.push(['unsubscribe', ...args]) },
+ query: async (...args: unknown[]) => { calls.push(['query', ...args]); return page },
+ refresh: async (...args: unknown[]) => { calls.push(['refresh', ...args]) },
+ moveIssue: async (...args: unknown[]) => {
+ calls.push(['move', ...args]); return { status: 'configuration-changed' as const }
+ },
+ createMissingLabels: async (...args: unknown[]) => {
+ calls.push(['labels', ...args]); return { status: 'confirmed' as const, created: [], remaining: [] }
+ },
+ clearCache: async (...args: unknown[]) => { calls.push(['clear', ...args]) }
+ }
+ const platform = fakePlatform()
+ registerGitHubIssueHandlers(platform, service)
+
+ await platform.handlers[IPC.githubIssuesSubscribe](7, { projectId: 'p1' })
+ platform.senderListeners[IPC.githubIssuesUnsubscribe](7, 'p1')
+ await platform.handlers[IPC.githubIssuesQuery]({ projectId: 'p1', columnId: null, pageSize: 50 })
+ expect(calls).toEqual([
+ ['subscribe', 7, { projectId: 'p1' }],
+ ['unsubscribe', 7, 'p1'],
+ ['query', { projectId: 'p1', columnId: null, pageSize: 50 }]
+ ])
+ 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
new file mode 100644
index 000000000..fa9dcbd2f
--- /dev/null
+++ b/src/core/github/handlers.ts
@@ -0,0 +1,41 @@
+import type { CorePlatform } from '../platform'
+import { IPC } from '../../shared/ipc'
+import type {
+ CreateMappedLabelsResult,
+ GitHubIssuePage,
+ GitHubIssueQuery,
+ GitHubMutationResult
+} from '../../shared/github-issues'
+
+export interface GitHubIssueHandlerService {
+ subscribe(uiId: number, request: { projectId: string }): Promise<GitHubIssuePage>
+ unsubscribe(uiId: number, projectId: string): void
+ query(request: GitHubIssueQuery): Promise<GitHubIssuePage>
+ refresh(request: { projectId: string; full?: boolean }): Promise<void>
+ moveIssue(request: {
+ projectId: string
+ issueNumber: number
+ toColumnId: string | null
+ expectedUpdatedAt: string
+ }): Promise<GitHubMutationResult>
+ createMissingLabels(request: { projectId: string }): Promise<CreateMappedLabelsResult>
+ clearCache(request: { projectId: string }): Promise<void>
+}
+
+export function registerGitHubIssueHandlers(
+ platform: CorePlatform,
+ service: GitHubIssueHandlerService
+): void {
+ platform.handleWithSender(IPC.githubIssuesSubscribe, (uiId, request: { projectId: string }) =>
+ service.subscribe(uiId, request))
+ platform.onWithSender(IPC.githubIssuesUnsubscribe, (uiId, projectId: string) =>
+ service.unsubscribe(uiId, projectId))
+ platform.handle(IPC.githubIssuesQuery, (request: GitHubIssueQuery) => service.query(request))
+ platform.handle(IPC.githubIssuesRefresh, (projectId: string, full?: boolean) =>
+ service.refresh({ projectId, full }))
+ platform.handle(IPC.githubIssuesMove, (request) => service.moveIssue(request))
+ platform.handle(IPC.githubIssuesCreateLabels, (projectId: string) =>
+ service.createMissingLabels({ projectId }))
+ platform.handle(IPC.githubIssuesClearCache, (projectId: string) =>
+ service.clearCache({ projectId }))
+}
diff --git a/src/core/github/host.test.ts b/src/core/github/host.test.ts
new file mode 100644
index 000000000..fd56452a3
--- /dev/null
+++ b/src/core/github/host.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { Project } from '../../shared/types'
+import type { GitHubControlState } from '../../shared/github-issues'
+import { GitHubHostController, GitHubHostError } from './host'
+
+const project: Project = {
+ id: 'project-1',
+ name: 'Test',
+ color: '#8b5cf6',
+ cwd: '/repo',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [],
+ kanban: {
+ columns: [
+ { id: 'todo', title: 'Todo', color: '#2563eb' },
+ { id: 'done', title: 'Done', color: '#16a34a' }
+ ],
+ assignments: [],
+ github: {
+ columnMappings: [
+ { columnId: 'todo', label: 'status:todo' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done'
+ }
+ }
+}
+
+function fixture() {
+ let state: GitHubControlState = {
+ version: 1,
+ revision: 0,
+ authProvider: 'auto',
+ approvals: []
+ }
+ let token = 'secret'
+ const secret = {
+ availability: 'encrypted' as const,
+ readForHost: vi.fn(async () => token || null),
+ save: vi.fn(async (value: string) => { token = value }),
+ clear: vi.fn(async () => { token = '' })
+ }
+ const controls = {
+ load: vi.fn(async () => structuredClone(state)),
+ isApproved: vi.fn((current: GitHubControlState, input: {
+ localApprovalId: string
+ projectId: string
+ repository: string
+ }) => current.approvals.some((item) => item.localApprovalId === input.localApprovalId &&
+ item.projectId === input.projectId && item.repository === input.repository)),
+ approve: vi.fn(async (input: {
+ expectedRevision: number
+ localApprovalId: string
+ projectId: string
+ repository: string
+ }) => {
+ state = {
+ ...state,
+ revision: state.revision + 1,
+ approvals: [{ ...input, enabled: true as const, approvedAt: 1 }]
+ }
+ return structuredClone(state)
+ }),
+ revoke: vi.fn(async () => {
+ state = { ...state, revision: state.revision + 1, approvals: [] }
+ return structuredClone(state)
+ }),
+ selectProvider: vi.fn(async (input: { provider: 'auto' | 'gh' | 'token' }) => {
+ state = { ...state, revision: state.revision + 1, authProvider: input.provider }
+ return structuredClone(state)
+ })
+ }
+ const resolver = {
+ status: vi.fn(async (provider: 'auto' | 'gh' | 'token') => ({
+ selectedProvider: provider,
+ activeProvider: token ? 'token' as const : null,
+ ghAuthenticated: false,
+ tokenPresent: !!token,
+ storage: secret.availability,
+ ...(token ? { login: 'octocat' } : {})
+ })),
+ resolve: vi.fn(async () => token ? {
+ provider: 'token' as const,
+ token,
+ userId: '1',
+ login: 'octocat'
+ } : null)
+ }
+ const client = {
+ listIssues: vi.fn(),
+ getIssue: vi.fn(),
+ updateIssue: vi.fn(),
+ listRepositoryLabels: vi.fn(),
+ createLabel: vi.fn()
+ }
+ const controller = new GitHubHostController({
+ project: vi.fn(async (id: string) => id === project.id
+ ? { project, localApprovalId: 'local-private-id' }
+ : null),
+ detectRepository: vi.fn(async () => 'owner/repo'),
+ controls,
+ resolver,
+ secret,
+ validateToken: vi.fn(async (value: string) => value === 'valid-token'
+ ? { userId: '1', login: 'octocat' }
+ : null),
+ client: vi.fn(() => client)
+ })
+ return { controller, controls, resolver, secret, client }
+}
+
+describe('GitHubHostController', () => {
+ it('returns a status view without tokens, approvals, or the local approval id', async () => {
+ const { controller, resolver } = fixture()
+ const view = await controller.status('project-1')
+ expect(view).toMatchObject({
+ control: { revision: 0, authProvider: 'auto' },
+ project: { repository: 'owner/repo', detectedRepository: 'owner/repo', approved: false }
+ })
+ expect(JSON.stringify(view)).not.toMatch(/secret|local-private-id|approvals/i)
+ expect(resolver.status).not.toHaveBeenCalled()
+ })
+
+ it('requires exact local approval before creating a service context', async () => {
+ const { controller } = fixture()
+ await expect(controller.contextForProject('project-1')).rejects.toMatchObject({ code: 'not-approved' })
+ await controller.approve({ projectId: 'project-1', repository: 'owner/repo', expectedRevision: 0 })
+ const context = await controller.contextForProject('project-1')
+ expect(context).toMatchObject({
+ projectId: 'project-1',
+ repository: 'owner/repo',
+ userId: '1',
+ columnColors: { todo: '#2563eb', done: '#16a34a' }
+ })
+ })
+
+ it('rejects approval for a repository other than the configured or detected repository', async () => {
+ const { controller } = fixture()
+ await expect(controller.approve({
+ projectId: 'project-1', repository: 'other/repo', expectedRevision: 0
+ })).rejects.toBeInstanceOf(GitHubHostError)
+ })
+
+ it('validates a token before saving and never returns it', async () => {
+ const { controller, secret } = fixture()
+ await expect(controller.saveToken('bad')).rejects.toMatchObject({ code: 'invalid-token' })
+ expect(secret.save).not.toHaveBeenCalled()
+ const view = await controller.saveToken('valid-token')
+ expect(secret.save).toHaveBeenCalledWith('valid-token')
+ expect(JSON.stringify(view)).not.toContain('valid-token')
+ })
+})
diff --git a/src/core/github/host.ts b/src/core/github/host.ts
new file mode 100644
index 000000000..5afd5cc0a
--- /dev/null
+++ b/src/core/github/host.ts
@@ -0,0 +1,240 @@
+import type { Project } from '../../shared/types'
+import type {
+ GitHubAuthProvider,
+ GitHubAuthStatus,
+ GitHubControlState,
+ GitHubControlView
+} from '../../shared/github-issues'
+import { normaliseProjectKanbanGitHub, parseGitHubRepository } from './config'
+import type { GitHubSecretStore, ResolvedGitHubCredential } from './credentials'
+import type {
+ GitHubIssueProjectContext,
+ GitHubIssueServiceContext,
+ GitHubIssuesClientLike
+} from './service'
+
+export class GitHubHostError extends Error {
+ constructor(readonly code:
+ | 'project-not-found'
+ | 'invalid-configuration'
+ | 'repository-not-found'
+ | 'repository-mismatch'
+ | 'not-approved'
+ | 'not-authenticated'
+ | 'invalid-token'
+ | 'configuration-changed') {
+ super(code)
+ }
+}
+
+type ProjectRecord = { project: Project; localApprovalId: string }
+
+type ControlStoreLike = {
+ load(): Promise<GitHubControlState>
+ approve(input: {
+ expectedRevision: number
+ localApprovalId: string
+ projectId: string
+ repository: string
+ }): Promise<GitHubControlState>
+ revoke(input: { expectedRevision: number; localApprovalId: string }): Promise<GitHubControlState>
+ selectProvider(input: {
+ expectedRevision: number
+ provider: GitHubAuthProvider
+ }): Promise<GitHubControlState>
+ isApproved(state: GitHubControlState, input: {
+ localApprovalId: string
+ projectId: string
+ repository: string
+ }): boolean
+}
+
+type CredentialResolverLike = {
+ resolve(provider: GitHubAuthProvider): Promise<ResolvedGitHubCredential | null>
+ status(provider: GitHubAuthProvider): Promise<GitHubAuthStatus>
+}
+
+type HostDependencies = {
+ project(projectId: string): Promise<ProjectRecord | null>
+ detectRepository(project: Project): Promise<string | null>
+ controls: ControlStoreLike
+ resolver: CredentialResolverLike
+ secret: GitHubSecretStore
+ validateToken(token: string): Promise<{ userId: string; login: string } | null>
+ client(token: string): GitHubIssuesClientLike
+ onCredentialBoundaryChange?(): void
+}
+
+type ResolvedProject = ProjectRecord & {
+ repository: string
+ detectedRepository?: string
+ config: GitHubIssueServiceContext['config']
+}
+
+export class GitHubHostController {
+ private credentialGeneration = 0
+
+ constructor(private readonly dependencies: HostDependencies) {}
+
+ async status(projectId?: string): Promise<GitHubControlView> {
+ const state = await this.dependencies.controls.load()
+ if (!projectId) {
+ return {
+ control: { revision: state.revision, authProvider: state.authProvider },
+ auth: await this.dependencies.resolver.status(state.authProvider)
+ }
+ }
+
+ const record = await this.dependencies.project(projectId)
+ if (!record) throw new GitHubHostError('project-not-found')
+ const detected = parseGitHubRepository(await this.dependencies.detectRepository(record.project)) ?? undefined
+ const configured = record.project.kanban?.github?.repository
+ ? parseGitHubRepository(record.project.kanban.github.repository) ?? undefined
+ : undefined
+ const repository = configured ?? detected
+ const approved = !!repository && this.dependencies.controls.isApproved(state, {
+ localApprovalId: record.localApprovalId,
+ projectId,
+ repository
+ })
+ const auth = approved
+ ? await this.dependencies.resolver.status(state.authProvider)
+ : {
+ selectedProvider: state.authProvider,
+ activeProvider: null,
+ ghAuthenticated: false,
+ tokenPresent: false,
+ storage: this.dependencies.secret.availability
+ }
+ return {
+ control: { revision: state.revision, authProvider: state.authProvider },
+ auth,
+ project: {
+ projectId,
+ ...(repository ? { repository } : {}),
+ ...(detected ? { detectedRepository: detected } : {}),
+ approved
+ }
+ }
+ }
+
+ async approve(input: {
+ projectId: string
+ repository: string
+ expectedRevision: number
+ }): Promise<GitHubControlView> {
+ const project = await this.resolveProject(input.projectId)
+ if (parseGitHubRepository(input.repository) !== project.repository) {
+ throw new GitHubHostError('repository-mismatch')
+ }
+ await this.dependencies.controls.approve({
+ ...input,
+ localApprovalId: project.localApprovalId,
+ repository: project.repository
+ })
+ return this.status(input.projectId)
+ }
+
+ async revoke(input: { projectId: string; expectedRevision: number }): Promise<GitHubControlView> {
+ const record = await this.dependencies.project(input.projectId)
+ if (!record) throw new GitHubHostError('project-not-found')
+ await this.dependencies.controls.revoke({
+ expectedRevision: input.expectedRevision,
+ localApprovalId: record.localApprovalId
+ })
+ this.dependencies.onCredentialBoundaryChange?.()
+ return this.status(input.projectId)
+ }
+
+ async selectProvider(input: {
+ provider: GitHubAuthProvider
+ expectedRevision: number
+ }): Promise<GitHubControlView> {
+ await this.dependencies.controls.selectProvider(input)
+ this.dependencies.onCredentialBoundaryChange?.()
+ return this.status()
+ }
+
+ async saveToken(token: string): Promise<GitHubControlView> {
+ const identity = await this.dependencies.validateToken(token)
+ if (!identity) throw new GitHubHostError('invalid-token')
+ await this.dependencies.secret.save(token)
+ this.credentialGeneration += 1
+ this.dependencies.onCredentialBoundaryChange?.()
+ return this.status()
+ }
+
+ async clearToken(): Promise<GitHubControlView> {
+ await this.dependencies.secret.clear()
+ this.credentialGeneration += 1
+ this.dependencies.onCredentialBoundaryChange?.()
+ return this.status()
+ }
+
+ async contextForProject(projectId: string): Promise<GitHubIssueServiceContext> {
+ const project = await this.projectContextForCache(projectId)
+ const state = await this.dependencies.controls.load()
+ if (state.revision !== project.controlRevision) {
+ throw new GitHubHostError('configuration-changed')
+ }
+ const credential = await this.dependencies.resolver.resolve(state.authProvider)
+ if (!credential) throw new GitHubHostError('not-authenticated')
+ return {
+ ...project,
+ credentialGeneration: this.credentialGeneration,
+ userId: credential.userId,
+ client: this.dependencies.client(credential.token)
+ }
+ }
+
+ async projectContextForCache(projectId: string): Promise<GitHubIssueProjectContext> {
+ const project = await this.resolveProject(projectId)
+ const state = await this.dependencies.controls.load()
+ if (!this.dependencies.controls.isApproved(state, {
+ localApprovalId: project.localApprovalId,
+ projectId,
+ repository: project.repository
+ })) throw new GitHubHostError('not-approved')
+ return this.cacheProjectContext(project, state.revision)
+ }
+
+ async projectContextForCacheDeletion(projectId: string): Promise<GitHubIssueProjectContext> {
+ const project = await this.resolveProject(projectId)
+ const state = await this.dependencies.controls.load()
+ return this.cacheProjectContext(project, state.revision)
+ }
+
+ private cacheProjectContext(
+ project: ResolvedProject,
+ controlRevision: number
+ ): GitHubIssueProjectContext {
+ return {
+ localApprovalId: project.localApprovalId,
+ projectId: project.project.id,
+ repository: project.repository,
+ config: project.config,
+ controlRevision,
+ columnColors: Object.fromEntries(
+ (project.project.kanban?.columns ?? []).map((column) => [column.id, column.color])
+ )
+ }
+ }
+
+ private async resolveProject(projectId: string): Promise<ResolvedProject> {
+ const record = await this.dependencies.project(projectId)
+ if (!record) throw new GitHubHostError('project-not-found')
+ const board = record.project.kanban
+ if (!board?.github) throw new GitHubHostError('invalid-configuration')
+ const config = normaliseProjectKanbanGitHub(board.github, board.columns)
+ if (!config.ok) throw new GitHubHostError('invalid-configuration')
+ const detected = parseGitHubRepository(await this.dependencies.detectRepository(record.project)) ?? undefined
+ const repository = config.value.repository ?? detected
+ if (!repository) throw new GitHubHostError('repository-not-found')
+ return {
+ ...record,
+ repository,
+ ...(detected ? { detectedRepository: detected } : {}),
+ config: config.value
+ }
+ }
+}
diff --git a/src/core/github/integration.test.ts b/src/core/github/integration.test.ts
new file mode 100644
index 000000000..2740b1993
--- /dev/null
+++ b/src/core/github/integration.test.ts
@@ -0,0 +1,120 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import type { Project } from '../../shared/types'
+import type { CorePlatform } from '../platform'
+import { registerGitHubIntegration } from './integration'
+import type { CommandRunner, GitHubSecretStore } from './credentials'
+
+let userDataDir: string
+
+const project: Project = {
+ id: 'project-1',
+ name: 'Test',
+ color: '#8b5cf6',
+ cwd: '/repo',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [],
+ kanban: {
+ columns: [
+ { id: 'todo', title: 'Todo', color: '#2563eb' },
+ { id: 'done', title: 'Done', color: '#16a34a' }
+ ],
+ assignments: [],
+ github: {
+ repository: 'owner/repo',
+ columnMappings: [
+ { columnId: 'todo', label: 'status:todo' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done'
+ }
+ }
+}
+
+/** Only the four members registerGitHubIntegration touches. */
+function fakePlatform(): CorePlatform {
+ const noop = (): void => undefined
+ return {
+ handle: noop,
+ on: noop,
+ handleWithSender: noop,
+ onWithSender: noop,
+ sendTo: noop
+ } as unknown as CorePlatform
+}
+
+let realFetch: typeof globalThis.fetch
+let userRequests = 0
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-integration-'))
+ // registerGitHubIntegration builds its own token validator against api.github.com. Stub the
+ // transport rather than adding a production seam that exists only for this test.
+ realFetch = globalThis.fetch
+ userRequests = 0
+ globalThis.fetch = (async () => {
+ userRequests += 1
+ return new Response(JSON.stringify({ id: 1, login: 'octocat' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' }
+ })
+ }) as typeof globalThis.fetch
+})
+
+afterEach(async () => {
+ globalThis.fetch = realFetch
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+describe('registerGitHubIntegration', () => {
+ it('drops the memoised credential when the token changes, without waiting for its TTL', async () => {
+ // The resolver memoises so the service's epoch re-checks stop spawning `gh` and spending a
+ // /user request each. That memo must not outlive an in-app credential change: saving a token
+ // and immediately reading a context has to see the NEW credential, not the cached old one.
+ // Provider 'token' keeps the credential on the stored-token path, so clearing the token is a
+ // real boundary move rather than something the gh path would paper over.
+ const run: CommandRunner = async () => ({ ok: false, stdout: '', stderr: 'not logged in' })
+ let stored: string | null = 'stored-token'
+ const secret: GitHubSecretStore = {
+ availability: 'encrypted',
+ readForHost: async () => stored,
+ save: async (value) => { stored = value },
+ clear: async () => { stored = null }
+ }
+
+ const { controller } = registerGitHubIntegration({
+ platform: fakePlatform(),
+ userDataDir,
+ project: async (id) => id === project.id
+ ? { project, localApprovalId: 'local-1' }
+ : null,
+ detectRepository: async () => 'owner/repo',
+ secret,
+ run
+ })
+
+ const status = await controller.status('project-1')
+ await controller.approve({
+ projectId: 'project-1',
+ repository: 'owner/repo',
+ expectedRevision: status.control.revision
+ })
+
+ // Count the /user validations, since those are the requests the memo exists to stop — they
+ // bypass the request coordinator entirely and so are never rate-limited or backed off.
+ const before = userRequests
+ await controller.contextForProject('project-1')
+ expect(userRequests).toBe(before + 1)
+
+ // Inside the TTL a second context reuses the memo, spending nothing.
+ await controller.contextForProject('project-1')
+ expect(userRequests).toBe(before + 1)
+
+ // Clearing the saved token moves the credential boundary. Serving the stale memo here would
+ // keep a revoked credential alive for the rest of the window.
+ await controller.clearToken()
+ await expect(controller.contextForProject('project-1')).rejects.toThrow('not-authenticated')
+ })
+})
diff --git a/src/core/github/integration.ts b/src/core/github/integration.ts
new file mode 100644
index 000000000..237187c9e
--- /dev/null
+++ b/src/core/github/integration.ts
@@ -0,0 +1,70 @@
+import type { Project } from '../../shared/types'
+import type { CorePlatform } from '../platform'
+import type { GitHubSecretStore, CommandRunner } from './credentials'
+import { GitHubCredentialResolver } from './credentials'
+import { GitHubControlStore } from './control-store'
+import { GitHubIssuesClient } from './client'
+import { GitHubIssueCache } from './cache'
+import { GitHubRequestCoordinator } from './request-coordinator'
+import { GitHubAvatarFetcher } from './avatar-fetcher'
+import { GitHubHostController } from './host'
+import { GitHubIssueService } from './service'
+import { registerGitHubIssueHandlers } from './handlers'
+import { IPC } from '../../shared/ipc'
+
+type Dependencies = {
+ platform: CorePlatform
+ userDataDir: string
+ project(projectId: string): Promise<{ project: Project; localApprovalId: string } | null>
+ detectRepository(project: Project): Promise<string | null>
+ secret: GitHubSecretStore
+ run: CommandRunner
+}
+
+export function registerGitHubIntegration(dependencies: Dependencies): {
+ controller: GitHubHostController
+ service: GitHubIssueService
+} {
+ const validateToken = async (token: string) => {
+ try {
+ return await new GitHubIssuesClient({ token }).getAuthenticatedUser()
+ } catch {
+ return null
+ }
+ }
+ const controls = new GitHubControlStore(dependencies.userDataDir)
+ const coordinator = new GitHubRequestCoordinator()
+ const resolver = new GitHubCredentialResolver({
+ run: dependencies.run,
+ secret: dependencies.secret,
+ validate: validateToken
+ })
+ const controller = new GitHubHostController({
+ project: dependencies.project,
+ detectRepository: dependencies.detectRepository,
+ controls,
+ resolver,
+ secret: dependencies.secret,
+ validateToken,
+ client: (token) => new GitHubIssuesClient({ token }),
+ // Both halves of a credential boundary move: stop work that captured the old credential, and
+ // drop the resolver's memo so the next resolve reflects the change immediately instead of
+ // serving a revoked credential until its TTL happens to lapse.
+ onCredentialBoundaryChange: () => {
+ coordinator.cancelAll()
+ resolver.invalidate()
+ }
+ })
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(dependencies.userDataDir),
+ coordinator,
+ contextForProject: (projectId) => controller.contextForProject(projectId),
+ projectContextForCache: (projectId) => controller.projectContextForCache(projectId),
+ projectContextForCacheDeletion: (projectId) => controller.projectContextForCacheDeletion(projectId),
+ avatarFetcher: new GitHubAvatarFetcher(),
+ onDelta: (uiId, projectId, changedIssueNumbers) =>
+ dependencies.platform.sendTo(uiId, IPC.githubIssuesChanged(projectId), changedIssueNumbers)
+ })
+ registerGitHubIssueHandlers(dependencies.platform, service)
+ return { controller, service }
+}
diff --git a/src/core/github/request-coordinator.test.ts b/src/core/github/request-coordinator.test.ts
new file mode 100644
index 000000000..297c3c140
--- /dev/null
+++ b/src/core/github/request-coordinator.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+import { GitHubRequestCoordinator } from './request-coordinator'
+
+describe('GitHubRequestCoordinator', () => {
+ it('allows at most four reads for one identity across repositories', async () => {
+ const coordinator = new GitHubRequestCoordinator()
+ let active = 0
+ let maximum = 0
+ const releases: Array<() => void> = []
+ const operation = () => coordinator.runRead('user-1', () => new Promise<number>((resolve) => {
+ active += 1
+ maximum = Math.max(maximum, active)
+ releases.push(() => { active -= 1; resolve(active) })
+ }))
+ const results = [operation(), operation(), operation(), operation(), operation(), operation()]
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(active).toBe(4)
+ while (releases.length) {
+ releases.shift()!()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ }
+ await Promise.all(results)
+ expect(maximum).toBe(4)
+ })
+
+ it('applies a rate limit from one repository to every repository for the identity', () => {
+ const coordinator = new GitHubRequestCoordinator({ now: () => 1_000 })
+ coordinator.noteRateLimit('user-1', { kind: 'secondary', retryAt: 5_000 })
+ expect(coordinator.canStart('user-1', 4_999)).toBe(false)
+ expect(coordinator.canStart('user-1', 5_000)).toBe(true)
+ expect(coordinator.canStart('user-2', 1_000)).toBe(true)
+ })
+
+ it('learns an identity-wide backoff directly from a failed GitHub operation', async () => {
+ const coordinator = new GitHubRequestCoordinator({ now: () => 1_000 })
+ await expect(coordinator.runRead('user-1', async () => {
+ throw Object.assign(new Error('rate-limited'), { code: 'rate-limited', retryAt: 5_000 })
+ })).rejects.toMatchObject({ code: 'rate-limited' })
+ expect(coordinator.canStart('user-1', 4_999)).toBe(false)
+ })
+
+ it('rechecks an identity deadline that is extended while a request is sleeping', async () => {
+ let now = 1_000
+ const sleeps: number[] = []
+ const coordinator = new GitHubRequestCoordinator({
+ now: () => now,
+ sleep: async (milliseconds) => {
+ sleeps.push(milliseconds)
+ now += milliseconds
+ if (sleeps.length === 1) {
+ coordinator.noteRateLimit('user-1', { kind: 'secondary', retryAt: 8_000 })
+ }
+ }
+ })
+ coordinator.noteRateLimit('user-1', { kind: 'secondary', retryAt: 5_000 })
+
+ await coordinator.runRead('user-1', async () => 'ok')
+
+ expect(sleeps).toEqual([4_000, 3_000])
+ expect(now).toBe(8_000)
+ })
+
+ it('serialises mutations and spaces their start times by one second', async () => {
+ let now = 0
+ const sleeps: number[] = []
+ const coordinator = new GitHubRequestCoordinator({
+ now: () => now,
+ sleep: async (ms) => { sleeps.push(ms); now += ms }
+ })
+ const starts: number[] = []
+ await Promise.all([
+ coordinator.runMutation('user-1', async () => { starts.push(now); return 1 }),
+ coordinator.runMutation('user-1', async () => { starts.push(now); return 2 }),
+ coordinator.runMutation('user-1', async () => { starts.push(now); return 3 })
+ ])
+ expect(starts).toEqual([0, 1_000, 2_000])
+ expect(sleeps).toEqual([1_000, 1_000])
+ })
+
+ it('cancels queued work when an identity changes', async () => {
+ const coordinator = new GitHubRequestCoordinator()
+ let release: () => void = () => undefined
+ const first = coordinator.runMutation('user-1', () => new Promise<void>((resolve) => { release = resolve }))
+ const queued = coordinator.runMutation('user-1', async () => 'must-not-run')
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ coordinator.cancelIdentity('user-1')
+ release()
+ await first
+ await expect(queued).rejects.toMatchObject({ code: 'configuration-changed' })
+ })
+
+ it('cancels queued work for every known identity at an authentication boundary', async () => {
+ const coordinator = new GitHubRequestCoordinator()
+ let releaseA: () => void = () => undefined
+ let releaseB: () => void = () => undefined
+ const activeA = coordinator.runMutation('user-a', () =>
+ new Promise<void>((resolve) => { releaseA = resolve }))
+ const activeB = coordinator.runMutation('user-b', () =>
+ new Promise<void>((resolve) => { releaseB = resolve }))
+ const queuedA = coordinator.runMutation('user-a', async () => 'must-not-run')
+ const queuedB = coordinator.runMutation('user-b', async () => 'must-not-run')
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ coordinator.cancelAll()
+ releaseA()
+ releaseB()
+ await Promise.all([activeA, activeB])
+ await expect(queuedA).rejects.toMatchObject({ code: 'configuration-changed' })
+ await expect(queuedB).rejects.toMatchObject({ code: 'configuration-changed' })
+ })
+})
diff --git a/src/core/github/request-coordinator.ts b/src/core/github/request-coordinator.ts
new file mode 100644
index 000000000..ee2d03e5b
--- /dev/null
+++ b/src/core/github/request-coordinator.ts
@@ -0,0 +1,147 @@
+export class GitHubCoordinatorError extends Error {
+ constructor(readonly code: 'configuration-changed') {
+ super(code)
+ }
+}
+
+type RateLimit = { kind: 'primary' | 'secondary'; retryAt: number }
+type ReadJob = {
+ generation: number
+ run: () => Promise<unknown>
+ resolve: (value: unknown) => void
+ reject: (error: unknown) => void
+}
+type IdentityState = {
+ activeReads: number
+ readQueue: ReadJob[]
+ mutationTail: Promise<void>
+ lastMutationAt: number
+ generation: number
+ retryAt: number
+}
+
+type CoordinatorOptions = {
+ now?: () => number
+ sleep?: (milliseconds: number) => Promise<void>
+}
+
+function noteOperationRateLimit(state: IdentityState, error: unknown): void {
+ if (!error || typeof error !== 'object') return
+ const value = error as { code?: unknown; retryAt?: unknown }
+ if (value.code === 'rate-limited' && typeof value.retryAt === 'number' &&
+ Number.isFinite(value.retryAt)) {
+ state.retryAt = Math.max(state.retryAt, value.retryAt)
+ }
+}
+
+export class GitHubRequestCoordinator {
+ private readonly states = new Map<string, IdentityState>()
+ private readonly now: () => number
+ private readonly sleep: (milliseconds: number) => Promise<void>
+
+ constructor(options: CoordinatorOptions = {}) {
+ this.now = options.now ?? Date.now
+ this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)))
+ }
+
+ runRead<T>(identity: string, operation: () => Promise<T>): Promise<T> {
+ const state = this.state(identity)
+ return new Promise<T>((resolve, reject) => {
+ state.readQueue.push({
+ generation: state.generation,
+ run: operation,
+ resolve: resolve as (value: unknown) => void,
+ reject
+ })
+ this.drainReads(identity, state)
+ })
+ }
+
+ runMutation<T>(identity: string, operation: () => Promise<T>): Promise<T> {
+ const state = this.state(identity)
+ const generation = state.generation
+ let resolveResult: (value: T) => void
+ let rejectResult: (error: unknown) => void
+ const result = new Promise<T>((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
+ state.mutationTail = state.mutationTail.then(async () => {
+ try {
+ if (generation !== state.generation) throw new GitHubCoordinatorError('configuration-changed')
+ await this.waitForRate(state)
+ const spacing = state.lastMutationAt + 1_000 - this.now()
+ if (spacing > 0) await this.sleep(spacing)
+ if (generation !== state.generation) throw new GitHubCoordinatorError('configuration-changed')
+ state.lastMutationAt = this.now()
+ resolveResult(await operation())
+ } catch (error) {
+ noteOperationRateLimit(state, error)
+ rejectResult(error)
+ }
+ })
+ return result
+ }
+
+ noteRateLimit(identity: string, limit: RateLimit): void {
+ const state = this.state(identity)
+ if (Number.isFinite(limit.retryAt)) state.retryAt = Math.max(state.retryAt, limit.retryAt)
+ }
+
+ canStart(identity: string, at = this.now()): boolean {
+ return at >= this.state(identity).retryAt
+ }
+
+ cancelIdentity(identity: string): void {
+ const state = this.state(identity)
+ state.generation += 1
+ const error = new GitHubCoordinatorError('configuration-changed')
+ for (const job of state.readQueue.splice(0)) job.reject(error)
+ }
+
+ cancelAll(): void {
+ for (const identity of this.states.keys()) this.cancelIdentity(identity)
+ }
+
+ private state(identity: string): IdentityState {
+ let state = this.states.get(identity)
+ if (!state) {
+ state = {
+ activeReads: 0,
+ readQueue: [],
+ mutationTail: Promise.resolve(),
+ lastMutationAt: Number.NEGATIVE_INFINITY,
+ generation: 0,
+ retryAt: 0
+ }
+ this.states.set(identity, state)
+ }
+ return state
+ }
+
+ private drainReads(identity: string, state: IdentityState): void {
+ while (state.activeReads < 4 && state.readQueue.length) {
+ const job = state.readQueue.shift()!
+ state.activeReads += 1
+ void (async () => {
+ try {
+ if (job.generation !== state.generation) throw new GitHubCoordinatorError('configuration-changed')
+ await this.waitForRate(state)
+ if (job.generation !== state.generation) throw new GitHubCoordinatorError('configuration-changed')
+ job.resolve(await job.run())
+ } catch (error) {
+ noteOperationRateLimit(state, error)
+ job.reject(error)
+ } finally {
+ state.activeReads -= 1
+ this.drainReads(identity, state)
+ }
+ })()
+ }
+ }
+
+ private async waitForRate(state: IdentityState): Promise<void> {
+ while (true) {
+ const wait = state.retryAt - this.now()
+ if (wait <= 0) return
+ await this.sleep(wait)
+ }
+ }
+}
diff --git a/src/core/github/service.test.ts b/src/core/github/service.test.ts
new file mode 100644
index 000000000..0b5c2e35e
--- /dev/null
+++ b/src/core/github/service.test.ts
@@ -0,0 +1,844 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { GitHubIssueCache } from './cache'
+import {
+ FULL_REFRESH_MIN_INTERVAL_MS,
+ GitHubIssueService,
+ REFRESH_MIN_INTERVAL_MS,
+ type GitHubIssueServiceContext,
+ type GitHubIssuesClientLike
+} from './service'
+import { GitHubRequestCoordinator } from './request-coordinator'
+import type {
+ GitHubIssue,
+ IssuePageResult,
+ ListIssueOptions,
+ NormalisedProjectKanbanGitHub
+} from '../../shared/github-issues'
+
+let userDataDir: string
+
+const config: NormalisedProjectKanbanGitHub = {
+ repository: 'o/r',
+ columnMappings: [
+ { columnId: 'todo', label: 'status:todo' },
+ { columnId: 'doing', label: 'status:doing' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done',
+ revision: 'mapping-1'
+}
+
+const issue = (number: number, over: Partial<GitHubIssue> = {}): GitHubIssue => ({
+ id: 1_000 + number,
+ number,
+ title: `Issue ${number}`,
+ body: '',
+ state: 'open',
+ stateReason: null,
+ htmlUrl: `https://github.com/o/r/issues/${number}`,
+ apiUrl: `https://api.github.com/repos/o/r/issues/${number}`,
+ labels: [],
+ assignees: [],
+ createdAt: '2026-08-01T10:00:00Z',
+ updatedAt: `2026-08-09T10:00:${String(number).padStart(2, '0')}Z`,
+ locked: false,
+ ...over
+})
+
+class FixtureClient implements GitHubIssuesClientLike {
+ issues = new Map<number, GitHubIssue>()
+ updates: Array<{ number: number; input: { state?: 'open' | 'closed'; labels?: string[] } }> = []
+ repositoryLabels: Array<{ id: number; name: string; color: string; description: null }> = []
+ createdLabels: Array<{ name: string; color: string }> = []
+
+ constructor(issues: GitHubIssue[]) {
+ for (const item of issues) this.issues.set(item.number, item)
+ }
+
+ async listIssues(_repository: string, _options: ListIssueOptions): Promise<IssuePageResult> {
+ return { items: [...this.issues.values()] }
+ }
+
+ async getIssue(_repository: string, number: number) {
+ return structuredClone(this.issues.get(number)!)
+ }
+
+ async updateIssue(
+ _repository: string,
+ number: number,
+ input: { state?: 'open' | 'closed'; labels?: string[] }
+ ) {
+ this.updates.push({ number, input: structuredClone(input) })
+ const current = this.issues.get(number)!
+ const updated = {
+ ...current,
+ ...(input.state ? { state: input.state } : {}),
+ ...(input.labels ? {
+ labels: input.labels.map((name, index) => ({ id: index + 1, name, color: '8b5cf6' }))
+ } : {}),
+ updatedAt: '2026-08-09T11:00:00Z'
+ }
+ this.issues.set(number, updated)
+ return structuredClone(updated)
+ }
+
+ async listRepositoryLabels() { return { items: structuredClone(this.repositoryLabels) } }
+ async createLabel(_repository: string, input: { name: string; color: string }) {
+ this.createdLabels.push(structuredClone(input))
+ const label = { id: 99 + this.createdLabels.length, name: input.name, color: input.color, description: null }
+ this.repositoryLabels.push(label)
+ return label
+ }
+}
+
+function context(client: FixtureClient, over: Partial<GitHubIssueServiceContext> = {}): GitHubIssueServiceContext {
+ return {
+ localApprovalId: 'local-1',
+ projectId: 'project-1',
+ repository: 'o/r',
+ config,
+ controlRevision: 1,
+ credentialGeneration: 1,
+ userId: 'user-1',
+ client,
+ columnColors: { todo: '#0a84ff', doing: '#ffd60a', done: '#30d158' },
+ ...over
+ }
+}
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-service-'))
+})
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+describe('GitHubIssueService', () => {
+ it('renders a cached snapshot immediately and refreshes it in the background', async () => {
+ const client = new FixtureClient([issue(2)])
+ let release!: () => void
+ let started!: () => void
+ const refreshStarted = new Promise<void>((resolve) => { started = resolve })
+ client.listIssues = async () => {
+ started()
+ await new Promise<void>((resolve) => { release = resolve })
+ return { items: [issue(2)] }
+ }
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [issue(1)], etags: {}, lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ let refreshed!: () => void
+ const refreshFinished = new Promise<void>((resolve) => { refreshed = resolve })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ onDelta: () => refreshed()
+ })
+
+ const initial = await service.subscribe(1, { projectId: 'project-1' })
+ expect(initial.items.map((item) => item.number)).toEqual([1])
+ await refreshStarted
+ release()
+ await refreshFinished
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([2])
+ })
+
+ it('does not repopulate private data when cache is cleared during a refresh', async () => {
+ const client = new FixtureClient([issue(2)])
+ let release!: () => void
+ let started!: () => void
+ const refreshStarted = new Promise<void>((resolve) => { started = resolve })
+ client.listIssues = async () => {
+ started()
+ await new Promise<void>((resolve) => { release = resolve })
+ return { items: [issue(2)] }
+ }
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [issue(1)], etags: {}, lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ projectContextForCacheDeletion: async () => context(client)
+ })
+
+ const refreshing = service.refresh({ projectId: 'project-1', full: true })
+ await refreshStarted
+ const clearing = service.clearCache({ projectId: 'project-1' })
+ release()
+ await Promise.all([refreshing, clearing])
+
+ expect(await cache.boundUserId('local-1', 'project-1', 'o/r')).toBeNull()
+ expect(await cache.load('user-1', 'o/r')).toEqual({ version: 1 })
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items)
+ .toEqual([])
+ })
+
+ it('blocks a mutation whose repository state would be created after cache deletion begins', async () => {
+ const shown = issue(42)
+ const client = new FixtureClient([shown])
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [shown], etags: {}, lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ let releaseContext!: () => void
+ let contextStarted!: () => void
+ const started = new Promise<void>((resolve) => { contextStarted = resolve })
+ let contextCalls = 0
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => {
+ contextCalls += 1
+ if (contextCalls === 1) {
+ contextStarted()
+ await new Promise<void>((resolve) => { releaseContext = resolve })
+ }
+ return context(client)
+ },
+ projectContextForCacheDeletion: async () => context(client)
+ })
+
+ const moving = service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: shown.updatedAt
+ })
+ await started
+ const clearing = service.clearCache({ projectId: 'project-1' })
+ releaseContext()
+ const [moveResult] = await Promise.all([moving, clearing])
+
+ expect(moveResult.status).toBe('read-only')
+ expect(client.updates).toEqual([])
+ expect(await cache.load('user-1', 'o/r')).toEqual({ version: 1 })
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items)
+ .toEqual([])
+ })
+
+ it('purges subscribed in-memory issue bodies and emits an empty cache-change delta', async () => {
+ const client = new FixtureClient([issue(1, { body: 'private issue body' })])
+ const deltas: number[][] = []
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ projectContextForCacheDeletion: async () => context(client),
+ onDelta: (_uiId, _projectId, numbers) => deltas.push(numbers)
+ })
+ await service.subscribe(1, { projectId: 'project-1' })
+ deltas.length = 0
+
+ await service.clearCache({ projectId: 'project-1' })
+
+ expect(deltas).toEqual([[]])
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items)
+ .toEqual([])
+ })
+
+ it('waits for a cache writer from another project sharing the repository', async () => {
+ class PausingCache extends GitHubIssueCache {
+ pause = false
+ private releaseWrite!: () => void
+ private writeStarted!: () => void
+ readonly started = new Promise<void>((resolve) => { this.writeStarted = resolve })
+
+ release(): void { this.releaseWrite() }
+
+ override async saveComplete(
+ userId: string,
+ repository: string,
+ snapshot: Parameters<GitHubIssueCache['saveComplete']>[2]
+ ): Promise<void> {
+ if (this.pause) {
+ this.writeStarted()
+ await new Promise<void>((resolve) => { this.releaseWrite = resolve })
+ }
+ await super.saveComplete(userId, repository, snapshot)
+ }
+ }
+ const shown = issue(42)
+ const client = new FixtureClient([shown])
+ const cache = new PausingCache(userDataDir)
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async (projectId) => context(client, { projectId }),
+ projectContextForCacheDeletion: async (projectId) => context(client, { projectId })
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+ await service.refresh({ projectId: 'project-2', full: true })
+ cache.pause = true
+
+ const moving = service.moveIssue({
+ projectId: 'project-2', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: shown.updatedAt
+ })
+ await cache.started
+ let clearFinished = false
+ const clearing = service.clearCache({ projectId: 'project-1' })
+ .then(() => { clearFinished = true })
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(clearFinished).toBe(false)
+
+ cache.release()
+ await Promise.all([moving, clearing])
+
+ expect(await cache.load('user-1', 'o/r')).toEqual({ version: 1 })
+ })
+
+ it('rebuilds every page unconditionally during a full reconciliation', async () => {
+ const client = new FixtureClient([])
+ const calls: Array<{ page: number; etag?: string }> = []
+ client.listIssues = async (_repository: string, options: { page: number; etag?: string }) => {
+ calls.push({ page: options.page, ...(options.etag ? { etag: options.etag } : {}) })
+ return options.page === 1
+ ? { items: [issue(1)], nextPage: 2, etag: 'page-one' }
+ : { items: [issue(2)], etag: 'page-two' }
+ }
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [issue(99)], etags: { old: 'etag' },
+ lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ now: () => 10_000
+ })
+
+ await service.refresh({ projectId: 'project-1', full: true })
+
+ expect(calls).toEqual([{ page: 1 }, { page: 2 }])
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([2, 1])
+ })
+
+ it('advances the incremental watermark to refresh start, not completion', async () => {
+ const client = new FixtureClient([issue(1)])
+ const times = [1_000, 9_000, 12_000]
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [], etags: {}, lastSuccessfulRefreshAt: 500, lastFullReconciliationAt: 999
+ })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ now: () => times.shift() ?? 12_000
+ })
+ await service.refresh({ projectId: 'project-1' })
+ const saved = await cache.load('user-1', 'o/r')
+ expect(saved.lastComplete?.lastSuccessfulRefreshAt).toBe(1_000)
+ })
+
+ it('refreshes and maps open, closed, unmatched, and conflicting issues', async () => {
+ const client = new FixtureClient([
+ issue(1, { labels: [{ id: 1, name: 'status:todo', color: '0a84ff' }] }),
+ issue(2),
+ issue(3, { labels: [
+ { id: 1, name: 'status:todo', color: '0a84ff' },
+ { id: 2, name: 'status:doing', color: 'ffd60a' }
+ ] }),
+ issue(4, { state: 'closed', labels: [] })
+ ])
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ now: () => 10_000
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+
+ expect((await service.query({ projectId: 'project-1', columnId: 'todo', pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([1])
+ const ungrouped = await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })
+ expect(ungrouped.items.map((item) => [item.number, item.conflict])).toEqual([
+ [3, 'multiple-mapped-labels'],
+ [2, null]
+ ])
+ expect((await service.query({ projectId: 'project-1', columnId: 'done', pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([4])
+ })
+
+ it('reads and clears an approved private cache while signed out', async () => {
+ const client = new FixtureClient([issue(1)])
+ const cache = new GitHubIssueCache(userDataDir)
+ const online = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+ await online.refresh({ projectId: 'project-1', full: true })
+
+ const offline = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => { throw new Error('not-authenticated') },
+ projectContextForCache: async () => {
+ const { credentialGeneration: _generation, userId: _userId, client: _client, ...base } = context(client)
+ return base
+ }
+ })
+ expect((await offline.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([1])
+ await offline.clearCache({ projectId: 'project-1' })
+ expect(await cache.boundUserId('local-1', 'project-1', 'o/r')).toBeNull()
+ expect(await cache.load('user-1', 'o/r')).toEqual({ version: 1 })
+ })
+
+ it('uses one poll timer for every visible subscriber to the same repository', async () => {
+ const client = new FixtureClient([])
+ const timers: Array<() => Promise<void>> = []
+ const cleared: unknown[] = []
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ setInterval: (fn) => { timers.push(fn as () => Promise<void>); return timers.length },
+ clearInterval: (id) => { cleared.push(id) }
+ })
+ await service.subscribe(1, { projectId: 'project-1' })
+ await service.subscribe(2, { projectId: 'project-1' })
+ expect(timers).toHaveLength(1)
+ service.unsubscribe(1, 'project-1')
+ expect(cleared).toEqual([])
+ service.unsubscribe(2, 'project-1')
+ expect(cleared).toEqual([1])
+ })
+
+ it('polls through an invalid shared project to a valid project for the repository', async () => {
+ const client = new FixtureClient([issue(1)])
+ const timers: Array<() => Promise<void>> = []
+ let firstProjectValid = true
+ const deltas: Array<[string, number[]]> = []
+ const polledProjects: string[] = []
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async (projectId) => {
+ if (!firstProjectValid) polledProjects.push(projectId)
+ if (projectId === 'project-1' && !firstProjectValid) throw new Error('approval-revoked')
+ return context(client, { projectId })
+ },
+ setInterval: (fn) => { timers.push(fn as () => Promise<void>); return timers.length },
+ onDelta: (_uiId, projectId, numbers) => { deltas.push([projectId, numbers]) }
+ })
+ await service.subscribe(1, { projectId: 'project-1' })
+ await service.subscribe(2, { projectId: 'project-2' })
+ firstProjectValid = false
+ client.issues.set(2, issue(2))
+
+ await timers[0]()
+
+ expect(polledProjects[0]).toBe('project-1')
+ expect(polledProjects).toContain('project-2')
+ expect(deltas).toContainEqual(['project-2', [2]])
+ expect((await service.query({ projectId: 'project-2', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([2, 1])
+ })
+
+ it('migrates subscribers and timer ownership when the authenticated identity changes', async () => {
+ const firstClient = new FixtureClient([issue(1)])
+ const secondClient = new FixtureClient([issue(2)])
+ const timers: Array<() => Promise<void>> = []
+ const cleared: unknown[] = []
+ let identity = 'user-1'
+ let refreshed!: () => void
+ const refreshSeen = new Promise<void>((resolve) => { refreshed = resolve })
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(
+ identity === 'user-1' ? firstClient : secondClient,
+ { userId: identity, credentialGeneration: identity === 'user-1' ? 1 : 2 }
+ ),
+ setInterval: (fn) => { timers.push(fn as () => Promise<void>); return timers.length },
+ clearInterval: (timer) => { cleared.push(timer) },
+ onDelta: (_uiId, _projectId, numbers) => {
+ if (numbers.includes(2)) refreshed()
+ }
+ })
+ await service.subscribe(7, { projectId: 'project-1' })
+ identity = 'user-2'
+
+ await timers[0]()
+ await refreshSeen
+
+ expect(cleared).toEqual([1])
+ expect(timers).toHaveLength(2)
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).items
+ .map((item) => item.number)).toEqual([2])
+ service.unsubscribe(7, 'project-1')
+ expect(cleared).toEqual([1, 2])
+ })
+
+ it('drops all subscriptions for a disconnected client and sends deltas only to subscribers', async () => {
+ const client = new FixtureClient([issue(1)])
+ const deltas: Array<[number, string, number[]]> = []
+ const timers: Array<() => void> = []
+ const cleared: unknown[] = []
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async (projectId) => context(client, { projectId }),
+ setInterval: (fn) => { timers.push(fn); return timers.length },
+ clearInterval: (id) => { cleared.push(id) },
+ onDelta: (uiId, projectId, numbers) => deltas.push([uiId, projectId, numbers])
+ })
+ await service.subscribe(7, { projectId: 'project-1' })
+ await service.subscribe(8, { projectId: 'project-2' })
+ client.issues.set(2, issue(2))
+ await service.refresh({ projectId: 'project-1', full: true })
+ expect(deltas.slice(-2)).toEqual([
+ [7, 'project-1', [2]],
+ [8, 'project-2', [2]]
+ ])
+
+ service.dropClient(7)
+ service.dropClient(8)
+ expect(cleared).toEqual([1])
+ })
+
+ it('notifies subscribers when a full refresh only removes issues', async () => {
+ const client = new FixtureClient([issue(1), issue(2)])
+ const deltas: number[][] = []
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ onDelta: (_uiId, _projectId, numbers) => deltas.push(numbers)
+ })
+ await service.subscribe(1, { projectId: 'project-1' })
+ deltas.length = 0
+ client.issues.delete(2)
+
+ await service.refresh({ projectId: 'project-1', full: true })
+
+ expect(deltas).toEqual([[2]])
+ })
+
+ it('notifies subscribers when a refresh changes completeness without issue changes', async () => {
+ const client = new FixtureClient([])
+ client.listIssues = async () => ({
+ items: Array.from({ length: 10_001 }, (_, index) => issue(index + 1))
+ })
+ const deltas: number[][] = []
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ onDelta: (_uiId, _projectId, numbers) => deltas.push(numbers)
+ })
+ await service.subscribe(1, { projectId: 'project-1' })
+
+ expect(deltas).toEqual([[]])
+ expect((await service.query({ projectId: 'project-1', columnId: null, pageSize: 50 })).readOnly)
+ .toBe(true)
+ })
+
+ it('calculates counts from the active search and GitHub label filter', async () => {
+ const client = new FixtureClient([
+ issue(1, { title: 'Alpha bug', labels: [{ id: 1, name: 'bug', color: 'd73a4a' }] }),
+ issue(2, { title: 'Beta task', labels: [{ id: 2, name: 'feature', color: '0a84ff' }] })
+ ])
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir), coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+ const page = await service.query({
+ projectId: 'project-1', columnId: null, pageSize: 50,
+ search: 'alpha', labelFilter: ['github:bug']
+ })
+ expect(page.items.map((item) => item.number)).toEqual([1])
+ expect(page.counts).toEqual({ ungrouped: 1 })
+ })
+
+ it('closes in completion, reopens outside it, and preserves unrelated labels', async () => {
+ const shown = issue(42, {
+ state: 'closed',
+ labels: [
+ { id: 1, name: 'status:done', color: '30d158' },
+ { id: 2, name: 'bug', color: 'd73a4a' }
+ ]
+ })
+ const client = new FixtureClient([shown])
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator({ sleep: async () => undefined }),
+ contextForProject: async () => context(client)
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+ const result = await service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'todo', expectedUpdatedAt: shown.updatedAt
+ })
+ expect(result.status).toBe('confirmed')
+ expect(client.updates).toEqual([{ number: 42, input: {
+ state: 'open', labels: ['bug', 'status:todo']
+ } }])
+ })
+
+ it('returns stale data without writing when the displayed version changed', async () => {
+ const client = new FixtureClient([issue(42, { updatedAt: '2026-08-09T11:00:00Z' })])
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+ const result = await service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: '2026-08-09T10:00:00Z'
+ })
+ expect(result).toMatchObject({ status: 'stale', issue: { updatedAt: '2026-08-09T11:00:00Z' } })
+ expect(client.updates).toEqual([])
+ })
+
+ it('rejects mutation when the repository is incomplete or the issue is outside the complete snapshot', async () => {
+ const client = new FixtureClient([issue(42)])
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.saveIncompleteAttempt('user-1', 'o/r', {
+ reason: 'issue-limit', observedAt: 1, partialIssues: [issue(42)]
+ })
+ const service = new GitHubIssueService({
+ cache, coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+ expect(await service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: issue(42).updatedAt
+ })).toEqual({ status: 'read-only' })
+ expect(client.updates).toEqual([])
+ })
+
+ it('verifies GitHub confirmed the requested state and labels', async () => {
+ const client = new FixtureClient([issue(42)])
+ client.updateIssue = async (_repository, number) => structuredClone(client.issues.get(number)!)
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir), coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+ await expect(service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: issue(42).updatedAt
+ })).rejects.toThrow('mutation-not-confirmed')
+ })
+
+ it('cancels before the write when the approval epoch changes in the queue', async () => {
+ const client = new FixtureClient([issue(42)])
+ let moving = false
+ let moveReads = 0
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => {
+ if (moving) moveReads += 1
+ return context(client, { controlRevision: moving && moveReads >= 3 ? 2 : 1 })
+ }
+ })
+ await service.refresh({ projectId: 'project-1', full: true })
+ moving = true
+ const result = await service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: issue(42).updatedAt
+ })
+ expect(result.status).toBe('configuration-changed')
+ expect(client.updates).toEqual([])
+ })
+
+ it('creates only missing mapped labels with column colours', async () => {
+ const client = new FixtureClient([])
+ client.repositoryLabels = [{ id: 1, name: 'STATUS:TODO', color: 'ffffff', description: null }]
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator({ sleep: async () => undefined }),
+ contextForProject: async () => context(client)
+ })
+ const result = await service.createMissingLabels({ projectId: 'project-1' })
+ expect(result).toEqual({
+ status: 'confirmed',
+ created: ['status:doing', 'status:done'],
+ remaining: []
+ })
+ expect(client.createdLabels).toEqual([
+ { name: 'status:doing', color: 'ffd60a' },
+ { name: 'status:done', color: '30d158' }
+ ])
+ })
+
+ it('treats an exact concurrently created label as success and reports exact ownership', async () => {
+ const client = new FixtureClient([])
+ const original = client.createLabel.bind(client)
+ let raced = false
+ client.createLabel = async (repository, input) => {
+ if (!raced) {
+ raced = true
+ client.repositoryLabels.push({ id: 500, name: input.name.toUpperCase(),
+ color: input.color, description: null })
+ throw Object.assign(new Error('already exists'), { status: 422 })
+ }
+ return original(repository, input)
+ }
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator({ sleep: async () => undefined }),
+ contextForProject: async () => context(client)
+ })
+ expect(await service.createMissingLabels({ projectId: 'project-1' })).toEqual({
+ status: 'confirmed',
+ created: ['status:doing', 'status:done'],
+ remaining: []
+ })
+ })
+
+ it('returns refresh-pending after one confirmed write when cache persistence fails', async () => {
+ class FailingCache extends GitHubIssueCache {
+ override async saveComplete(): Promise<void> { throw new Error('disk full') }
+ }
+ const shown = issue(42)
+ const client = new FixtureClient([shown])
+ const cache = new FailingCache(userDataDir)
+ await GitHubIssueCache.prototype.saveComplete.call(cache, 'user-1', 'o/r', {
+ issues: [shown], etags: {}, lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+ const result = await service.moveIssue({
+ projectId: 'project-1', issueNumber: 42, toColumnId: 'doing',
+ expectedUpdatedAt: shown.updatedAt
+ })
+ expect(result.status).toBe('refresh-pending')
+ expect(client.updates).toHaveLength(1)
+ })
+
+ it('omits state from a move that does not change it, so GitHub keeps state_reason', async () => {
+ // A closed-as-not_planned issue maps into the completion column, so a drag that lands it back
+ // where it already is would PATCH state:'closed' again. GitHub rewrites state_reason to
+ // 'completed' for that write, silently destroying the "wontfix" record nobody asked to change.
+ const shelved = issue(5, {
+ state: 'closed',
+ stateReason: 'not_planned',
+ labels: [{ id: 1, name: 'status:doing', color: 'ffd60a' }]
+ })
+ const client = new FixtureClient([shelved])
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [shelved], etags: {}, lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+
+ const result = await service.moveIssue({
+ projectId: 'project-1', issueNumber: 5, toColumnId: 'done',
+ expectedUpdatedAt: shelved.updatedAt
+ })
+
+ expect(result.status).toBe('confirmed')
+ expect(client.updates).toHaveLength(1)
+ expect(client.updates[0].input.state).toBeUndefined()
+ expect(client.updates[0].input.labels).toEqual(['status:done'])
+ })
+
+ it('still sends state when the move really does change it', async () => {
+ const open = issue(6, { labels: [{ id: 1, name: 'status:doing', color: 'ffd60a' }] })
+ const client = new FixtureClient([open])
+ const cache = new GitHubIssueCache(userDataDir)
+ await cache.bind('local-1', 'project-1', 'o/r', 'user-1')
+ await cache.saveComplete('user-1', 'o/r', {
+ issues: [open], etags: {}, lastSuccessfulRefreshAt: 1, lastFullReconciliationAt: 1
+ })
+ const service = new GitHubIssueService({
+ cache,
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client)
+ })
+
+ const result = await service.moveIssue({
+ projectId: 'project-1', issueNumber: 6, toColumnId: 'done',
+ expectedUpdatedAt: open.updatedAt
+ })
+
+ expect(result.status).toBe('confirmed')
+ expect(client.updates[0].input.state).toBe('closed')
+ })
+
+ it('skips a repeat refresh inside the minimum interval', async () => {
+ const client = new FixtureClient([issue(1)])
+ let listed = 0
+ client.listIssues = async () => {
+ listed += 1
+ return { items: [issue(1)] }
+ }
+ let clock = 1_000_000
+ let resolutions = 0
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => {
+ resolutions += 1
+ return context(client)
+ },
+ now: () => clock
+ })
+
+ await service.refresh({ projectId: 'project-1' })
+ expect(listed).toBe(1)
+ const afterFirst = resolutions
+
+ clock += 1_000
+ await service.refresh({ projectId: 'project-1' })
+ expect(listed).toBe(1)
+ // The throttle must run BEFORE the credential resolution, or the expensive half still happens.
+ expect(resolutions).toBe(afterFirst)
+
+ clock += REFRESH_MIN_INTERVAL_MS
+ await service.refresh({ projectId: 'project-1' })
+ expect(listed).toBe(2)
+ })
+
+ it('lets a full refresh through its own longer interval, not the incremental one', async () => {
+ const client = new FixtureClient([issue(1)])
+ const fullPages: Array<string | undefined> = []
+ client.listIssues = async (_repository, options: ListIssueOptions) => {
+ fullPages.push(options.since)
+ return { items: [issue(1)] }
+ }
+ let clock = 1_000_000
+ const service = new GitHubIssueService({
+ cache: new GitHubIssueCache(userDataDir),
+ coordinator: new GitHubRequestCoordinator(),
+ contextForProject: async () => context(client),
+ now: () => clock
+ })
+
+ await service.refresh({ projectId: 'project-1', full: true })
+ expect(fullPages).toHaveLength(1)
+
+ clock += REFRESH_MIN_INTERVAL_MS
+ await service.refresh({ projectId: 'project-1', full: true })
+ expect(fullPages).toHaveLength(1)
+
+ clock += FULL_REFRESH_MIN_INTERVAL_MS
+ await service.refresh({ projectId: 'project-1', full: true })
+ expect(fullPages).toHaveLength(2)
+ })
+})
diff --git a/src/core/github/service.ts b/src/core/github/service.ts
new file mode 100644
index 000000000..3edd06456
--- /dev/null
+++ b/src/core/github/service.ts
@@ -0,0 +1,925 @@
+import type {
+ CreateMappedLabelsResult,
+ GitHubIssue,
+ GitHubIssueCardView,
+ GitHubIssuePage,
+ GitHubIssueQuery,
+ GitHubMutationResult,
+ GitHubRepositoryLabel,
+ IssuePageResult,
+ LabelPageResult,
+ ListIssueOptions,
+ NormalisedProjectKanbanGitHub,
+ UpdateIssueInput
+} from '../../shared/github-issues'
+import type { GitHubAvatarFetcher } from './avatar-fetcher'
+import {
+ GitHubCacheError,
+ type GitHubCompleteSnapshot,
+ type GitHubIssueCache
+} from './cache'
+import type { GitHubRequestCoordinator } from './request-coordinator'
+
+const MAX_ISSUES = 10_000
+const MAX_CACHE_BYTES = 64 * 1024 * 1024
+const FULL_REFRESH_AGE = 24 * 60 * 60_000
+const POLL_MS = 60_000
+
+/** Floor between two caller-driven refreshes of one project, and the longer floor for a FULL
+ * reconciliation. `refresh` is reachable from the renderer AND — for a shared project — from a
+ * relay guest, and nothing else bounds it: `state.refresh` coalesces CONCURRENT calls but not
+ * sequential ones, so an unthrottled caller can restart a whole-repository scan as fast as the
+ * previous one completes and spend the host's entire hourly quota (which is the ACCOUNT's quota —
+ * it degrades the user's `gh` CLI and github.com session too, not just nodeterm). Both floors sit
+ * under POLL_MS so the background poll is never the thing they throttle. */
+export const REFRESH_MIN_INTERVAL_MS = 30_000
+export const FULL_REFRESH_MIN_INTERVAL_MS = 120_000
+
+export interface GitHubIssuesClientLike {
+ listIssues(repository: string, options: ListIssueOptions): Promise<IssuePageResult>
+ getIssue(repository: string, issueNumber: number): Promise<GitHubIssue>
+ updateIssue(repository: string, issueNumber: number, input: UpdateIssueInput): Promise<GitHubIssue>
+ listRepositoryLabels(
+ repository: string,
+ options: { page: number; perPage: number; etag?: string }
+ ): Promise<LabelPageResult>
+ createLabel(
+ repository: string,
+ input: { name: string; color: string; description?: string }
+ ): Promise<GitHubRepositoryLabel>
+}
+
+export interface GitHubIssueProjectContext {
+ localApprovalId: string
+ projectId: string
+ repository: string
+ config: NormalisedProjectKanbanGitHub
+ controlRevision: number
+ columnColors: Record<string, string>
+}
+
+export interface GitHubIssueServiceContext extends GitHubIssueProjectContext {
+ credentialGeneration: number
+ userId: string
+ client: GitHubIssuesClientLike
+}
+
+type TimerId = ReturnType<typeof setInterval> | number
+type ServiceOptions = {
+ cache: GitHubIssueCache
+ coordinator: GitHubRequestCoordinator
+ contextForProject(projectId: string): Promise<GitHubIssueServiceContext>
+ projectContextForCache?(projectId: string): Promise<GitHubIssueProjectContext>
+ projectContextForCacheDeletion?(projectId: string): Promise<GitHubIssueProjectContext>
+ avatarFetcher?: GitHubAvatarFetcher
+ now?: () => number
+ setInterval?: (fn: () => void, milliseconds: number) => TimerId
+ clearInterval?: (timer: TimerId) => void
+ onDelta?: (uiId: number, projectId: string, changedIssueNumbers: number[]) => void
+}
+
+type RepositoryState = {
+ snapshot?: GitHubCompleteSnapshot
+ partialIssues?: GitHubIssue[]
+ incomplete: boolean
+ subscribers: Map<string, Set<number>>
+ timer?: TimerId
+ refresh?: Promise<void>
+ cacheGeneration: number
+}
+
+type RepositoryControl = {
+ generation: number
+ clearCutoff: number
+ deletion?: Promise<void>
+}
+
+function repositoryKey(context: GitHubIssueServiceContext): string {
+ return `${context.userId}\0${context.repository}`
+}
+
+function epoch(context: GitHubIssueServiceContext): string {
+ return JSON.stringify([
+ context.localApprovalId,
+ context.projectId,
+ context.repository,
+ context.config.revision,
+ context.controlRevision,
+ context.credentialGeneration,
+ context.userId
+ ])
+}
+
+function foldLabel(value: string): string {
+ return value.normalize('NFKC').toLocaleLowerCase('en-US')
+}
+
+function mapping(issue: GitHubIssue, config: NormalisedProjectKanbanGitHub): {
+ columnId: string | null
+ conflict: GitHubIssueCardView['conflict']
+} {
+ if (issue.state === 'closed') {
+ return { columnId: config.completionColumnId ?? null, conflict: null }
+ }
+ const labelNames = new Set(issue.labels.map((label) => foldLabel(label.name)))
+ const matches = config.columnMappings.filter((item) =>
+ labelNames.has(foldLabel(item.label)))
+ if (matches.length > 1) return { columnId: null, conflict: 'multiple-mapped-labels' }
+ if (matches.length === 1 && matches[0].columnId === config.completionColumnId) {
+ return { columnId: null, conflict: 'open-with-completion-label' }
+ }
+ return { columnId: matches[0]?.columnId ?? null, conflict: null }
+}
+
+function mutationChain<T>(
+ chains: Map<string, Promise<void>>,
+ key: string,
+ operation: () => Promise<T>
+): Promise<T> {
+ const previous = chains.get(key) ?? Promise.resolve()
+ let resolveResult: (value: T) => void
+ let rejectResult: (error: unknown) => void
+ const result = new Promise<T>((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
+ const next = previous.then(async () => {
+ try { resolveResult(await operation()) } catch (error) { rejectResult(error) }
+ })
+ chains.set(key, next)
+ void next.finally(() => { if (chains.get(key) === next) chains.delete(key) })
+ return result
+}
+
+export class GitHubIssueService {
+ private readonly repositories = new Map<string, RepositoryState>()
+ private readonly projectKeys = new Map<string, string>()
+ private readonly issueChains = new Map<string, Promise<void>>()
+ private readonly repositoryControls = new Map<string, RepositoryControl>()
+ private readonly statePreparations = new Map<string, Set<Promise<RepositoryState>>>()
+ private readonly refreshFloors = new Map<string, { any: number; full: number }>()
+ private operationSequence = 0
+ private readonly now: () => number
+ private readonly schedule: NonNullable<ServiceOptions['setInterval']>
+ private readonly unschedule: NonNullable<ServiceOptions['clearInterval']>
+
+ constructor(private readonly options: ServiceOptions) {
+ this.now = options.now ?? Date.now
+ this.schedule = options.setInterval ?? ((fn, milliseconds) => setInterval(fn, milliseconds))
+ this.unschedule = options.clearInterval ?? ((timer) => clearInterval(timer as ReturnType<typeof setInterval>))
+ }
+
+ async subscribe(uiId: number, request: { projectId: string }): Promise<GitHubIssuePage> {
+ const context = await this.cacheContext(request.projectId)
+ const { key, state } = await this.cachedState(context)
+ const firstSubscriber = this.subscriberCount(state) === 0
+ let subscribers = state.subscribers.get(request.projectId)
+ if (!subscribers) {
+ subscribers = new Set()
+ state.subscribers.set(request.projectId, subscribers)
+ }
+ subscribers.add(uiId)
+ this.projectKeys.set(request.projectId, key)
+ if (firstSubscriber) {
+ if (!state.snapshot && !state.partialIssues) {
+ try { await this.refresh({ projectId: request.projectId }) } catch { /* offline cache remains readable */ }
+ } else {
+ void this.refresh({ projectId: request.projectId }).catch(() => undefined)
+ }
+ }
+ const activeKey = this.projectKeys.get(request.projectId)
+ this.ensureTimer(activeKey ? this.repositories.get(activeKey) ?? state : state)
+ return this.query({ projectId: request.projectId, columnId: null, pageSize: 50 })
+ }
+
+ unsubscribe(uiId: number, projectId: string): void {
+ const key = this.projectKeys.get(projectId)
+ const state = key ? this.repositories.get(key) : undefined
+ if (!state) return
+ const subscribers = state.subscribers.get(projectId)
+ subscribers?.delete(uiId)
+ if (subscribers?.size === 0) state.subscribers.delete(projectId)
+ if (this.subscriberCount(state) === 0 && state.timer) {
+ this.unschedule(state.timer)
+ delete state.timer
+ }
+ }
+
+ dropClient(uiId: number): void {
+ for (const state of this.repositories.values()) {
+ for (const [projectId, subscribers] of state.subscribers) {
+ subscribers.delete(uiId)
+ if (subscribers.size === 0) state.subscribers.delete(projectId)
+ }
+ if (this.subscriberCount(state) === 0 && state.timer) {
+ this.unschedule(state.timer)
+ delete state.timer
+ }
+ }
+ }
+
+ async refresh(request: { projectId: string; full?: boolean }): Promise<void> {
+ // The floor is checked BEFORE contextForProject on purpose: resolving a context runs the whole
+ // credential chain (gh subprocesses + a /user round trip), so a throttle placed after it would
+ // still pay the expensive half of every call it rejects.
+ const full = request.full === true
+ const startedAt = this.now()
+ const previousFloor = this.refreshFloors.get(request.projectId)
+ if (previousFloor && startedAt < (full ? previousFloor.full : previousFloor.any)) return
+ this.refreshFloors.set(request.projectId, {
+ any: startedAt + REFRESH_MIN_INTERVAL_MS,
+ // An incremental pass does not satisfy a full reconciliation, so it never moves that floor.
+ full: full ? startedAt + FULL_REFRESH_MIN_INTERVAL_MS : previousFloor?.full ?? 0
+ })
+ try {
+ // Reuse the clock read above as the refresh's own start stamp: one read per refresh keeps the
+ // incremental watermark anchored to when the work actually began.
+ return await this.refreshWithinFloor(request, startedAt)
+ } catch (error) {
+ // A refresh that FAILED bought nothing, so it must not hold the floor — otherwise the first
+ // network blip disables the board's own Retry button for the next 30 seconds.
+ if (this.refreshFloors.get(request.projectId)?.any === startedAt + REFRESH_MIN_INTERVAL_MS) {
+ if (previousFloor) this.refreshFloors.set(request.projectId, previousFloor)
+ else this.refreshFloors.delete(request.projectId)
+ }
+ throw error
+ }
+ }
+
+ private async refreshWithinFloor(
+ request: { projectId: string; full?: boolean },
+ startedAt = this.now()
+ ): Promise<void> {
+ const operationId = ++this.operationSequence
+ const captured = await this.options.contextForProject(request.projectId)
+ const control = this.repositoryControl(captured.repository)
+ if (control.deletion || operationId <= control.clearCutoff) return
+ const repositoryGeneration = control.generation
+ let state: RepositoryState
+ try {
+ state = await this.state(captured, operationId, repositoryGeneration)
+ } catch (error) {
+ if (error instanceof RepositoryClearedError) return
+ throw error
+ }
+ if (state.refresh) return state.refresh
+ const cacheGeneration = state.cacheGeneration
+ const work = this.refreshRepository(
+ captured, state, request.full === true, cacheGeneration, operationId, repositoryGeneration,
+ startedAt
+ )
+ state.refresh = work
+ try { await work } finally { if (state.refresh === work) delete state.refresh }
+ }
+
+ async query(request: GitHubIssueQuery): Promise<GitHubIssuePage> {
+ if (!Number.isSafeInteger(request.pageSize) || request.pageSize < 1 || request.pageSize > 50) {
+ throw new Error('invalid-query')
+ }
+ const context = await this.cacheContext(request.projectId)
+ const { state } = await this.cachedState(context)
+ const source = state.snapshot?.issues ?? state.partialIssues ?? []
+ const mapped = source.map((issue): GitHubIssueCardView => ({ ...issue, ...mapping(issue, context.config) }))
+ const search = request.search?.trim().toLocaleLowerCase('en-US') ?? ''
+ const filters = new Set((request.labelFilter ?? []).map((item) =>
+ foldLabel(item.replace(/^github:/, ''))))
+ const filtered = mapped.filter((item) => !search || item.title.toLocaleLowerCase('en-US').includes(search) ||
+ String(item.number).includes(search))
+ .filter((item) => filters.size === 0 || item.labels.some((label) =>
+ filters.has(foldLabel(label.name))))
+ const visible = filtered.filter((item) => item.columnId === request.columnId)
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || b.number - a.number)
+ const offset = request.cursor ? Number(request.cursor) : 0
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('invalid-query')
+ const page = visible.slice(offset, offset + request.pageSize)
+ if (this.options.avatarFetcher) {
+ const avatars = await this.options.avatarFetcher.forPage(page.flatMap((item) => item.assignees))
+ for (const item of page) {
+ const entries = item.assignees.flatMap((user) => {
+ const data = avatars.dataUrls.get(user.id)
+ return data ? [[String(user.id), data] as const] : []
+ })
+ if (entries.length) item.avatarDataUrls = Object.fromEntries(entries)
+ }
+ }
+ const counts: Record<string, number> = {}
+ for (const item of filtered) {
+ counts[item.columnId ?? 'ungrouped'] = (counts[item.columnId ?? 'ungrouped'] ?? 0) + 1
+ }
+ return {
+ items: page,
+ counts,
+ ...(offset + page.length < visible.length ? { nextCursor: String(offset + page.length) } : {}),
+ partial: !state.snapshot && !!state.partialIssues,
+ readOnly: state.incomplete || !state.snapshot || !context.config.completionColumnId,
+ ...(state.snapshot ? {
+ lastSuccessfulRefreshAt: state.snapshot.lastSuccessfulRefreshAt,
+ lastFullReconciliationAt: state.snapshot.lastFullReconciliationAt
+ } : {})
+ }
+ }
+
+ moveIssue(request: {
+ projectId: string
+ issueNumber: number
+ toColumnId: string | null
+ expectedUpdatedAt: string
+ }): Promise<GitHubMutationResult> {
+ const operationId = ++this.operationSequence
+ return mutationChain(this.issueChains, `${request.projectId}:${request.issueNumber}`, async () => {
+ const captured = await this.options.contextForProject(request.projectId)
+ const capturedEpoch = epoch(captured)
+ const repositoryGeneration = this.repositoryControl(captured.repository).generation
+ let state: RepositoryState
+ try {
+ state = await this.state(captured, operationId, repositoryGeneration)
+ } catch (error) {
+ if (error instanceof RepositoryClearedError) return { status: 'read-only' }
+ throw error
+ }
+ const cacheGeneration = state.cacheGeneration
+ if (state.incomplete || !state.snapshot || !captured.config.completionColumnId) {
+ return { status: 'read-only' }
+ }
+ if (!state.snapshot.issues.some((item) => item.number === request.issueNumber)) {
+ return { status: 'invalid-target' }
+ }
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ return { status: 'configuration-changed' }
+ }
+ const latest = await this.readWithEpoch(captured, () =>
+ captured.client.getIssue(captured.repository, request.issueNumber))
+ .catch((error: unknown) => error instanceof ConfigurationChangedError ? null : Promise.reject(error))
+ if (!latest) return { status: 'configuration-changed' }
+ if (latest.updatedAt !== request.expectedUpdatedAt) {
+ if (cacheGeneration !== state.cacheGeneration ||
+ !this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration)) {
+ return { status: 'stale', issue: latest }
+ }
+ state.snapshot = {
+ ...state.snapshot,
+ issues: state.snapshot.issues.map((item) => item.number === latest.number ? latest : item)
+ }
+ try {
+ await this.options.cache.saveComplete(captured.userId, captured.repository, state.snapshot)
+ } catch { /* the validated in-memory issue remains available for this process */ }
+ this.emitDelta(state, [latest.number])
+ return { status: 'stale', issue: latest }
+ }
+ const destination = request.toColumnId === null
+ ? null
+ : captured.config.columnMappings.find((item) => item.columnId === request.toColumnId)
+ if (request.toColumnId !== null && !destination) return { status: 'invalid-target' }
+ const mappedNames = new Set(captured.config.columnMappings.map((item) =>
+ foldLabel(item.label)))
+ const labels = latest.labels.map((label) => label.name)
+ .filter((name) => !mappedNames.has(foldLabel(name)))
+ if (destination) labels.push(destination.label)
+ const desiredState = request.toColumnId === captured.config.completionColumnId
+ ? 'closed'
+ : 'open'
+ const input: UpdateIssueInput = {
+ // Send `state` ONLY when it actually changes. GitHub rewrites `state_reason` for any write
+ // that carries `state`, so re-closing an already-closed issue turns a deliberate
+ // 'not_planned' (wontfix) into 'completed'. Closed issues all map into the completion
+ // column, so a drag that lands one back where it already sits is a no-op the user never
+ // meant as a state change — and it must not be one on GitHub either.
+ ...(latest.state === desiredState ? {} : { state: desiredState }),
+ labels
+ }
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ return { status: 'configuration-changed' }
+ }
+ const updated = await this.options.coordinator.runMutation(captured.userId, async () => {
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ throw new ConfigurationChangedError()
+ }
+ return captured.client.updateIssue(captured.repository, request.issueNumber, input)
+ }).catch((error: unknown) => {
+ if (error instanceof ConfigurationChangedError) return null
+ throw error
+ })
+ if (!updated) return { status: 'configuration-changed' }
+ const confirmedLabels = new Set(updated.labels.map((label) =>
+ label.name.normalize('NFKC').toLocaleLowerCase('en-US')))
+ const expectedLabels = new Set(labels.map((label) =>
+ label.normalize('NFKC').toLocaleLowerCase('en-US')))
+ if (updated.state !== desiredState || confirmedLabels.size !== expectedLabels.size ||
+ [...expectedLabels].some((label) => !confirmedLabels.has(label))) {
+ throw new Error('mutation-not-confirmed')
+ }
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ return { status: 'confirmed', issue: updated }
+ }
+ if (cacheGeneration !== state.cacheGeneration) {
+ return { status: 'refresh-pending', issue: updated }
+ }
+ if (!this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration)) {
+ return { status: 'refresh-pending', issue: updated }
+ }
+ const snapshot = state.snapshot ?? {
+ issues: [], etags: {}, lastSuccessfulRefreshAt: this.now(), lastFullReconciliationAt: 0
+ }
+ const issues = snapshot.issues.some((item) => item.number === updated.number)
+ ? snapshot.issues.map((item) => item.number === updated.number ? updated : item)
+ : [...snapshot.issues, updated]
+ state.snapshot = { ...snapshot, issues, lastSuccessfulRefreshAt: this.now() }
+ state.partialIssues = undefined
+ try {
+ await this.options.cache.saveComplete(captured.userId, captured.repository, state.snapshot)
+ } catch {
+ return { status: 'refresh-pending', issue: updated }
+ }
+ this.emitDelta(state, [updated.number])
+ return { status: 'confirmed', issue: updated }
+ })
+ }
+
+ async createMissingLabels(request: { projectId: string }): Promise<CreateMappedLabelsResult> {
+ const operationId = ++this.operationSequence
+ const captured = await this.options.contextForProject(request.projectId)
+ const capturedEpoch = epoch(captured)
+ const repositoryGeneration = this.repositoryControl(captured.repository).generation
+ let state: RepositoryState
+ try {
+ state = await this.state(captured, operationId, repositoryGeneration)
+ } catch (error) {
+ if (error instanceof RepositoryClearedError) {
+ return { status: 'read-only', created: [], remaining:
+ captured.config.columnMappings.map((item) => item.label) }
+ }
+ throw error
+ }
+ if (state.incomplete || !captured.config.completionColumnId) {
+ return {
+ status: 'read-only',
+ created: [],
+ remaining: captured.config.columnMappings.map((item) => item.label)
+ }
+ }
+ const known = new Set<string>()
+ let page = 1
+ while (true) {
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ return {
+ status: 'configuration-changed',
+ created: [],
+ remaining: captured.config.columnMappings.map((item) => item.label)
+ }
+ }
+ const result = await this.readWithEpoch(captured, () =>
+ captured.client.listRepositoryLabels(captured.repository, { page, perPage: 100 }))
+ .catch((error: unknown) => error instanceof ConfigurationChangedError ? null : Promise.reject(error))
+ if (!result) {
+ return { status: 'configuration-changed', created: [], remaining:
+ captured.config.columnMappings.map((item) => item.label) }
+ }
+ for (const label of result.items) known.add(label.name.normalize('NFKC').toLocaleLowerCase('en-US'))
+ if (!result.nextPage) break
+ page = result.nextPage
+ }
+ const pending = captured.config.columnMappings.filter((item) =>
+ !known.has(item.label.normalize('NFKC').toLocaleLowerCase('en-US')))
+ const created: string[] = []
+ for (let index = 0; index < pending.length; index++) {
+ const item = pending[index]
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ return {
+ status: 'configuration-changed',
+ created,
+ remaining: pending.filter((candidate) => !created.includes(candidate.label))
+ .map((candidate) => candidate.label)
+ }
+ }
+ const current = await this.repositoryLabelNames(captured).catch((error: unknown) =>
+ error instanceof ConfigurationChangedError ? null : Promise.reject(error))
+ if (!current) {
+ return {
+ status: 'configuration-changed', created,
+ remaining: pending.slice(index).map((candidate) => candidate.label)
+ }
+ }
+ const folded = item.label.normalize('NFKC').toLocaleLowerCase('en-US')
+ if (current.has(folded)) continue
+ const color = captured.columnColors[item.columnId]?.replace(/^#/, '')
+ const result = await this.options.coordinator.runMutation(captured.userId, async () => {
+ if (capturedEpoch !== epoch(await this.options.contextForProject(request.projectId))) {
+ throw new ConfigurationChangedError()
+ }
+ return captured.client.createLabel(captured.repository, {
+ name: item.label,
+ color: color && /^[0-9a-fA-F]{6}$/.test(color) ? color.toLowerCase() : '8b5cf6'
+ })
+ }).catch(async (error: unknown) => {
+ if (error instanceof ConfigurationChangedError) return null
+ const after = await this.repositoryLabelNames(captured).catch(() => null)
+ if (after?.has(folded)) return { concurrent: true } as const
+ return { failed: true } as const
+ })
+ if (!result) {
+ return {
+ status: 'configuration-changed',
+ created,
+ remaining: pending.filter((candidate) => !created.includes(candidate.label))
+ .map((candidate) => candidate.label)
+ }
+ }
+ if ('failed' in result) {
+ return {
+ status: 'partial', created,
+ remaining: pending.slice(index).map((candidate) => candidate.label)
+ }
+ }
+ if ('concurrent' in result) {
+ known.add(folded)
+ } else {
+ known.add(result.name.normalize('NFKC').toLocaleLowerCase('en-US'))
+ created.push(item.label)
+ }
+ }
+ return { status: 'confirmed', created, remaining: [] }
+ }
+
+ async clearCache(request: { projectId: string }): Promise<void> {
+ const clearOperationId = ++this.operationSequence
+ const context = this.options.projectContextForCacheDeletion
+ ? await this.options.projectContextForCacheDeletion(request.projectId)
+ : await this.cacheContext(request.projectId)
+ const control = this.repositoryControl(context.repository)
+ if (control.deletion) await control.deletion
+ let finishDeletion!: () => void
+ const deletion = new Promise<void>((resolve) => { finishDeletion = resolve })
+ control.clearCutoff = Math.max(control.clearCutoff, clearOperationId)
+ control.generation += 1
+ control.deletion = deletion
+ try {
+ const affected = this.repositoryStates(context.localApprovalId, context.repository)
+ for (const state of affected) state.cacheGeneration += 1
+ const mutations = [...this.issueChains.values()]
+ await Promise.allSettled([
+ ...this.statePreparations.get(context.repository) ?? [],
+ ...affected.flatMap((state) => state.refresh ? [state.refresh] : []),
+ ...mutations
+ ])
+ await this.options.cache.clearBound(context.localApprovalId, context.projectId, context.repository)
+ for (const state of this.repositoryStates(context.localApprovalId, context.repository)) {
+ state.cacheGeneration += 1
+ state.snapshot = undefined
+ state.partialIssues = undefined
+ state.incomplete = false
+ this.emitDelta(state, [], true)
+ }
+ } finally {
+ if (control.deletion === deletion) delete control.deletion
+ finishDeletion()
+ }
+ }
+
+ private state(
+ context: GitHubIssueServiceContext,
+ operationId: number,
+ repositoryGeneration: number
+ ): Promise<RepositoryState> {
+ const work = this.prepareState(context, operationId, repositoryGeneration)
+ let preparations = this.statePreparations.get(context.repository)
+ if (!preparations) {
+ preparations = new Set()
+ this.statePreparations.set(context.repository, preparations)
+ }
+ preparations.add(work)
+ void work.finally(() => {
+ preparations!.delete(work)
+ if (preparations!.size === 0) this.statePreparations.delete(context.repository)
+ }).catch(() => undefined)
+ return work
+ }
+
+ private async prepareState(
+ context: GitHubIssueServiceContext,
+ operationId: number,
+ repositoryGeneration: number
+ ): Promise<RepositoryState> {
+ this.assertRepositoryWriteAllowed(context.repository, operationId, repositoryGeneration)
+ await this.options.cache.bind(
+ context.localApprovalId, context.projectId, context.repository, context.userId
+ )
+ this.assertRepositoryWriteAllowed(context.repository, operationId, repositoryGeneration)
+ const key = repositoryKey(context)
+ const unboundKey = `unbound:${context.localApprovalId}\0${context.repository}`
+ const unbound = this.repositories.get(unboundKey)
+ let state = this.repositories.get(key)
+ if (!state) {
+ const cached = await this.options.cache.load(context.userId, context.repository)
+ this.assertRepositoryWriteAllowed(context.repository, operationId, repositoryGeneration)
+ state = {
+ snapshot: cached.lastComplete,
+ partialIssues: cached.lastAttempt?.partialIssues,
+ incomplete: !!cached.lastAttempt,
+ subscribers: new Map(),
+ cacheGeneration: 0
+ }
+ this.repositories.set(key, state)
+ }
+ if (unbound && unbound !== state) {
+ for (const [projectId, subscribers] of unbound.subscribers) {
+ let target = state.subscribers.get(projectId)
+ if (!target) {
+ target = new Set()
+ state.subscribers.set(projectId, target)
+ }
+ for (const uiId of subscribers) target.add(uiId)
+ }
+ if (unbound.timer) {
+ this.unschedule(unbound.timer)
+ delete unbound.timer
+ }
+ this.repositories.delete(unboundKey)
+ this.ensureTimer(state)
+ }
+ this.migrateProjectState(context.projectId, key, state)
+ this.projectKeys.set(context.projectId, key)
+ return state
+ }
+
+ private async cacheContext(projectId: string): Promise<GitHubIssueProjectContext> {
+ if (this.options.projectContextForCache) return this.options.projectContextForCache(projectId)
+ return this.options.contextForProject(projectId)
+ }
+
+ private async cachedState(context: GitHubIssueProjectContext): Promise<{
+ key: string
+ state: RepositoryState
+ }> {
+ await this.waitForRepositoryDeletion(context.repository)
+ const repositoryGeneration = this.repositoryControl(context.repository).generation
+ const userId = await this.options.cache.boundUserId(
+ context.localApprovalId, context.projectId, context.repository
+ )
+ if (!userId) {
+ if (repositoryGeneration !== this.repositoryControl(context.repository).generation) {
+ return this.cachedState(context)
+ }
+ const key = `unbound:${context.localApprovalId}\0${context.repository}`
+ let state = this.repositories.get(key)
+ if (!state) {
+ state = { incomplete: false, subscribers: new Map(), cacheGeneration: 0 }
+ this.repositories.set(key, state)
+ }
+ this.projectKeys.set(context.projectId, key)
+ if (repositoryGeneration !== this.repositoryControl(context.repository).generation) {
+ return this.cachedState(context)
+ }
+ return { key, state }
+ }
+ const key = `${userId}\0${context.repository}`
+ let state = this.repositories.get(key)
+ if (!state) {
+ const cached = await this.options.cache.load(userId, context.repository)
+ if (repositoryGeneration !== this.repositoryControl(context.repository).generation) {
+ return this.cachedState(context)
+ }
+ state = {
+ snapshot: cached.lastComplete,
+ partialIssues: cached.lastAttempt?.partialIssues,
+ incomplete: !!cached.lastAttempt,
+ subscribers: new Map(),
+ cacheGeneration: 0
+ }
+ this.repositories.set(key, state)
+ }
+ this.projectKeys.set(context.projectId, key)
+ if (repositoryGeneration !== this.repositoryControl(context.repository).generation) {
+ return this.cachedState(context)
+ }
+ return { key, state }
+ }
+
+ private async refreshRepository(
+ captured: GitHubIssueServiceContext,
+ state: RepositoryState,
+ forceFull: boolean,
+ cacheGeneration: number,
+ operationId: number,
+ repositoryGeneration: number,
+ refreshStartedAt: number
+ ): Promise<void> {
+ const full = forceFull || !state.snapshot ||
+ this.now() - state.snapshot.lastFullReconciliationAt >= FULL_REFRESH_AGE
+ const previous = state.snapshot
+ const byNumber = new Map((full ? [] : previous?.issues ?? []).map((issue) => [issue.number, issue]))
+ let page = 1
+ const etags: Record<string, string> = {}
+ while (true) {
+ if (!this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration) ||
+ cacheGeneration !== state.cacheGeneration ||
+ epoch(captured) !== epoch(await this.options.contextForProject(captured.projectId))) return
+ const since = !full && previous?.lastSuccessfulRefreshAt
+ ? new Date(Math.max(0, previous.lastSuccessfulRefreshAt - 2_000)).toISOString()
+ : undefined
+ const result = await this.readWithEpoch(captured, () =>
+ captured.client.listIssues(captured.repository, {
+ state: 'all', page, perPage: 100, ...(since ? { since } : {})
+ })).catch((error: unknown) =>
+ error instanceof ConfigurationChangedError ? null : Promise.reject(error))
+ if (!result) return
+ if (!result.notModified) {
+ for (const item of result.items) {
+ const old = byNumber.get(item.number)
+ if (!old || item.updatedAt >= old.updatedAt) byNumber.set(item.number, item)
+ }
+ }
+ if (byNumber.size > MAX_ISSUES) {
+ await this.incomplete(
+ captured, state, 'issue-limit', [...byNumber.values()].slice(0, MAX_ISSUES),
+ cacheGeneration, operationId, repositoryGeneration
+ )
+ return
+ }
+ if (!result.nextPage) break
+ page = result.nextPage
+ }
+ const issues = [...byNumber.values()]
+ if (Buffer.byteLength(JSON.stringify(issues), 'utf-8') > MAX_CACHE_BYTES) {
+ await this.incomplete(
+ captured, state, 'byte-limit', issues, cacheGeneration, operationId, repositoryGeneration
+ )
+ return
+ }
+ if (!this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration) ||
+ cacheGeneration !== state.cacheGeneration ||
+ epoch(captured) !== epoch(await this.options.contextForProject(captured.projectId))) return
+ const snapshot: GitHubCompleteSnapshot = {
+ issues,
+ etags,
+ lastSuccessfulRefreshAt: refreshStartedAt,
+ lastFullReconciliationAt: full
+ ? refreshStartedAt
+ : previous?.lastFullReconciliationAt ?? refreshStartedAt
+ }
+ if (!this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration)) return
+ await this.options.cache.saveComplete(captured.userId, captured.repository, snapshot)
+ if (!this.repositoryWriteAllowed(captured.repository, operationId, repositoryGeneration) ||
+ cacheGeneration !== state.cacheGeneration) return
+ const oldNumbers = new Map((previous?.issues ?? []).map((item) => [item.number, item.updatedAt]))
+ const nextNumbers = new Set(issues.map((item) => item.number))
+ const changed = [
+ ...issues.filter((item) => oldNumbers.get(item.number) !== item.updatedAt)
+ .map((item) => item.number),
+ ...(previous?.issues ?? []).filter((item) => !nextNumbers.has(item.number))
+ .map((item) => item.number)
+ ]
+ state.snapshot = snapshot
+ state.partialIssues = undefined
+ state.incomplete = false
+ this.emitDelta(state, changed, true)
+ }
+
+ private subscriberCount(state: RepositoryState): number {
+ let count = 0
+ for (const subscribers of state.subscribers.values()) count += subscribers.size
+ return count
+ }
+
+ private ensureTimer(state: RepositoryState): void {
+ if (state.timer || this.subscriberCount(state) === 0) return
+ state.timer = this.schedule(() => this.poll(state), POLL_MS)
+ }
+
+ private async poll(state: RepositoryState): Promise<void> {
+ for (const projectId of [...state.subscribers.keys()]) {
+ try {
+ // Deliberately BELOW the caller floor: the floor bounds callers we don't control (the
+ // renderer, and a relay guest on a shared project), while the poll is already paced by
+ // POLL_MS. Routing it through the floor would also break this loop's fallback — a
+ // throttled call returns without throwing, which reads here as "this project worked" and
+ // would stop us ever trying the next subscriber's context.
+ await this.refreshWithinFloor({ projectId })
+ return
+ } catch {
+ // Another approved project may still provide a valid context for the shared repository.
+ }
+ }
+ }
+
+ private migrateProjectState(projectId: string, key: string, target: RepositoryState): void {
+ const previousKey = this.projectKeys.get(projectId)
+ if (!previousKey || previousKey === key) return
+ const previous = this.repositories.get(previousKey)
+ const subscribers = previous?.subscribers.get(projectId)
+ if (!previous || !subscribers) return
+ let destination = target.subscribers.get(projectId)
+ if (!destination) {
+ destination = new Set()
+ target.subscribers.set(projectId, destination)
+ }
+ for (const uiId of subscribers) destination.add(uiId)
+ previous.subscribers.delete(projectId)
+ if (this.subscriberCount(previous) === 0 && previous.timer) {
+ this.unschedule(previous.timer)
+ delete previous.timer
+ }
+ this.ensureTimer(target)
+ }
+
+ private repositoryControl(repository: string): RepositoryControl {
+ let control = this.repositoryControls.get(repository)
+ if (!control) {
+ control = { generation: 0, clearCutoff: 0 }
+ this.repositoryControls.set(repository, control)
+ }
+ return control
+ }
+
+ private repositoryWriteAllowed(
+ repository: string,
+ operationId: number,
+ repositoryGeneration: number
+ ): boolean {
+ const control = this.repositoryControl(repository)
+ return !control.deletion && operationId > control.clearCutoff &&
+ repositoryGeneration === control.generation
+ }
+
+ private assertRepositoryWriteAllowed(
+ repository: string,
+ operationId: number,
+ repositoryGeneration: number
+ ): void {
+ if (!this.repositoryWriteAllowed(repository, operationId, repositoryGeneration)) {
+ throw new RepositoryClearedError()
+ }
+ }
+
+ private async waitForRepositoryDeletion(repository: string): Promise<void> {
+ while (this.repositoryControl(repository).deletion) {
+ await this.repositoryControl(repository).deletion
+ }
+ }
+
+ private repositoryStates(localApprovalId: string, repository: string): RepositoryState[] {
+ const states: RepositoryState[] = []
+ for (const [key, state] of this.repositories) {
+ if (key.endsWith(`\0${repository}`) || key === `unbound:${localApprovalId}\0${repository}`) {
+ states.push(state)
+ }
+ }
+ return states
+ }
+
+ private readWithEpoch<T>(captured: GitHubIssueServiceContext, operation: () => Promise<T>): Promise<T> {
+ return this.options.coordinator.runRead(captured.userId, async () => {
+ if (epoch(captured) !== epoch(await this.options.contextForProject(captured.projectId))) {
+ throw new ConfigurationChangedError()
+ }
+ return operation()
+ })
+ }
+
+ private async repositoryLabelNames(captured: GitHubIssueServiceContext): Promise<Set<string>> {
+ const names = new Set<string>()
+ let page = 1
+ while (true) {
+ const result = await this.readWithEpoch(captured, () =>
+ captured.client.listRepositoryLabels(captured.repository, { page, perPage: 100 }))
+ for (const label of result.items) {
+ names.add(label.name.normalize('NFKC').toLocaleLowerCase('en-US'))
+ }
+ if (!result.nextPage) return names
+ page = result.nextPage
+ }
+ }
+
+ private emitDelta(
+ state: RepositoryState,
+ changedIssueNumbers: number[],
+ includeEmpty = false
+ ): void {
+ if (!includeEmpty && changedIssueNumbers.length === 0) return
+ for (const [projectId, subscribers] of state.subscribers) {
+ for (const uiId of subscribers) this.options.onDelta?.(uiId, projectId, changedIssueNumbers)
+ }
+ }
+
+ private async incomplete(
+ context: GitHubIssueServiceContext,
+ state: RepositoryState,
+ reason: 'issue-limit' | 'byte-limit',
+ issues: GitHubIssue[],
+ cacheGeneration: number,
+ operationId: number,
+ repositoryGeneration: number
+ ): Promise<void> {
+ if (!this.repositoryWriteAllowed(context.repository, operationId, repositoryGeneration) ||
+ cacheGeneration !== state.cacheGeneration) return
+ await this.options.cache.saveIncompleteAttempt(context.userId, context.repository, {
+ reason,
+ observedAt: this.now(),
+ ...(!state.snapshot ? { partialIssues: issues } : {})
+ })
+ if (!this.repositoryWriteAllowed(context.repository, operationId, repositoryGeneration) ||
+ cacheGeneration !== state.cacheGeneration) return
+ if (!state.snapshot) state.partialIssues = issues
+ state.incomplete = true
+ this.emitDelta(state, [], true)
+ }
+}
+
+class ConfigurationChangedError extends Error {}
+class RepositoryClearedError extends Error {}
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index 795ad2973..e13008344 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -39,6 +39,8 @@ export interface ProjectFileV1 {
* ProjectFileV1 seen/written — used while the server is unreachable. */
export interface IndexEntryV3 {
id: string
+ /** Stable machine-local trust identity. Never copied into the shared project file. */
+ localApprovalId?: string
name: string
color: string
closed?: boolean
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 8323880c5..547d45b75 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -32,6 +32,26 @@ afterEach(async () => {
})
describe('save → load round trip (v3)', () => {
+ it('creates and preserves a machine-local approval id outside the shared project file', async () => {
+ const store = new WorkspaceStore()
+ const workspace = ws([project({ cwd: projRoot })])
+
+ await store.save(workspace)
+ const firstIndex = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ const approvalId = firstIndex.entries[0].localApprovalId
+ expect(approvalId).toMatch(/^[0-9a-f-]{36}$/)
+
+ await store.save(workspace)
+ const secondIndex = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(secondIndex.entries[0].localApprovalId).toBe(approvalId)
+ expect(await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8'))
+ .not.toContain('localApprovalId')
+ await expect(store.githubProject('p1')).resolves.toMatchObject({
+ project: { id: 'p1', cwd: projRoot },
+ localApprovalId: approvalId
+ })
+ })
+
it('writes <cwd>/.nodeterm/project.json + a v3 index, and loads it back assembled', async () => {
const store = new WorkspaceStore()
await store.save(ws([project({ cwd: projRoot }), project({ id: 'p2', name: 'inline' })]))
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index cdf86ec0e..67ee93079 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1,4 +1,5 @@
import { promises as fs } from 'fs'
+import { randomUUID } from 'node:crypto'
import path from 'path'
import { IPC } from '../shared/ipc'
import { platform } from './platform'
@@ -110,6 +111,7 @@ export class WorkspaceStore {
}
private async loadV3(index: WorkspaceIndexV3, sideline: boolean): Promise<Workspace> {
+ for (const entry of index.entries) entry.localApprovalId ||= randomUUID()
this.index = index
const projects: Project[] = []
for (const e of index.entries) {
@@ -215,6 +217,11 @@ export class WorkspaceStore {
const savedAt = new Date().toISOString()
const { index, files } = splitWorkspace(workspace, (id) => this.revs.get(id) ?? 0, savedAt)
+ for (const entry of index.entries) {
+ const previous = this.index?.entries.find((candidate) => candidate.id === entry.id)
+ entry.localApprovalId = previous?.localApprovalId || randomUUID()
+ }
+
// An unavailable placeholder carries no real data. splitWorkspace already dropped its file
// and cache; here we restore the machine-local payload (ssh offline cache) from the previous
// index so the index rewrite doesn't drop a good cache we still can't reach.
@@ -379,6 +386,18 @@ export class WorkspaceStore {
return this.index?.entries.find((e) => e.id === projectId && e.cwd)?.cwd
}
+ /** Resolve the shared project together with its machine-local trust identity. The approval id
+ * never enters the shared project object or project.json. */
+ async githubProject(projectId: string): Promise<{
+ project: Project
+ localApprovalId: string
+ } | null> {
+ const workspace = await this.load({ sideline: false })
+ const project = workspace.projects.find((candidate) => candidate.id === projectId)
+ const localApprovalId = this.index?.entries.find((entry) => entry.id === projectId)?.localApprovalId
+ return project && localApprovalId ? { project, localApprovalId } : null
+ }
+
/** The local ref cwds of the current index — the workspace half of the phone bridge's fs/git
* jail. The phone browses EVERY project over `projects.list`, so jailing to only the active
* canvas's node cwds denied any project the desktop didn't happen to have focused. */
diff --git a/src/main/github-control.test.ts b/src/main/github-control.test.ts
new file mode 100644
index 000000000..f171757ae
--- /dev/null
+++ b/src/main/github-control.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { promises as fs } from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { vi } from 'vitest'
+import { IPC } from '../shared/ipc'
+import {
+ ElectronGitHubSecretStore,
+ registerElectronGitHubControl,
+ type SafeStorageLike
+} from './github-control'
+
+let userDataDir: string
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-electron-github-secret-'))
+})
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+function safeStorage(options: { available?: boolean; backend?: string } = {}): SafeStorageLike {
+ return {
+ isEncryptionAvailable: () => options.available ?? true,
+ getSelectedStorageBackend: () => options.backend ?? 'keychain',
+ encryptString: (value) => Buffer.from(`encrypted:${value}`, 'utf-8'),
+ decryptString: (value) => value.toString('utf-8').replace(/^encrypted:/, '')
+ }
+}
+
+describe('ElectronGitHubSecretStore', () => {
+ it('encrypts a token and reads it only inside the host', async () => {
+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())
+ await store.save('github_pat_secret')
+
+ const raw = await fs.readFile(path.join(userDataDir, 'github-issues-token.json'), 'utf-8')
+ expect(raw).not.toContain('github_pat_secret')
+ expect(JSON.parse(raw)).toMatchObject({ version: 1, kind: 'safe-storage' })
+ expect(await store.readForHost()).toBe('github_pat_secret')
+ expect(store.availability).toBe('encrypted')
+ })
+
+ it('uses a restricted 0600 file for basic_text and reports the warning state', async () => {
+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage({ backend: 'basic_text' }))
+ await store.save('github_pat_secret')
+
+ expect(store.availability).toBe('restricted-file')
+ expect((await fs.stat(path.join(userDataDir, 'github-issues-token.json'))).mode & 0o777).toBe(0o600)
+ expect(await store.readForHost()).toBe('github_pat_secret')
+ })
+
+ it('does not overwrite an encrypted token while the keyring is locked', async () => {
+ const unlocked = new ElectronGitHubSecretStore(userDataDir, safeStorage())
+ await unlocked.save('original-token')
+ const before = await fs.readFile(path.join(userDataDir, 'github-issues-token.json'), 'utf-8')
+
+ const locked = new ElectronGitHubSecretStore(userDataDir, safeStorage({ available: false }))
+ await expect(locked.save('replacement-token')).rejects.toMatchObject({ code: 'keyring-locked' })
+ expect(await fs.readFile(path.join(userDataDir, 'github-issues-token.json'), 'utf-8')).toBe(before)
+ expect(await locked.readForHost()).toBeNull()
+ })
+
+ it('clears only the stored token file', async () => {
+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())
+ await store.save('github_pat_secret')
+ await store.clear()
+ expect(await store.readForHost()).toBeNull()
+ })
+})
+
+describe('registerElectronGitHubControl', () => {
+ it('accepts only the current local main window and wires every control action', async () => {
+ const handlers = new Map<string, (event: { sender: { id: number } }, ...args: any[]) => unknown>()
+ const view = {
+ control: { revision: 0, authProvider: 'auto' as const },
+ auth: {
+ selectedProvider: 'auto' as const,
+ activeProvider: null,
+ ghAuthenticated: false,
+ tokenPresent: false,
+ storage: 'encrypted' as const
+ }
+ }
+ const controller = {
+ status: vi.fn(async () => view),
+ approve: vi.fn(async () => view),
+ revoke: vi.fn(async () => view),
+ selectProvider: vi.fn(async () => view),
+ saveToken: vi.fn(async () => view),
+ clearToken: vi.fn(async () => view)
+ }
+ registerElectronGitHubControl(
+ { handle: (channel, handler) => handlers.set(channel, handler) },
+ () => 7,
+ controller
+ )
+ expect([...handlers.keys()].sort()).toEqual([
+ IPC.githubControlApprove,
+ IPC.githubControlClearToken,
+ IPC.githubControlRevoke,
+ IPC.githubControlSaveToken,
+ IPC.githubControlSelectProvider,
+ IPC.githubControlStatus
+ ].sort())
+ await expect(Promise.resolve().then(() =>
+ handlers.get(IPC.githubControlStatus)!({ sender: { id: 8 } }, 'p1')))
+ .rejects.toMatchObject({ code: 'E_FORBIDDEN' })
+ await expect(handlers.get(IPC.githubControlStatus)!({ sender: { id: 7 } }, 'p1'))
+ .resolves.toEqual(view)
+ expect(controller.status).toHaveBeenCalledWith('p1')
+ })
+})
diff --git a/src/main/github-control.ts b/src/main/github-control.ts
new file mode 100644
index 000000000..28e29e320
--- /dev/null
+++ b/src/main/github-control.ts
@@ -0,0 +1,146 @@
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import type { GitHubSecretStore } from '../core/github/credentials'
+import type { GitHubSecretAvailability } from '../shared/github-issues'
+import { IPC } from '../shared/ipc'
+import type { GitHubHostController } from '../core/github/host'
+
+const FILE_NAME = 'github-issues-token.json'
+
+export interface SafeStorageLike {
+ isEncryptionAvailable(): boolean
+ getSelectedStorageBackend?(): string
+ encryptString(value: string): Buffer
+ decryptString(value: Buffer): string
+}
+
+type TokenDocument =
+ | { version: 1; kind: 'safe-storage'; value: string }
+ | { version: 1; kind: 'restricted-file'; token: string }
+
+export class GitHubSecretError extends Error {
+ constructor(readonly code: 'invalid-token' | 'keyring-locked') {
+ super(code)
+ }
+}
+
+function validToken(token: string): boolean {
+ return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)
+}
+
+async function atomicWrite(file: string, document: TokenDocument): Promise<void> {
+ await fs.mkdir(path.dirname(file), { recursive: true })
+ const temporary = `${file}.tmp`
+ await fs.writeFile(temporary, JSON.stringify(document), { encoding: 'utf-8', mode: 0o600 })
+ await fs.chmod(temporary, 0o600)
+ await fs.rename(temporary, file)
+ await fs.chmod(file, 0o600)
+}
+
+export class ElectronGitHubSecretStore implements GitHubSecretStore {
+ constructor(
+ private readonly userDataDir: string,
+ private readonly safeStorage: SafeStorageLike
+ ) {}
+
+ get availability(): GitHubSecretAvailability {
+ return this.canEncrypt() ? 'encrypted' : 'restricted-file'
+ }
+
+ private get filePath(): string {
+ return path.join(this.userDataDir, FILE_NAME)
+ }
+
+ async save(token: string): Promise<void> {
+ if (!validToken(token)) throw new GitHubSecretError('invalid-token')
+ const current = await this.readDocument()
+ if (current?.kind === 'safe-storage' && !this.canEncrypt()) {
+ throw new GitHubSecretError('keyring-locked')
+ }
+ const document: TokenDocument = this.canEncrypt()
+ ? {
+ version: 1,
+ kind: 'safe-storage',
+ value: this.safeStorage.encryptString(token).toString('base64')
+ }
+ : { version: 1, kind: 'restricted-file', token }
+ await atomicWrite(this.filePath, document)
+ }
+
+ async clear(): Promise<void> {
+ await fs.rm(this.filePath, { force: true })
+ }
+
+ async readForHost(): Promise<string | null> {
+ const document = await this.readDocument()
+ if (!document) return null
+ if (document.kind === 'restricted-file') return validToken(document.token) ? document.token : null
+ if (!this.canEncrypt()) return null
+ try {
+ const token = this.safeStorage.decryptString(Buffer.from(document.value, 'base64'))
+ return validToken(token) ? token : null
+ } catch {
+ return null
+ }
+ }
+
+ private canEncrypt(): boolean {
+ if (!this.safeStorage.isEncryptionAvailable()) return false
+ try {
+ return this.safeStorage.getSelectedStorageBackend?.() !== 'basic_text'
+ } catch {
+ return false
+ }
+ }
+
+ private async readDocument(): Promise<TokenDocument | null> {
+ try {
+ const value: unknown = JSON.parse(await fs.readFile(this.filePath, 'utf-8'))
+ if (!value || typeof value !== 'object') return null
+ const document = value as Partial<TokenDocument>
+ if (document.version !== 1) return null
+ if (document.kind === 'safe-storage' && typeof document.value === 'string') {
+ return document as TokenDocument
+ }
+ if (document.kind === 'restricted-file' && typeof document.token === 'string') {
+ return document as TokenDocument
+ }
+ return null
+ } catch {
+ return null
+ }
+ }
+}
+
+export class GitHubControlAccessError extends Error {
+ readonly code = 'E_FORBIDDEN'
+
+ constructor() {
+ super('GitHub control is available only to the local main window')
+ }
+}
+
+type IpcMainLike = {
+ handle(channel: string, handler: (event: { sender: { id: number } }, ...args: any[]) => unknown): void
+}
+
+type Controller = Pick<GitHubHostController,
+ 'status' | 'approve' | 'revoke' | 'selectProvider' | 'saveToken' | 'clearToken'>
+
+export function registerElectronGitHubControl(
+ ipc: IpcMainLike,
+ mainWindowId: () => number | undefined,
+ controller: Controller
+): void {
+ const local = <T extends unknown[]>(action: (...args: T) => unknown) =>
+ (event: { sender: { id: number } }, ...args: T): unknown => {
+ if (mainWindowId() !== event.sender.id) throw new GitHubControlAccessError()
+ return action(...args)
+ }
+ ipc.handle(IPC.githubControlStatus, local((projectId?: string) => controller.status(projectId)))
+ ipc.handle(IPC.githubControlApprove, local((input) => controller.approve(input)))
+ ipc.handle(IPC.githubControlRevoke, local((input) => controller.revoke(input)))
+ ipc.handle(IPC.githubControlSelectProvider, local((input) => controller.selectProvider(input)))
+ ipc.handle(IPC.githubControlSaveToken, local((token: string) => controller.saveToken(token)))
+ ipc.handle(IPC.githubControlClearToken, local(() => controller.clearToken()))
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index ffda5c415..44422ef0c 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -5,7 +5,7 @@ import { canRename, type AgentId } from '@shared/agents/config'
import { readFile } from 'fs/promises'
import { homedir, hostname } from 'os'
import { randomUUID } from 'crypto'
-import { app, BrowserWindow, clipboard, dialog, ipcMain, Notification, powerMonitor, shell, systemPreferences } from 'electron'
+import { app, BrowserWindow, clipboard, dialog, ipcMain, Notification, powerMonitor, safeStorage, shell, systemPreferences } from 'electron'
import { IPC } from '../shared/ipc'
import { registerFsHandlers } from '../core/fs-handlers'
import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'
@@ -18,6 +18,9 @@ import { SettingsStore } from '../core/settings-store'
import { presenceHub } from '../core/presence/hub'
import { SshStore } from './ssh-store'
import { GitService } from '../core/git-service'
+import { registerGitHubIntegration } from '../core/github/integration'
+import { runGitHubCliCommand } from '../core/github/credentials'
+import { ElectronGitHubSecretStore, registerElectronGitHubControl } from './github-control'
import { generateCommitMessage, generateGroupName, generateTerminalName } from '../core/commit-message'
import { initUpdater } from './updater'
import { fetchCheck } from '../core/check'
@@ -205,10 +208,14 @@ const speechService = new SpeechService({ models: whisperModels, isPremium })
// viewer. Inert with zero peers: the registry holds no sink, so none of this ever runs.
// Wired once here — do not double-wire (4b Task 4). A second wirePeerRegistry() call would silently
// overwrite these deps (last write wins), so keep this the sole call site in src/main.
+let dropGitHubRelayClient: ((id: number) => void) | undefined
wirePeerRegistry({
setFlow: (id, sid, resume, owner) => ptyManager.setFlow(id, sid, resume, owner),
captureForResync: (sid) => ptyManager.captureForResync(sid),
- onPeerGone: (id) => ptyManager.dropClient(id)
+ onPeerGone: (id) => {
+ ptyManager.dropClient(id)
+ dropGitHubRelayClient?.(id)
+ }
})
// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters and
@@ -704,6 +711,23 @@ app.whenReady().then(async () => {
// behaviour cannot drift. Registered on the platform, so a remote tab's Explorer/editor works.
registerFsHandlers(corePlatform)
+ const githubSecret = new ElectronGitHubSecretStore(app.getPath('userData'), safeStorage)
+ const github = registerGitHubIntegration({
+ platform: corePlatform,
+ userDataDir: app.getPath('userData'),
+ project: (projectId) => workspaceStore.githubProject(projectId),
+ detectRepository: (project) =>
+ gitService.originUrl(project.ssh?.remoteCwd ?? project.cwd ?? ''),
+ secret: githubSecret,
+ run: runGitHubCliCommand
+ })
+ dropGitHubRelayClient = (id) => github.service.dropClient(id)
+ registerElectronGitHubControl(
+ ipcMain,
+ () => getMainWindow()?.webContents.id,
+ github.controller
+ )
+
// SSH-project Explorer/Editor fs: the remote analog of the fs:* handlers above, scoped to a
// project's ControlMaster. One SshFs bound to the SSH-project manager's own ssh runner (the SAME
// runner RemoteFile reuses — just forwarding stdin so writes work), resolved lazily because
diff --git a/src/main/platform-electron.test.ts b/src/main/platform-electron.test.ts
index 65ec1d360..a7d83f358 100644
--- a/src/main/platform-electron.test.ts
+++ b/src/main/platform-electron.test.ts
@@ -114,6 +114,17 @@ describe('electronPlatform', () => {
* registered, bit-identical to the webContents-only code they replaced.
*/
describe('electronPlatform + relay peers', () => {
+ it('denies every raw relay request to the GitHub host-control namespace', async () => {
+ const p = electronPlatform()
+ p.handle('githubControl:approve', () => 'must-not-run')
+ expect(await p.dispatch(PEER, {
+ t: 'req', id: 9, method: 'githubControl:approve', args: []
+ })).toEqual({
+ t: 'res', id: 9, ok: false,
+ error: { code: 'E_FORBIDDEN', message: 'host-control method is not available to relay peers' }
+ })
+ })
+
it('clientIds = webContents ids ++ peer ids', () => {
const p = electronPlatform()
h.clientIds = [5]
diff --git a/src/main/platform-electron.ts b/src/main/platform-electron.ts
index 222ab6ee5..b511cab97 100644
--- a/src/main/platform-electron.ts
+++ b/src/main/platform-electron.ts
@@ -87,6 +87,15 @@ export function electronPlatform(): ElectronPlatform {
ipcMain.on(ch, (e, ...args) => fn(e.sender.id, ...args))
},
async dispatch(clientId, req) {
+ if (req.method.startsWith('githubControl:')) {
+ return {
+ t: 'res', id: req.id, ok: false,
+ error: {
+ code: 'E_FORBIDDEN',
+ message: 'host-control method is not available to relay peers'
+ }
+ }
+ }
const h = handlers.get(req.method)
if (!h) {
return {
diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.ts
index 50c67d7c0..1fc0da104 100644
--- a/src/main/remote/relay-host.test.ts
+++ b/src/main/remote/relay-host.test.ts
@@ -408,6 +408,56 @@ describe('relay host — workspace:load is scoped to the shared project', () =>
})
})
+describe('relay host — GitHub issue RPCs are scoped to the shared project', () => {
+ it('rejects every cross-project request before a GitHub handler can run', async () => {
+ const reached: string[] = []
+ const methods: Array<[string, unknown[]]> = [
+ [IPC.githubIssuesSubscribe, [{ projectId: 'proj-2' }]],
+ [IPC.githubIssuesQuery, [{ projectId: 'proj-2', columnId: null, pageSize: 50 }]],
+ [IPC.githubIssuesRefresh, ['proj-2', true]],
+ [IPC.githubIssuesMove, [{ projectId: 'proj-2', issueNumber: 7, toColumnId: null,
+ expectedUpdatedAt: '2026-08-09T00:00:00Z' }]],
+ [IPC.githubIssuesCreateLabels, ['proj-2']],
+ [IPC.githubIssuesClearCache, ['proj-2']]
+ ]
+ for (const [method] of methods) platform.handle(method, async () => { reached.push(method) })
+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })
+ await s.openMutually()
+
+ for (let index = 0; index < methods.length; index++) {
+ const [method, args] = methods[index]
+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 100 + index, method, args }))
+ }
+
+ await vi.waitFor(() => expect(s.textFrames.filter((frame) => {
+ const message = JSON.parse(frame)
+ return message.t === 'res' && message.id >= 100
+ })).toHaveLength(methods.length))
+ const responses = s.textFrames.map((frame) => JSON.parse(frame))
+ .filter((message) => message.t === 'res' && message.id >= 100)
+ expect(responses.every((response) =>
+ response.ok === false && response.error.code === 'E_FORBIDDEN')).toBe(true)
+ expect(reached).toEqual([])
+ })
+
+ it('drops cross-project unsubscribe casts but permits the shared project', async () => {
+ const calls: Array<[number, string]> = []
+ platform.onWithSender(IPC.githubIssuesUnsubscribe, (uiId, projectId) => calls.push([uiId, projectId]))
+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })
+ await s.openMutually()
+ const uiId = s.session.clientId()!
+
+ s.peerSendsTunnelText(JSON.stringify({
+ t: 'cast', method: IPC.githubIssuesUnsubscribe, args: ['proj-2']
+ }))
+ s.peerSendsTunnelText(JSON.stringify({
+ t: 'cast', method: IPC.githubIssuesUnsubscribe, args: ['proj-1']
+ }))
+
+ await vi.waitFor(() => expect(calls).toEqual([[uiId, 'proj-1']]))
+ })
+})
+
describe('relay host — nothing is served before mutual approval', () => {
it('a peer RPC BEFORE mutual approval is refused (no dispatch, no sink, no presence)', async () => {
let created = 0
diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.ts
index 9c8b868b8..fde04c6e1 100644
--- a/src/main/remote/relay-host.ts
+++ b/src/main/remote/relay-host.ts
@@ -196,6 +196,42 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
? { t: 'res', id, ok: true, result: { entries: [], unsupported: true } }
: { t: 'res', id, ok: true, result: false }
+ const githubIssuesProject = (method: string, args: unknown[]): {
+ githubIssues: boolean
+ projectId: unknown
+ } => {
+ switch (method) {
+ case IPC.githubIssuesSubscribe:
+ case IPC.githubIssuesQuery:
+ case IPC.githubIssuesMove:
+ return {
+ githubIssues: true,
+ projectId: args[0] && typeof args[0] === 'object'
+ ? (args[0] as { projectId?: unknown }).projectId
+ : undefined
+ }
+ case IPC.githubIssuesRefresh:
+ case IPC.githubIssuesCreateLabels:
+ case IPC.githubIssuesClearCache:
+ case IPC.githubIssuesUnsubscribe:
+ return { githubIssues: true, projectId: args[0] }
+ default:
+ return { githubIssues: false, projectId: undefined }
+ }
+ }
+
+ const githubIssuesOutOfScope = (method: string, args: unknown[]): boolean => {
+ const target = githubIssuesProject(method, args)
+ return !!opts.sharedProjectId && target.githubIssues && target.projectId !== opts.sharedProjectId
+ }
+
+ const githubIssuesRefusal = (id: number): RpcErr => ({
+ t: 'res',
+ id,
+ ok: false,
+ error: { code: 'E_FORBIDDEN', message: 'GitHub Issues project is outside this relay session' }
+ })
+
const socket = connectRelay({
url: opts.url,
token: opts.token,
@@ -249,6 +285,10 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
return
}
if (m.t === 'req') {
+ if (githubIssuesOutOfScope(m.method, m.args)) {
+ socket.sendTunnelText(JSON.stringify(githubIssuesRefusal(m.id)))
+ return
+ }
// Board-log read/append naming a project outside this session's scope: refuse WITHOUT
// dispatching (the host router never resolves it), degrading exactly as an unknown project.
if (
@@ -263,6 +303,7 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio
.dispatch(id, m)
.then((res) => socket.sendTunnelText(JSON.stringify(scopeResponse(m.method, res))))
} else if (m.t === 'cast') {
+ if (githubIssuesOutOfScope(m.method, m.args)) return
// Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this
// connection's net per-project count so a dropped guest's watch is released in detach().
if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {
diff --git a/src/preload/index.test.ts b/src/preload/index.test.ts
index fcd9e12b6..7b6738a9b 100644
--- a/src/preload/index.test.ts
+++ b/src/preload/index.test.ts
@@ -36,6 +36,15 @@ import './index'
const api = h.exposed.nodeTerminal as NodeTerminalApi
describe('preload sshProject passphrase wiring', () => {
+ it('exposes GitHub issue data and host-control namespaces on their exact channels', async () => {
+ await api.githubIssues.query({ projectId: 'p1', columnId: null, pageSize: 50 })
+ await api.githubControl.saveToken('write-only-secret')
+ expect(h.invoke).toHaveBeenCalledWith(IPC.githubIssuesQuery, {
+ projectId: 'p1', columnId: null, pageSize: 50
+ })
+ expect(h.invoke).toHaveBeenCalledWith(IPC.githubControlSaveToken, 'write-only-secret')
+ })
+
it('submitPassphrase invokes the submit channel with (requestId, value) in that order', async () => {
await api.sshProject.submitPassphrase('req-1', 'hunter2')
expect(h.invoke).toHaveBeenCalledWith(IPC.sshPassphraseSubmit, 'req-1', 'hunter2')
diff --git a/src/preload/index.ts b/src/preload/index.ts
index f647496d8..12206398a 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -134,6 +134,31 @@ const api: NodeTerminalApi = {
load: () => ipcRenderer.invoke(IPC.settingsLoad),
save: (settings) => ipcRenderer.invoke(IPC.settingsSave, settings)
},
+ githubIssues: {
+ subscribe: (projectId) => ipcRenderer.invoke(IPC.githubIssuesSubscribe, { projectId }),
+ unsubscribe: async (projectId) => {
+ ipcRenderer.send(IPC.githubIssuesUnsubscribe, projectId)
+ },
+ query: (request) => ipcRenderer.invoke(IPC.githubIssuesQuery, request),
+ refresh: (projectId, full) => ipcRenderer.invoke(IPC.githubIssuesRefresh, projectId, full),
+ moveIssue: (request) => ipcRenderer.invoke(IPC.githubIssuesMove, request),
+ createMissingLabels: (projectId) => ipcRenderer.invoke(IPC.githubIssuesCreateLabels, projectId),
+ clearCache: (projectId) => ipcRenderer.invoke(IPC.githubIssuesClearCache, projectId),
+ onChanged: (projectId, listener) => {
+ const channel = IPC.githubIssuesChanged(projectId)
+ const handler = (_event: unknown, changed: number[]) => listener(changed)
+ ipcRenderer.on(channel, handler)
+ return () => ipcRenderer.removeListener(channel, handler)
+ }
+ },
+ githubControl: {
+ status: (projectId) => ipcRenderer.invoke(IPC.githubControlStatus, projectId),
+ approve: (input) => ipcRenderer.invoke(IPC.githubControlApprove, input),
+ revoke: (input) => ipcRenderer.invoke(IPC.githubControlRevoke, input),
+ selectProvider: (input) => ipcRenderer.invoke(IPC.githubControlSelectProvider, input),
+ saveToken: (token) => ipcRenderer.invoke(IPC.githubControlSaveToken, token),
+ clearToken: () => ipcRenderer.invoke(IPC.githubControlClearToken)
+ },
speech: {
// IPC carries the raw Float32 samples as an ArrayBuffer (structured clone; decodePcmPayload's
// ArrayBuffer branch reads it directly, no re-encoding). A Float32Array view doesn't always
diff --git a/src/renderer/bridge/relay-api.test.ts b/src/renderer/bridge/relay-api.test.ts
index 014b549e8..ee224c6f5 100644
--- a/src/renderer/bridge/relay-api.test.ts
+++ b/src/renderer/bridge/relay-api.test.ts
@@ -44,6 +44,7 @@ function fakeLocalApi() {
updates: { NAME: 'local-updates' },
clipboard: { NAME: 'local-clipboard' },
settings: { NAME: 'local-settings' },
+ githubControl: { NAME: 'local-github-control' },
dialog: { NAME: 'local-dialog' },
license: { NAME: 'local-license' },
pty: { onData: ptyOnData },
@@ -91,6 +92,17 @@ describe('buildRelayApi', () => {
expect(api.clipboard).toBe(local.clipboard)
expect(api.settings).toBe(local.settings)
expect(api.license).toBe(local.license)
+ expect(api.githubControl).toBe(local.githubControl)
+ })
+
+ it('routes GitHub issue data to the host while keeping control local', () => {
+ const { local } = fakeLocalApi()
+ ;(globalThis as Record<string, unknown>).window = { nodeTerminal: local }
+ const t = new FakeTransport()
+ const { api } = buildRelayApi('conn-1', t)
+
+ void api.githubIssues.query({ projectId: 'p1', columnId: null, pageSize: 50 })
+ expect(JSON.parse(t.sent[0])).toMatchObject({ t: 'req', method: IPC.githubIssuesQuery })
})
it('routes the folder/file picker to the HOST fs, not the local native dialog', () => {
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index 050f86d85..d93e26b5e 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -39,7 +39,8 @@ import {
buildAgentApi,
buildCanvasApi,
buildPresenceApi,
- buildClaudeApi
+ buildClaudeApi,
+ buildGitHubApi
} from './ws-bridge'
import { buildStubApi } from './stubs'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
@@ -69,6 +70,7 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
const real = buildRealApi(client) // { pty, workspace, settings, userDataDir }
const files = buildFilesApi(client) // { fs, git, files, context }
+ const github = buildGitHubApi(client)
const stub = buildStubApi()
const api: NodeTerminalApi = {
@@ -85,6 +87,8 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
git: files.git,
files: files.files,
context: files.context,
+ githubIssues: github.githubIssues,
+ githubControl: local.githubControl,
...buildAgentApi(client), // onAgentStatus / onSubagentActivity — the host's agent hooks
...buildCanvasApi(client), // canvas sync against the host's reflector
...buildPresenceApi(client), // the host's presence hub
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 5edede686..0e3baee2b 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -111,6 +111,8 @@ export function buildStubApi(): Omit<
| 'files'
| 'context'
| 'boardLog'
+ | 'githubIssues'
+ | 'githubControl'
| 'canvas'
| 'dialog'
| 'onAgentStatus'
@@ -345,6 +347,8 @@ export function buildStubApi(): Omit<
| 'files'
| 'context'
| 'boardLog'
+ | 'githubIssues'
+ | 'githubControl'
| 'canvas'
| 'dialog'
| 'onAgentStatus'
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index f31c98230..95e7a54a0 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -14,6 +14,7 @@ import {
type RpcMessage
} from '../../shared/rpc'
import { IPC } from '../../shared/ipc'
+import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'
import {
UNKNOWN_CLAUDE_CLI_CAPS,
type BoardLogApi,
@@ -278,6 +279,53 @@ export function buildRealApi(
return { pty, workspace, settings, userDataDir }
}
+export function buildGitHubApi(
+ client: RpcClient
+): Pick<NodeTerminalApi, 'githubIssues' | 'githubControl'> {
+ const githubIssues: GitHubIssuesApi = {
+ subscribe: (projectId) =>
+ client.request(IPC.githubIssuesSubscribe, { projectId }) as ReturnType<
+ GitHubIssuesApi['subscribe']
+ >,
+ unsubscribe: async (projectId) => {
+ client.cast(IPC.githubIssuesUnsubscribe, projectId)
+ },
+ query: (request) =>
+ client.request(IPC.githubIssuesQuery, request) as ReturnType<GitHubIssuesApi['query']>,
+ refresh: (projectId, full) =>
+ client.request(IPC.githubIssuesRefresh, projectId, full) as Promise<void>,
+ moveIssue: (request) =>
+ client.request(IPC.githubIssuesMove, request) as ReturnType<GitHubIssuesApi['moveIssue']>,
+ createMissingLabels: (projectId) =>
+ client.request(IPC.githubIssuesCreateLabels, projectId) as ReturnType<
+ GitHubIssuesApi['createMissingLabels']
+ >,
+ clearCache: (projectId) =>
+ client.request(IPC.githubIssuesClearCache, projectId) as Promise<void>,
+ onChanged: (projectId, listener) =>
+ client.subscribe(IPC.githubIssuesChanged(projectId), listener as Listener)
+ }
+
+ const githubControl: GitHubControlApi = {
+ status: (projectId) =>
+ client.request(IPC.githubControlStatus, projectId) as ReturnType<GitHubControlApi['status']>,
+ approve: (input) =>
+ client.request(IPC.githubControlApprove, input) as ReturnType<GitHubControlApi['approve']>,
+ revoke: (input) =>
+ client.request(IPC.githubControlRevoke, input) as ReturnType<GitHubControlApi['revoke']>,
+ selectProvider: (input) =>
+ client.request(IPC.githubControlSelectProvider, input) as ReturnType<
+ GitHubControlApi['selectProvider']
+ >,
+ saveToken: (token) =>
+ client.request(IPC.githubControlSaveToken, token) as ReturnType<GitHubControlApi['saveToken']>,
+ clearToken: () =>
+ client.request(IPC.githubControlClearToken) as ReturnType<GitHubControlApi['clearToken']>
+ }
+
+ return { githubIssues, githubControl }
+}
+
/**
* Build the real `fs` / `git` / `files` / `context` namespaces over an RpcClient, mirroring the
* preload's invoke(→request) / send(→cast) / on*(→subscribe) split member-for-member. Every
@@ -724,6 +772,7 @@ export async function installWsBridge(): Promise<boolean> {
...buildPresenceApi(client),
...buildSpeechApi(client),
...buildUsageApi(client),
+ ...buildGitHubApi(client),
// `claude` is assembled from two builders: `cliCaps` from the relay-shared one, and the
// transcript reader from the Server-Edition-only one (which also supplies `chat`).
...(() => {
diff --git a/src/renderer/components/kanban/GitHubIssueCard.test.tsx b/src/renderer/components/kanban/GitHubIssueCard.test.tsx
new file mode 100644
index 000000000..f4d1bb4b5
--- /dev/null
+++ b/src/renderer/components/kanban/GitHubIssueCard.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { describe, expect, it, vi } from 'vitest'
+import type { GitHubIssueCardView } from '@shared/github-issues'
+import { GitHubIssueCard } from './GitHubIssueCard'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const issue: GitHubIssueCardView = {
+ id: 42, number: 42, title: 'Fix polling', body: '', state: 'open', stateReason: null,
+ htmlUrl: 'https://github.com/o/r/issues/42', apiUrl: 'https://api.github.com/repos/o/r/issues/42',
+ labels: [{ id: 1, name: 'bug', color: 'ff0000' }], assignees: [],
+ createdAt: '2026-08-09T00:00:00Z', updatedAt: '2026-08-09T00:00:00Z', locked: false,
+ columnId: 'todo', conflict: null
+}
+
+describe('GitHubIssueCard', () => {
+ it('renders its source and exposes an accessible non-drag move action', () => {
+ const host = document.createElement('div')
+ const root = createRoot(host)
+ const move = vi.fn()
+ act(() => root.render(
+ <GitHubIssueCard
+ issue={issue}
+ columns={[
+ { id: 'todo', title: 'Todo', color: '#2563eb' },
+ { id: 'done', title: 'Done', color: '#16a34a' }
+ ]}
+ moving={false}
+ readOnly={false}
+ onOpen={vi.fn()}
+ onMove={move}
+ onDragStart={vi.fn()}
+ onDragEnd={vi.fn()}
+ />
+ ))
+ expect(host.textContent).toContain('#42')
+ expect(host.textContent).toContain('Fix polling')
+ expect(host.textContent).toContain('GH')
+ const select = host.querySelector<HTMLSelectElement>('select[aria-label="Move issue #42"]')!
+ act(() => {
+ select.value = 'done'
+ select.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ expect(move).toHaveBeenCalledWith(issue, 'done')
+ const card = host.querySelector<HTMLElement>('[role="button"]')!
+ const open = vi.fn()
+ act(() => root.render(
+ <GitHubIssueCard issue={issue} columns={[]} moving={false} readOnly={false}
+ onOpen={open} onMove={vi.fn()} onDragStart={vi.fn()} onDragEnd={vi.fn()} />
+ ))
+ act(() => card.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })))
+ expect(open).toHaveBeenCalledWith(issue)
+ act(() => root.unmount())
+ })
+})
diff --git a/src/renderer/components/kanban/GitHubIssueCard.tsx b/src/renderer/components/kanban/GitHubIssueCard.tsx
new file mode 100644
index 000000000..f304591eb
--- /dev/null
+++ b/src/renderer/components/kanban/GitHubIssueCard.tsx
@@ -0,0 +1,117 @@
+import { memo, useState } from 'react'
+import type { GitHubIssueCardView } from '@shared/github-issues'
+import type { KanbanColumn } from '@shared/types'
+
+function relativeTime(value: string): string {
+ const milliseconds = Date.now() - Date.parse(value)
+ if (!Number.isFinite(milliseconds) || milliseconds < 0) return 'updated recently'
+ const minutes = Math.floor(milliseconds / 60_000)
+ if (minutes < 1) return 'updated now'
+ if (minutes < 60) return `updated ${minutes}m ago`
+ const hours = Math.floor(minutes / 60)
+ if (hours < 24) return `updated ${hours}h ago`
+ return `updated ${Math.floor(hours / 24)}d ago`
+}
+
+export const GitHubIssueCard = memo(function GitHubIssueCard({
+ issue,
+ columns,
+ moving,
+ readOnly,
+ status,
+ onOpen,
+ onMove,
+ onDragStart,
+ onDragEnd
+}: {
+ issue: GitHubIssueCardView
+ columns: KanbanColumn[]
+ moving: boolean
+ readOnly: boolean
+ status?: string
+ onOpen: (issue: GitHubIssueCardView) => void
+ onMove: (issue: GitHubIssueCardView, columnId: string | null) => void
+ onDragStart: (issue: GitHubIssueCardView) => void
+ onDragEnd: () => void
+}): React.JSX.Element {
+ const [dragging, setDragging] = useState(false)
+ return (
+ <article
+ className={`kanban-card kanban-card--github${dragging ? ' kanban-card--dragging' : ''}`}
+ role="button"
+ tabIndex={0}
+ aria-label={`Open GitHub issue #${issue.number}: ${issue.title}`}
+ draggable={!moving && !readOnly}
+ onDragStart={(event) => {
+ event.dataTransfer.effectAllowed = 'move'
+ setDragging(true)
+ onDragStart(issue)
+ }}
+ onDragEnd={() => {
+ setDragging(false)
+ onDragEnd()
+ }}
+ onClick={() => onOpen(issue)}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return
+ if ((event.target as HTMLElement).closest('select')) return
+ event.preventDefault()
+ onOpen(issue)
+ }}
+ >
+ <div className="kanban-card__row">
+ <span className={`github-issue-state github-issue-state--${issue.state}`} aria-hidden="true" />
+ <span className="kanban-card__title">{issue.title}</span>
+ <span className="github-issue-source" title="GitHub issue">GH</span>
+ </div>
+ <div className="github-issue-card__number">#{issue.number}</div>
+ {issue.labels.length > 0 && (
+ <div className="github-issue-card__labels">
+ {issue.labels.slice(0, 5).map((label) => (
+ <span
+ key={label.id}
+ className="github-issue-label"
+ style={{ borderColor: `#${label.color}`, color: `#${label.color}` }}
+ >
+ {label.name}
+ </span>
+ ))}
+ {issue.labels.length > 5 && <span className="github-issue-label">+{issue.labels.length - 5}</span>}
+ </div>
+ )}
+ <div className="github-issue-card__footer">
+ <span>{moving ? 'Syncing…' : relativeTime(issue.updatedAt)}</span>
+ {issue.conflict && <span className="github-issue-conflict">Needs a column</span>}
+ {issue.assignees.length > 0 && (
+ <span className="kanban-card__avatars">
+ {issue.assignees.slice(0, 3).map((assignee) => {
+ const avatar = issue.avatarDataUrls?.[String(assignee.id)]
+ return avatar ? (
+ <img key={assignee.id} className="github-issue-avatar" src={avatar} alt={assignee.login} />
+ ) : (
+ <span key={assignee.id} className="github-issue-avatar github-issue-avatar--initial" title={assignee.login}>
+ {(assignee.login[0] ?? '?').toUpperCase()}
+ </span>
+ )
+ })}
+ </span>
+ )}
+ <label className="github-issue-move" onClick={(event) => event.stopPropagation()}>
+ <span className="sr-only">Move issue #{issue.number}</span>
+ <select
+ aria-label={`Move issue #${issue.number}`}
+ value={issue.columnId ?? ''}
+ disabled={moving || readOnly}
+ onChange={(event) => onMove(issue, event.target.value || null)}
+ >
+ <option value="">Ungrouped</option>
+ {columns.map((column) => (
+ <option key={column.id} value={column.id}>{column.title}</option>
+ ))}
+ </select>
+ </label>
+ </div>
+ {status && <div className="github-issue-card__status" role="status">{status}</div>}
+ </article>
+ )
+})
diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx
new file mode 100644
index 000000000..90fba1391
--- /dev/null
+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx
@@ -0,0 +1,45 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { describe, expect, it, vi } from 'vitest'
+import type { GitHubIssueCardView } from '@shared/github-issues'
+import { GitHubIssueSummaryModal } from './GitHubIssueSummaryModal'
+
+vi.mock('../../session/session', () => ({
+ useSession: () => ({ api: { shell: { openExternal: vi.fn(async () => {}) } } })
+}))
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const issue: GitHubIssueCardView = {
+ id: 1, number: 1, title: 'Keyboard access', body: '', state: 'open', stateReason: null,
+ htmlUrl: 'https://github.com/o/r/issues/1', apiUrl: 'https://api.github.com/repos/o/r/issues/1',
+ labels: [], assignees: [], createdAt: '2026-08-09T00:00:00Z',
+ updatedAt: '2026-08-09T00:00:00Z', locked: false, columnId: null, conflict: null
+}
+
+describe('GitHubIssueSummaryModal', () => {
+ it('contains keyboard focus and restores it when closed', () => {
+ const opener = document.createElement('button')
+ document.body.append(opener)
+ opener.focus()
+ const host = document.createElement('div')
+ document.body.append(host)
+ const root = createRoot(host)
+ act(() => root.render(
+ <GitHubIssueSummaryModal issue={issue} columns={[]} moving={false} readOnly={false}
+ onMove={vi.fn()} onClose={vi.fn()} />
+ ))
+ const close = host.querySelector<HTMLButtonElement>('[aria-label="Close"]')!
+ const buttons = host.querySelectorAll<HTMLButtonElement>('button')
+ const last = buttons[buttons.length - 1]
+ expect(document.activeElement).toBe(close)
+ last.focus()
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' })))
+ expect(document.activeElement).toBe(close)
+ act(() => root.unmount())
+ expect(document.activeElement).toBe(opener)
+ host.remove()
+ opener.remove()
+ })
+})
diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
new file mode 100644
index 000000000..20608fec4
--- /dev/null
+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
@@ -0,0 +1,99 @@
+import { useEffect, useRef } from 'react'
+import type { GitHubIssueCardView } from '@shared/github-issues'
+import type { KanbanColumn } from '@shared/types'
+import { useSession } from '../../session/session'
+import { Button } from '@renderer/ui/Button'
+import { Select } from '@renderer/ui/Select'
+
+export function GitHubIssueSummaryModal({
+ issue,
+ columns,
+ moving,
+ readOnly,
+ status,
+ onMove,
+ onClose
+}: {
+ issue: GitHubIssueCardView
+ columns: KanbanColumn[]
+ moving: boolean
+ readOnly: boolean
+ status?: string
+ onMove: (columnId: string | null) => void
+ onClose: () => void
+}): React.JSX.Element {
+ const { api } = useSession()
+ const close = useRef<HTMLButtonElement>(null)
+ const dialog = useRef<HTMLElement>(null)
+ const opener = useRef(document.activeElement instanceof HTMLElement ? document.activeElement : null)
+ useEffect(() => {
+ close.current?.focus()
+ return () => opener.current?.focus()
+ }, [])
+ useEffect(() => {
+ const key = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') onClose()
+ if (event.key === 'Tab' && dialog.current) {
+ const focusable = [...dialog.current.querySelectorAll<HTMLElement>(
+ 'button:not([disabled]), select:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'
+ )]
+ if (focusable.length === 0) return
+ const first = focusable[0]
+ const last = focusable[focusable.length - 1]
+ if (event.shiftKey && document.activeElement === first) {
+ event.preventDefault()
+ last.focus()
+ } else if (!event.shiftKey && document.activeElement === last) {
+ event.preventDefault()
+ first.focus()
+ }
+ }
+ }
+ window.addEventListener('keydown', key)
+ return () => window.removeEventListener('keydown', key)
+ }, [onClose])
+ return (
+ <div className="kanban-modal-scrim" role="presentation" onMouseDown={onClose}>
+ <section
+ ref={dialog}
+ className="github-issue-modal"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="github-issue-modal-title"
+ onMouseDown={(event) => event.stopPropagation()}
+ >
+ <header className="github-issue-modal__header">
+ <div>
+ <div className="github-issue-modal__eyebrow">GitHub issue #{issue.number}</div>
+ <h2 id="github-issue-modal-title">{issue.title}</h2>
+ </div>
+ <button ref={close} className="github-issue-modal__close" onClick={onClose} aria-label="Close">×</button>
+ </header>
+ <div className="github-issue-modal__actions">
+ <label>
+ <span>Move to</span>
+ <Select
+ aria-label={`Move issue #${issue.number}`}
+ value={issue.columnId ?? ''}
+ disabled={moving || readOnly}
+ onChange={(event) => onMove(event.target.value || null)}
+ >
+ <option value="">Ungrouped</option>
+ {columns.map((column) => <option key={column.id} value={column.id}>{column.title}</option>)}
+ </Select>
+ </label>
+ <Button onClick={() => void api.shell.openExternal(issue.htmlUrl)}>Open on GitHub</Button>
+ </div>
+ {issue.conflict && (
+ <p className="github-issue-modal__warning">
+ This issue has conflicting mapped labels. Choose a column to replace them with one exact label.
+ </p>
+ )}
+ {status && <p className="github-issue-modal__warning" role="status">{status}</p>}
+ <div className="github-issue-modal__body">
+ {issue.body.trim() || 'No description provided.'}
+ </div>
+ </section>
+ </div>
+ )
+}
diff --git a/src/renderer/components/kanban/KanbanColumn.tsx b/src/renderer/components/kanban/KanbanColumn.tsx
index b6b87a681..2c76b9dbd 100644
--- a/src/renderer/components/kanban/KanbanColumn.tsx
+++ b/src/renderer/components/kanban/KanbanColumn.tsx
@@ -4,11 +4,19 @@ import { NODE_COLORS } from '../../state/workspace'
import { SessionCard } from './SessionCard'
import type { KanbanCardMeta, KanbanLabel } from '@shared/types'
import type { KanbanCreateChoice, KanbanCreateOption, KanbanSession } from './KanbanView'
+import type { GitHubIssueCardView } from '@shared/github-issues'
+import { GitHubIssueCard } from './GitHubIssueCard'
interface KanbanColumnProps {
/** null = the virtual Ungrouped column: fixed label, no rename/recolor/delete, header not draggable. */
column: KanbanColumnT | null
cards: KanbanSession[]
+ githubCards?: GitHubIssueCardView[]
+ githubColumns?: KanbanColumnT[]
+ githubMoving?: Record<number, true>
+ githubReadOnly?: boolean
+ githubStatus?: Record<number, string>
+ displayCount?: number
// Column-scoped callbacks carry the column id (and card-scoped ones the node id) so KanbanView
// can hand every column the SAME function references — that identity stability is what lets
// memo() skip columns/cards untouched by a render.
@@ -34,10 +42,18 @@ interface KanbanColumnProps {
onDropAtCard: (columnId: string | null, nodeId: string, side: 'before' | 'after') => void
/** Right-click on a card — bubbles the cursor position + node id up to the board menu. */
onCardContext: (nodeId: string, x: number, y: number) => void
+ onOpenGitHub?: (issue: GitHubIssueCardView) => void
+ onMoveGitHub?: (issue: GitHubIssueCardView, columnId: string | null) => void
+ onGitHubDragStart?: (issue: GitHubIssueCardView) => void
+ onLoadMoreGitHub?: (columnId: string | null) => void
+ hasMoreGitHub?: boolean
}
export const KanbanColumn = memo(function KanbanColumn({
- column, cards, metaOf, labelsOf, onRename, onRecolor, onDelete, onOpenCard, onCardContext,
+ column, cards, githubCards = [], githubColumns = [], githubMoving = {}, displayCount, metaOf, labelsOf,
+ githubReadOnly = false, githubStatus = {},
+ onRename, onRecolor, onDelete, onOpenCard, onCardContext, onOpenGitHub, onMoveGitHub,
+ onGitHubDragStart, onLoadMoreGitHub, hasMoreGitHub,
createOptions, onCreate, onCardDragStart, onColumnDragStart, onDragEnd, onDropOnColumn,
onDropAtCard
}: KanbanColumnProps) {
@@ -117,7 +133,7 @@ export const KanbanColumn = memo(function KanbanColumn({
{column ? column.title : 'Ungrouped'}
</span>
)}
- <span className="kanban-col__count">{cards.length}</span>
+ <span className="kanban-col__count">{displayCount ?? cards.length + githubCards.length}</span>
{column && (
<button
className="kanban-col__close"
@@ -157,6 +173,25 @@ export const KanbanColumn = memo(function KanbanColumn({
onDropAt={dropAtCard}
/>
))}
+ {githubCards.map((issue) => (
+ <GitHubIssueCard
+ key={`github:${issue.id}`}
+ issue={issue}
+ columns={githubColumns}
+ moving={!!githubMoving[issue.number]}
+ readOnly={githubReadOnly}
+ status={githubStatus[issue.number]}
+ onOpen={(item) => onOpenGitHub?.(item)}
+ onMove={(item, target) => onMoveGitHub?.(item, target)}
+ onDragStart={(item) => onGitHubDragStart?.(item)}
+ onDragEnd={onDragEnd}
+ />
+ ))}
+ {hasMoreGitHub && (
+ <button className="kanban-github-more" onClick={() => onLoadMoreGitHub?.(colId)}>
+ Show more issues
+ </button>
+ )}
</div>
<div className="kanban-col__footer">
{newMenuOpen && (
diff --git a/src/renderer/components/kanban/KanbanSourceFilter.test.tsx b/src/renderer/components/kanban/KanbanSourceFilter.test.tsx
new file mode 100644
index 000000000..26fade1cd
--- /dev/null
+++ b/src/renderer/components/kanban/KanbanSourceFilter.test.tsx
@@ -0,0 +1,21 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { describe, expect, it, vi } from 'vitest'
+import { KanbanSourceFilter } from './KanbanSourceFilter'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+describe('KanbanSourceFilter', () => {
+ it('offers All, GitHub, and Sessions without changing board data', () => {
+ const host = document.createElement('div')
+ const root = createRoot(host)
+ const onChange = vi.fn()
+ act(() => root.render(<KanbanSourceFilter value="all" onChange={onChange} />))
+ expect([...host.querySelectorAll('button')].map((button) => button.textContent))
+ .toEqual(['All', 'GitHub', 'Sessions'])
+ act(() => host.querySelectorAll('button')[1].click())
+ expect(onChange).toHaveBeenCalledWith('github')
+ act(() => root.unmount())
+ })
+})
diff --git a/src/renderer/components/kanban/KanbanSourceFilter.tsx b/src/renderer/components/kanban/KanbanSourceFilter.tsx
new file mode 100644
index 000000000..7ca44d147
--- /dev/null
+++ b/src/renderer/components/kanban/KanbanSourceFilter.tsx
@@ -0,0 +1,25 @@
+export type KanbanSource = 'all' | 'github' | 'sessions'
+
+export function KanbanSourceFilter({
+ value,
+ onChange
+}: {
+ value: KanbanSource
+ onChange: (value: KanbanSource) => void
+}): React.JSX.Element {
+ return (
+ <div className="kanban-source-filter" role="group" aria-label="Card source">
+ {(['all', 'github', 'sessions'] as const).map((source) => (
+ <button
+ key={source}
+ type="button"
+ className={value === source ? 'kanban-source-filter__button is-active' : 'kanban-source-filter__button'}
+ aria-pressed={value === source}
+ onClick={() => onChange(source)}
+ >
+ {source === 'all' ? 'All' : source === 'github' ? 'GitHub' : 'Sessions'}
+ </button>
+ ))}
+ </div>
+ )
+}
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index ffab253e6..13e299c7c 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -16,6 +16,17 @@ import { KanbanColumn } from './KanbanColumn'
import type { ModalSpawn } from './ModalTerminal'
import { ContextMenu, type MenuItem } from '../ContextMenu'
import { IconAgent, IconExternal, IconNote, IconSwitch, IconTerminal, IconTrash, IconWeb } from '../icons'
+import type { GitHubIssueCardView } from '@shared/github-issues'
+import { useGitHubIssues } from '../../state/githubIssues'
+import { useSession } from '../../session/session'
+import { KanbanSourceFilter, type KanbanSource } from './KanbanSourceFilter'
+import { GitHubIssueSummaryModal } from './GitHubIssueSummaryModal'
+import { ConfirmDialog } from '../ConfirmDialog'
+import {
+ githubMoveConfirmation,
+ githubMoveIntent,
+ type GitHubMoveConfirmation
+} from '../../lib/githubIssueMove'
/** One session node shown as a board card — derived LIVE from the canvas nodes; the board
* itself stores only column assignments. */
@@ -70,7 +81,10 @@ export interface KanbanViewProps {
onBrowserNav: (nodeId: string, patch: { url?: string; title?: string }) => void
}
-type Drag = { kind: 'card' | 'column'; id: string } | null
+type Drag =
+ | { kind: 'card' | 'column'; id: string }
+ | { kind: 'github'; issue: GitHubIssueCardView }
+ | null
/** Shared empty results — stable identities so memoized cards/columns see "no change". */
const NO_LABELS: KanbanLabel[] = []
@@ -86,6 +100,7 @@ export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
onModalNodeChange, onBrowserNav
}: KanbanViewProps) {
+ const { api } = useSession()
const dragRef = useRef<Drag>(null)
// One card modal at a time; a deleted node closes it via the byId.has render guard.
const [modalNodeId, setModalNodeId] = useState<string | null>(null)
@@ -95,12 +110,45 @@ export const KanbanView = memo(function KanbanView({
// show everything; otherwise a card must carry at least one selected label (cardMatchesLabelFilter).
const [labelFilter, setLabelFilter] = useState<string[]>([])
const [filterOpen, setFilterOpen] = useState(false)
+ const [source, setSource] = useState<KanbanSource>('all')
+ const [modalIssue, setModalIssue] = useState<GitHubIssueCardView | null>(null)
+ const [githubRetry, setGitHubRetry] = useState(0)
+ // A move that would close or reopen the issue on GitHub waits here for an explicit confirmation.
+ const [pendingGitHubMove, setPendingGitHubMove] = useState<
+ { issue: GitHubIssueCardView; columnId: string | null; confirmation: GitHubMoveConfirmation } | null
+ >(null)
+ // Primitive selectors (not one object) — an object selector would re-render on every store set.
+ const projectId = useProjects((s) => s.activeProjectId)
+ const projectName = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.name)
+ const projectColor = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.color)
+ const github = useGitHubIssues((state) => state.projects[projectId])
+ const githubReadOnly = Object.values(github?.pages ?? {}).some((page) => page.readOnly)
+ const connectGitHub = useGitHubIssues((state) => state.connect)
+ const moveGitHubState = useGitHubIssues((state) => state.move)
+ const loadMoreGitHub = useGitHubIssues((state) => state.loadMore)
// Drop ids no longer in the palette so a deleted label can't keep the board filtered to nothing.
const paletteLabels = useMemo(() => boardLabels(board), [board])
+ const githubLabels = useMemo(() => {
+ const labels = new Map<string, { name: string; color: string }>()
+ for (const page of Object.values(github?.pages ?? {})) {
+ for (const issue of page.items) {
+ for (const label of issue.labels) {
+ const key = label.name.normalize('NFKC').toLocaleLowerCase('en-US')
+ if (!labels.has(key)) labels.set(key, { name: label.name, color: label.color })
+ }
+ }
+ }
+ return [...labels.values()].sort((a, b) => a.name.localeCompare(b.name))
+ }, [github?.pages])
+ const localFilterKeys = useMemo(() => new Set(paletteLabels.map((label) => `local:${label.id}`)), [paletteLabels])
const activeFilter = useMemo(
- () => labelFilter.filter((id) => paletteLabels.some((l) => l.id === id)),
- [labelFilter, paletteLabels]
+ () => labelFilter.filter((id) => localFilterKeys.has(id) || id.startsWith('github:')),
+ [labelFilter, localFilterKeys]
)
+ const activeLocalFilter = useMemo(() => activeFilter
+ .filter((key) => key.startsWith('local:')).map((key) => key.slice(6)), [activeFilter])
+ const activeGitHubFilter = useMemo(() => activeFilter
+ .filter((key) => key.startsWith('github:')), [activeFilter])
const toggleFilter = (id: string): void =>
setLabelFilter((f) => (f.includes(id) ? f.filter((x) => x !== id) : [...f, id]))
// Opening a card = you're looking at that session: clear its unread badge, and report the open
@@ -118,9 +166,41 @@ export const KanbanView = memo(function KanbanView({
setModalNodeId(requestedCardNodeId)
useViewMode.getState().clearCardRequest()
}, [requestedCardNodeId])
- // Primitive selectors (not one object) — an object selector would re-render on every store set.
- const projectName = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.name)
- const projectColor = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.color)
+ const githubConfigKey = JSON.stringify(board.github ?? null)
+ const columnIdsKey = board.columns.map((column) => column.id).join('\0')
+ const githubFilterKey = activeGitHubFilter.join('\0')
+ useEffect(() => {
+ if (!board.github || !projectId) return
+ let disposed = false
+ let disconnect: (() => void) | undefined
+ void connectGitHub(
+ api.githubIssues,
+ projectId,
+ board.columns.map((column) => column.id),
+ activeGitHubFilter
+ )
+ .then((teardown) => {
+ if (disposed) teardown()
+ else disconnect = teardown
+ })
+ return () => {
+ disposed = true
+ disconnect?.()
+ }
+ // The serialised config is the epoch visible to the renderer. Reconnect when mappings change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [api, projectId, githubConfigKey, columnIdsKey, githubFilterKey, connectGitHub, githubRetry])
+ useEffect(() => {
+ setSource('all')
+ setModalIssue(null)
+ }, [projectId])
+ useEffect(() => {
+ if (!modalIssue || !github) return
+ const latest = Object.values(github.pages)
+ .flatMap((page) => page.items)
+ .find((issue) => issue.number === modalIssue.number)
+ if (latest && latest.updatedAt !== modalIssue.updatedAt) setModalIssue(latest)
+ }, [github, modalIssue])
const customAgents = useSettings((s) => s.settings.customAgents)
// "+ New" menu entries: the builtin agents, the user's custom agents, then terminal + sticky
// (same universe as the dock's add menu, minus canvas-only kinds). Memoized — a fresh array
@@ -177,22 +257,48 @@ export const KanbanView = memo(function KanbanView({
return d
}
+ // The ONE path every GitHub card move takes — drag drop, the card's Move selector, and the
+ // summary modal — so none of them can skip the confirmation the others ask for.
+ const requestGitHubMove = useCallback(
+ (issue: GitHubIssueCardView, columnId: string | null) => {
+ if (githubReadOnly) return
+ const completion = board.github?.completionColumnId
+ const intent = githubMoveIntent(issue, columnId, completion)
+ // Dropping a card back where it already sits is not a write: sending it would spend an API
+ // call and let GitHub rewrite state_reason for no reason the user asked for.
+ if (intent.kind === 'noop') return
+ const confirmation = githubMoveConfirmation(issue, columnId, completion)
+ if (confirmation) {
+ setPendingGitHubMove({ issue, columnId, confirmation })
+ return
+ }
+ void moveGitHubState(api.githubIssues, projectId, issue.number, columnId, issue.updatedAt)
+ },
+ [api.githubIssues, board.github?.completionColumnId, githubReadOnly, moveGitHubState, projectId]
+ )
+
// columnId null = the virtual Ungrouped column.
const dropOnColumn = useCallback(
(columnId: string | null) => {
const drag = takeDrag()
if (!drag) return
- if (drag.kind === 'card') commit(assignNode(board, drag.id, columnId, null))
+ if (drag.kind === 'github') {
+ requestGitHubMove(drag.issue, columnId)
+ } else if (drag.kind === 'card') commit(assignNode(board, drag.id, columnId, null))
else if (columnId !== null) commit(moveColumn(board, drag.id, columnId))
// a column dropped on Ungrouped is a no-op — Ungrouped is always first
},
- [board, commit]
+ [board, commit, requestGitHubMove]
)
const dropAtCard = useCallback(
(columnId: string | null, targetNodeId: string, side: 'before' | 'after') => {
const drag = takeDrag()
if (!drag) return
+ if (drag.kind === 'github') {
+ requestGitHubMove(drag.issue, columnId)
+ return
+ }
if (drag.kind === 'column') {
if (columnId !== null) commit(moveColumn(board, drag.id, columnId))
return
@@ -206,7 +312,7 @@ export const KanbanView = memo(function KanbanView({
}
commit(assignNode(board, drag.id, columnId, beforeId))
},
- [board, commit, sessionIds]
+ [board, commit, requestGitHubMove, sessionIds]
)
// Per-column card lists in one pass, so a board render doesn't re-derive (and re-allocate)
@@ -214,7 +320,7 @@ export const KanbanView = memo(function KanbanView({
// the sessions, nor the filter, which is what lets the memoized columns skip.
const columnCards = useMemo(() => {
const vis = (ids: string[]): string[] =>
- activeFilter.length ? ids.filter((id) => cardMatchesLabelFilter(board, id, activeFilter)) : ids
+ activeLocalFilter.length ? ids.filter((id) => cardMatchesLabelFilter(board, id, activeLocalFilter)) : ids
const toCards = (ids: string[]): KanbanSession[] => {
const cards = ids.flatMap((id) => (byId.has(id) ? [byId.get(id)!] : []))
return cards.length ? cards : NO_CARDS
@@ -223,13 +329,16 @@ export const KanbanView = memo(function KanbanView({
ungrouped: toCards(vis(unassigned(board, sessionIds))),
byColumn: new Map(board.columns.map((c) => [c.id, toCards(vis(assignedTo(board, c.id)))]))
}
- }, [board, byId, sessionIds, activeFilter])
+ }, [board, byId, sessionIds, activeLocalFilter])
// Stable column/card plumbing — every handler the memoized columns receive is identity-stable
// across renders (the column binds its own id; cards bind theirs).
const handleCardDragStart = useCallback((id: string) => {
dragRef.current = { kind: 'card', id }
}, [])
+ const handleGitHubDragStart = useCallback((issue: GitHubIssueCardView) => {
+ dragRef.current = { kind: 'github', issue }
+ }, [])
const handleColumnDragStart = useCallback((columnId: string) => {
dragRef.current = { kind: 'column', id: columnId }
}, [])
@@ -252,6 +361,11 @@ export const KanbanView = memo(function KanbanView({
(columnId: string) => commit(deleteColumn(board, columnId)),
[board, commit]
)
+ const handleMoveGitHub = requestGitHubMove
+ const githubPage = useCallback((columnId: string | null) =>
+ github?.pages[columnId ?? 'ungrouped'], [github])
+ const sessionVisible = source !== 'github'
+ const githubVisible = source !== 'sessions' && !!board.github
// Right-click menu for a card: open on canvas, move to another column, delete.
const cardMenuItems = (nodeId: string): MenuItem[] => {
@@ -285,7 +399,22 @@ export const KanbanView = memo(function KanbanView({
<div className="kanban-header">
<span className="kanban-header__dot" style={{ background: projectColor }} />
<span className="kanban-header__name">{projectName}</span>
- {paletteLabels.length > 0 && (
+ {board.github && <KanbanSourceFilter value={source} onChange={setSource} />}
+ {board.github && github?.loading && <span className="kanban-github-status">Loading GitHub issues…</span>}
+ {board.github && github?.error && (
+ <button
+ className="kanban-github-status kanban-github-status--error kanban-github-retry"
+ onClick={() => setGitHubRetry((value) => value + 1)}
+ >
+ GitHub issues unavailable · Retry
+ </button>
+ )}
+ {board.github && githubReadOnly && (
+ <span className="kanban-github-status kanban-github-status--error">
+ GitHub issues are read only until configuration and refresh are complete.
+ </span>
+ )}
+ {(paletteLabels.length > 0 || githubLabels.length > 0 || activeFilter.length > 0) && (
<div className="kanban-header__filter">
<button
className={`kanban-filter-btn${activeFilter.length ? ' kanban-filter-btn--on' : ''}`}
@@ -298,11 +427,13 @@ export const KanbanView = memo(function KanbanView({
<>
<div className="label-picker__scrim" onMouseDown={() => setFilterOpen(false)} />
<div className="kanban-filter-menu">
+ {paletteLabels.length > 0 && <div className="kanban-filter-group">Sessions</div>}
{paletteLabels.map((l) => {
const s = labelSwatch(l.color)
- const on = activeFilter.includes(l.id)
+ const key = `local:${l.id}`
+ const on = activeFilter.includes(key)
return (
- <button key={l.id} className="kanban-filter-row" onClick={() => toggleFilter(l.id)}>
+ <button key={key} className="kanban-filter-row" onClick={() => toggleFilter(key)}>
<span className="kanban-label-chip" style={{ background: s.bg, color: s.fg }}>
{l.name || 'Label'}
</span>
@@ -310,6 +441,20 @@ export const KanbanView = memo(function KanbanView({
</button>
)
})}
+ {githubLabels.length > 0 && <div className="kanban-filter-group">GitHub</div>}
+ {githubLabels.map((label) => {
+ const key = `github:${label.name.normalize('NFKC').toLocaleLowerCase('en-US')}`
+ const on = activeFilter.includes(key)
+ return (
+ <button key={key} className="kanban-filter-row" onClick={() => toggleFilter(key)}>
+ <span className="github-issue-label" style={{
+ borderColor: `#${label.color}`,
+ color: `#${label.color}`
+ }}>{label.name}</span>
+ {on && <span className="label-picker__rowcheck">✓</span>}
+ </button>
+ )
+ })}
{activeFilter.length > 0 && (
<button className="kanban-filter-clear" onClick={() => setLabelFilter([])}>
Clear filter
@@ -322,47 +467,73 @@ export const KanbanView = memo(function KanbanView({
)}
</div>
<div className="kanban-board">
- <KanbanColumn
- column={null}
- cards={columnCards.ungrouped}
- metaOf={metaOf}
- labelsOf={labelsOf}
- onOpenCard={setModalNodeId}
- createOptions={createOptions}
- onCreate={onCreateNode}
- onCardDragStart={handleCardDragStart}
- onDragEnd={handleDragEnd}
- onDropOnColumn={dropOnColumn}
- onDropAtCard={dropAtCard}
- onCardContext={handleCardContext}
- />
- {board.columns.map((col) => (
+ <div className="kanban-board__columns">
<KanbanColumn
- key={col.id}
- column={col}
- cards={columnCards.byColumn.get(col.id) ?? NO_CARDS}
+ column={null}
+ cards={sessionVisible ? columnCards.ungrouped : NO_CARDS}
+ githubCards={githubVisible ? githubPage(null)?.items ?? [] : []}
+ githubColumns={board.columns}
+ githubMoving={github?.moving}
+ githubReadOnly={githubReadOnly}
+ githubStatus={github?.issueStatus}
+ displayCount={(sessionVisible ? columnCards.ungrouped.length : 0) +
+ (githubVisible ? githubPage(null)?.counts.ungrouped ?? 0 : 0)}
metaOf={metaOf}
labelsOf={labelsOf}
- onRename={handleRenameColumn}
- onRecolor={handleRecolorColumn}
- onDelete={handleDeleteColumn}
onOpenCard={setModalNodeId}
createOptions={createOptions}
onCreate={onCreateNode}
onCardDragStart={handleCardDragStart}
- onColumnDragStart={handleColumnDragStart}
onDragEnd={handleDragEnd}
onDropOnColumn={dropOnColumn}
onDropAtCard={dropAtCard}
onCardContext={handleCardContext}
+ onOpenGitHub={setModalIssue}
+ onMoveGitHub={handleMoveGitHub}
+ onGitHubDragStart={handleGitHubDragStart}
+ hasMoreGitHub={githubVisible && !!githubPage(null)?.nextCursor}
+ onLoadMoreGitHub={() => void loadMoreGitHub(api.githubIssues, projectId, null)}
/>
- ))}
- <button
- className="kanban-add-col"
- onClick={() => commit(addColumn(board, 'New column', nextColumnColor(board)))}
- >
- + Add column
- </button>
+ {board.columns.map((col) => (
+ <KanbanColumn
+ key={col.id}
+ column={col}
+ cards={sessionVisible ? columnCards.byColumn.get(col.id) ?? NO_CARDS : NO_CARDS}
+ githubCards={githubVisible ? githubPage(col.id)?.items ?? [] : []}
+ githubColumns={board.columns}
+ githubMoving={github?.moving}
+ githubReadOnly={githubReadOnly}
+ githubStatus={github?.issueStatus}
+ displayCount={(sessionVisible ? columnCards.byColumn.get(col.id)?.length ?? 0 : 0) +
+ (githubVisible ? githubPage(col.id)?.counts[col.id] ?? 0 : 0)}
+ metaOf={metaOf}
+ labelsOf={labelsOf}
+ onRename={handleRenameColumn}
+ onRecolor={handleRecolorColumn}
+ onDelete={handleDeleteColumn}
+ onOpenCard={setModalNodeId}
+ createOptions={createOptions}
+ onCreate={onCreateNode}
+ onCardDragStart={handleCardDragStart}
+ onColumnDragStart={handleColumnDragStart}
+ onDragEnd={handleDragEnd}
+ onDropOnColumn={dropOnColumn}
+ onDropAtCard={dropAtCard}
+ onCardContext={handleCardContext}
+ onOpenGitHub={setModalIssue}
+ onMoveGitHub={handleMoveGitHub}
+ onGitHubDragStart={handleGitHubDragStart}
+ hasMoreGitHub={githubVisible && !!githubPage(col.id)?.nextCursor}
+ onLoadMoreGitHub={() => void loadMoreGitHub(api.githubIssues, projectId, col.id)}
+ />
+ ))}
+ <button
+ className="kanban-add-col"
+ onClick={() => commit(addColumn(board, 'New column', nextColumnColor(board)))}
+ >
+ + Add column
+ </button>
+ </div>
</div>
{cardMenu && byId.has(cardMenu.nodeId) && (
<ContextMenu
@@ -389,6 +560,32 @@ export const KanbanView = memo(function KanbanView({
onBrowserNav={(patch) => onBrowserNav(modalNodeId, patch)}
/>
)}
+ {modalIssue && (
+ <GitHubIssueSummaryModal
+ issue={modalIssue}
+ columns={board.columns}
+ moving={!!github?.moving[modalIssue.number]}
+ readOnly={githubReadOnly}
+ status={github?.issueStatus[modalIssue.number]}
+ onMove={(columnId) => handleMoveGitHub(modalIssue, columnId)}
+ onClose={() => setModalIssue(null)}
+ />
+ )}
+ {pendingGitHubMove && (
+ <ConfirmDialog
+ message={pendingGitHubMove.confirmation.message}
+ confirmLabel={pendingGitHubMove.confirmation.confirmLabel}
+ danger={pendingGitHubMove.confirmation.danger}
+ onCancel={() => setPendingGitHubMove(null)}
+ onConfirm={() => {
+ const { issue, columnId } = pendingGitHubMove
+ setPendingGitHubMove(null)
+ void moveGitHubState(
+ api.githubIssues, projectId, issue.number, columnId, issue.updatedAt
+ )
+ }}
+ />
+ )}
</div>
)
})
diff --git a/src/renderer/components/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsx
index c39668ff9..4281c0632 100644
--- a/src/renderer/components/settings/SettingsIcons.tsx
+++ b/src/renderer/components/settings/SettingsIcons.tsx
@@ -81,6 +81,11 @@ const PATHS: Record<SettingsSectionId, React.JSX.Element> = {
<path d="M8 3v10" />
</>
),
+ 'github-issues': (
+ <>
+ <path d="M8 2.2a5.8 5.8 0 0 0-1.8 11.3c.3.1.4-.1.4-.3v-1.1c-1.7.4-2.1-.7-2.1-.7-.3-.8-.8-1-1-1.1-.7-.4.1-.4.1-.4.8.1 1.2.8 1.2.8.7 1.2 1.8.8 2.2.6.1-.5.3-.8.5-1-1.4-.2-2.8-.7-2.8-3a2.4 2.4 0 0 1 .6-1.6 2.2 2.2 0 0 1 .1-1.6s.5-.2 1.7.6a5.7 5.7 0 0 1 3.1 0c1.2-.8 1.7-.6 1.7-.6a2.2 2.2 0 0 1 .1 1.6 2.4 2.4 0 0 1 .6 1.6c0 2.3-1.4 2.8-2.8 3 .2.2.4.6.4 1.2v1.7c0 .2.1.4.4.3A5.8 5.8 0 0 0 8 2.2Z" />
+ </>
+ ),
license: (
<>
<circle cx="5.6" cy="5.6" r="2.6" />
diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsx
index d4cab8865..1167dcbe7 100644
--- a/src/renderer/components/settings/SettingsPage.tsx
+++ b/src/renderer/components/settings/SettingsPage.tsx
@@ -25,6 +25,7 @@ import { TeamAccessSection } from './sections/TeamAccessSection'
import { SshSection } from './sections/SshSection'
import { UpdatesSection } from './sections/UpdatesSection'
import { PrivacySection } from './sections/PrivacySection'
+import { GitHubIssuesSection } from './sections/GitHubIssuesSection'
const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
@@ -83,6 +84,7 @@ export function SettingsPage({
<NotificationsSection isActive={active === 'notifications'} />
<CommitSection isActive={active === 'commit'} />
<TmuxSection isActive={active === 'tmux'} />
+ <GitHubIssuesSection isActive={active === 'github-issues'} />
<LicenseSection isActive={active === 'license'} />
<PresenceIdentitySection isActive={active === 'presence'} />
<RemoteSection isActive={active === 'remote'} onClose={onClose} />
diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.ts
index 737b5246a..ee2544a35 100644
--- a/src/renderer/components/settings/nav.test.ts
+++ b/src/renderer/components/settings/nav.test.ts
@@ -2,10 +2,10 @@ import { describe, it, expect } from 'vitest'
import { SETTINGS_GROUPS, allSectionIds, FIRST_SECTION_ID, visibleSettingsGroups } from './nav'
describe('SETTINGS_GROUPS', () => {
- it('lists exactly 21 sections with no duplicates', () => {
+ it('lists exactly 22 sections with no duplicates', () => {
const ids = allSectionIds()
- expect(ids).toHaveLength(21)
- expect(new Set(ids).size).toBe(21)
+ expect(ids).toHaveLength(22)
+ expect(new Set(ids).size).toBe(22)
})
it('starts at a section that exists in the groups', () => {
expect(allSectionIds()).toContain(FIRST_SECTION_ID)
@@ -13,7 +13,7 @@ describe('SETTINGS_GROUPS', () => {
it('hides mac-only sections off macOS, keeps them on', () => {
const off = visibleSettingsGroups(false).flatMap((g) => g.sections.map((s) => s.id))
expect(off).not.toContain('notch')
- expect(off).toHaveLength(20)
+ expect(off).toHaveLength(21)
expect(visibleSettingsGroups(true)).toEqual(SETTINGS_GROUPS)
// No group is left empty by the filter.
expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)
diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.ts
index b71d26929..8591a6a1c 100644
--- a/src/renderer/components/settings/nav.ts
+++ b/src/renderer/components/settings/nav.ts
@@ -13,6 +13,7 @@ export type SettingsSectionId =
| 'notifications'
| 'commit'
| 'tmux'
+ | 'github-issues'
| 'license'
| 'presence'
| 'remote'
@@ -55,6 +56,7 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [
{ id: 'terminal', title: 'Terminal' },
{ id: 'shell', title: 'Shell' },
{ id: 'tmux', title: 'tmux' },
+ { id: 'github-issues', title: 'GitHub Issues' },
{ id: 'behavior', title: 'Behavior' }
]
},
diff --git a/src/renderer/components/settings/sections/GitHubIssuesSection.test.tsx b/src/renderer/components/settings/sections/GitHubIssuesSection.test.tsx
new file mode 100644
index 000000000..eb6d25867
--- /dev/null
+++ b/src/renderer/components/settings/sections/GitHubIssuesSection.test.tsx
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useProjects } from '../../../state/projects'
+import { GitHubIssuesSection } from './GitHubIssuesSection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+describe('GitHubIssuesSection', () => {
+ let root: Root
+ let host: HTMLElement
+ let saveToken: ReturnType<typeof vi.fn>
+
+ beforeEach(async () => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ saveToken = vi.fn(async () => ({
+ control: { revision: 0, authProvider: 'auto' },
+ auth: {
+ selectedProvider: 'auto', activeProvider: 'token', ghAuthenticated: false,
+ tokenPresent: true, storage: 'encrypted', login: 'octocat'
+ }
+ }))
+ ;(window as unknown as { nodeTerminal: any }).nodeTerminal = {
+ githubControl: {
+ status: vi.fn(async () => ({
+ control: { revision: 0, authProvider: 'auto' },
+ auth: {
+ selectedProvider: 'auto', activeProvider: 'token', ghAuthenticated: false,
+ tokenPresent: true, storage: 'encrypted', login: 'octocat'
+ },
+ project: {
+ projectId: 'p1', repository: 'owner/repo', detectedRepository: 'owner/repo',
+ approved: false
+ }
+ })),
+ approve: vi.fn(),
+ revoke: vi.fn(),
+ selectProvider: vi.fn(),
+ saveToken,
+ clearToken: vi.fn()
+ },
+ githubIssues: {
+ createMissingLabels: vi.fn(), refresh: vi.fn(), clearCache: vi.fn()
+ }
+ }
+ useProjects.setState({
+ activeProjectId: 'p1',
+ projects: [{
+ id: 'p1', name: 'Project', color: '#8b5cf6', viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [], cwd: '/repo',
+ kanban: {
+ columns: [
+ { id: 'todo', title: 'Todo', color: '#2563eb' },
+ { id: 'done', title: 'Done', color: '#16a34a' }
+ ],
+ assignments: [],
+ github: {
+ columnMappings: [
+ { columnId: 'todo', label: 'status:todo' },
+ { columnId: 'done', label: 'status:done' }
+ ],
+ completionColumnId: 'done'
+ }
+ }
+ }]
+ })
+ root = createRoot(host)
+ await act(async () => {
+ root.render(<GitHubIssuesSection isActive />)
+ })
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ })
+
+ it('clears the write-only token field after Save and never renders the stored token', async () => {
+ const input = host.querySelector<HTMLInputElement>('#github-personal-access-token')!
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
+ setter.call(input, 'github_pat_secret')
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ const save = [...host.querySelectorAll('button')].find((button) => button.textContent === 'Save token')!
+ await act(async () => { save.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ expect(saveToken).toHaveBeenCalledWith('github_pat_secret')
+ expect(input.value).toBe('')
+ expect(host.textContent).not.toContain('github_pat_secret')
+ })
+
+ it('updates exact label mappings in the shared project board', async () => {
+ const input = host.querySelector<HTMLInputElement>('#github-label-todo')!
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
+ setter.call(input, 'workflow:ready')
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ expect(useProjects.getState().getProject('p1')?.kanban?.github?.columnMappings)
+ .toContainEqual({ columnId: 'todo', label: 'workflow:ready' })
+ })
+})
diff --git a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
new file mode 100644
index 000000000..0fe4cb161
--- /dev/null
+++ b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
@@ -0,0 +1,454 @@
+import { useEffect, useMemo, useState } from 'react'
+import type {
+ GitHubAuthProvider,
+ GitHubControlView,
+ ProjectKanbanGitHub
+} from '@shared/github-issues'
+import { useProjects } from '../../../state/projects'
+import { SettingsSection } from '../SettingsSection'
+import { SearchableRow } from '../SearchableRow'
+import { FieldRow } from '../FieldRow'
+import { ConfirmDialog } from '../../ConfirmDialog'
+import { Button } from '@renderer/ui/Button'
+import { Input } from '@renderer/ui/Input'
+import { Select } from '@renderer/ui/Select'
+import { Switch } from '@renderer/ui/Switch'
+
+const ROWS = {
+ enable: {
+ title: 'GitHub Issues',
+ description: 'Show repository issues on this project Kanban board.',
+ keywords: ['github', 'issues', 'kanban', 'sync', 'repository']
+ },
+ repository: {
+ title: 'Repository',
+ keywords: ['github', 'origin', 'owner', 'repository', 'override']
+ },
+ authentication: {
+ title: 'Authentication',
+ keywords: ['github', 'token', 'personal access token', 'cli', 'authentication']
+ },
+ mapping: {
+ title: 'Column labels',
+ keywords: ['github', 'labels', 'columns', 'mapping', 'workflow', 'completion']
+ },
+ data: {
+ title: 'Sync and local data',
+ keywords: ['github', 'refresh', 'cache', 'revoke', 'labels']
+ }
+}
+const ENTRIES = Object.values(ROWS)
+
+type Confirmation = 'labels' | 'cache' | 'revoke' | null
+
+function defaultGitHub(columns: Array<{ id: string; title: string }>): ProjectKanbanGitHub {
+ return {
+ columnMappings: columns.map((column) => ({
+ columnId: column.id,
+ label: `status:${column.title.trim().toLocaleLowerCase('en-US').replace(/\s+/g, '-')}`
+ })),
+ ...(columns.length ? { completionColumnId: columns[columns.length - 1].id } : {})
+ }
+}
+
+function messageFor(error: unknown): string {
+ const code = error && typeof error === 'object' && 'code' in error
+ ? String((error as { code: unknown }).code)
+ : error instanceof Error ? error.message : ''
+ if (code.includes('revision-conflict')) return 'Settings changed elsewhere. The latest state has been loaded.'
+ if (code.includes('invalid-token')) return 'GitHub could not validate that token.'
+ if (code.includes('not-authenticated')) return 'Sign in with GitHub CLI or save a valid token first.'
+ if (code.includes('not-approved')) return 'Approve this repository on this machine first.'
+ return 'The GitHub action could not be completed. Please try again.'
+}
+
+export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.JSX.Element {
+ const projectId = useProjects((state) => state.activeProjectId)
+ const project = useProjects((state) => state.projects.find((item) => item.id === state.activeProjectId))
+ const setProjectKanban = useProjects((state) => state.setProjectKanban)
+ const board = project?.kanban
+ const githubConfig = board?.github
+ const [view, setView] = useState<GitHubControlView | null>(null)
+ const [token, setToken] = useState('')
+ const [repositoryDraft, setRepositoryDraft] = useState('')
+ const [busy, setBusy] = useState('')
+ const [notice, setNotice] = useState('')
+ const [confirmation, setConfirmation] = useState<Confirmation>(null)
+
+ const refreshStatus = async (): Promise<void> => {
+ if (!projectId) return
+ const next = await window.nodeTerminal.githubControl.status(projectId)
+ setView(next)
+ }
+
+ useEffect(() => {
+ if (!isActive || !projectId || project?.remote) return
+ let live = true
+ void window.nodeTerminal.githubControl.status(projectId)
+ .then((next) => { if (live) setView(next) })
+ .catch((error) => { if (live) setNotice(messageFor(error)) })
+ return () => { live = false }
+ }, [isActive, projectId, project?.remote])
+
+ useEffect(() => {
+ setRepositoryDraft(githubConfig?.repository ?? '')
+ }, [projectId, githubConfig?.repository])
+
+ const updateConfig = (next: ProjectKanbanGitHub | undefined): void => {
+ if (!board || !projectId) return
+ const updated = { ...board }
+ if (next) updated.github = next
+ else delete updated.github
+ setProjectKanban(projectId, updated)
+ setNotice('')
+ }
+
+ const run = async (name: string, action: () => Promise<void>, success: string): Promise<void> => {
+ setBusy(name)
+ setNotice('')
+ try {
+ await action()
+ await refreshStatus()
+ setNotice(success)
+ } catch (error) {
+ setNotice(messageFor(error))
+ try { await refreshStatus() } catch { /* keep the actionable error */ }
+ } finally {
+ setBusy('')
+ }
+ }
+
+ const mappings = useMemo(
+ () => new Map(githubConfig?.columnMappings.map((item) => [item.columnId, item.label]) ?? []),
+ [githubConfig?.columnMappings]
+ )
+
+ if (!projectId || !project) {
+ return (
+ <SettingsSection id="github-issues" title="GitHub Issues" isActive={isActive} searchEntries={ENTRIES}>
+ <p className="text-sm text-muted">Open a project to configure GitHub Issues.</p>
+ </SettingsSection>
+ )
+ }
+
+ if (project.remote) {
+ return (
+ <SettingsSection id="github-issues" title="GitHub Issues" isActive={isActive} searchEntries={ENTRIES}>
+ <p className="text-sm text-muted">Configure GitHub Issues on the computer hosting this project.</p>
+ </SettingsSection>
+ )
+ }
+
+ if (!board) {
+ return (
+ <SettingsSection id="github-issues" title="GitHub Issues" isActive={isActive} searchEntries={ENTRIES}>
+ <p className="text-sm text-muted">Create this project’s Kanban board before enabling GitHub Issues.</p>
+ </SettingsSection>
+ )
+ }
+
+ const enabled = !!githubConfig
+ const repository = githubConfig?.repository ?? view?.project?.detectedRepository
+ const approved = enabled && !!view?.project?.approved
+ const authenticated = !!view?.auth.activeProvider
+ const completionReady = !!githubConfig?.completionColumnId &&
+ mappings.has(githubConfig.completionColumnId)
+ const ready = approved && authenticated && completionReady
+
+ return (
+ <SettingsSection
+ id="github-issues"
+ title="GitHub Issues"
+ description="Show this project’s GitHub issues alongside sessions and keep column movement in sync with exact issue labels."
+ isActive={isActive}
+ searchEntries={ENTRIES}
+ >
+ <SearchableRow {...ROWS.enable}>
+ <FieldRow
+ label="Include GitHub issues"
+ description="GitHub remains the source of truth. Issues are cached privately on this computer and are not copied into the project file."
+ control={
+ <Switch
+ checked={enabled}
+ ariaLabel="Include GitHub issues"
+ onChange={(on) => updateConfig(on ? defaultGitHub(board.columns) : undefined)}
+ />
+ }
+ />
+ </SearchableRow>
+
+ {enabled && (
+ <>
+ <SearchableRow {...ROWS.repository}>
+ <div className="space-y-3">
+ <FieldRow
+ label="Repository"
+ description={view?.project?.detectedRepository
+ ? `Detected from origin as ${view.project.detectedRepository}. Leave the override empty to use it.`
+ : 'Enter the GitHub repository as owner/repository.'}
+ control={
+ <div className="flex items-center gap-2">
+ <Input
+ id="github-repository"
+ className="w-56"
+ value={repositoryDraft}
+ placeholder={view?.project?.detectedRepository ?? 'owner/repository'}
+ onChange={(event) => setRepositoryDraft(event.target.value)}
+ />
+ <Button
+ disabled={busy !== ''}
+ onClick={() => {
+ updateConfig({
+ ...githubConfig,
+ ...(repositoryDraft.trim() ? { repository: repositoryDraft.trim() } : {})
+ })
+ if (!repositoryDraft.trim()) {
+ const next = { ...githubConfig }
+ delete next.repository
+ updateConfig(next)
+ }
+ void refreshStatus()
+ }}
+ >
+ Apply
+ </Button>
+ </div>
+ }
+ />
+ <div className="flex items-center gap-2 text-[13px]">
+ <span className={`size-2 rounded-full ${ready ? 'bg-green-500' : 'bg-amber-500'}`} />
+ <span className="text-muted">
+ {ready
+ ? `Ready as ${view?.auth.login ?? 'GitHub user'}`
+ : view?.project?.approved
+ ? 'Repository approved. Authentication is still needed.'
+ : 'Approval is required before nodeterm reads the repository.'}
+ </span>
+ {!view?.project?.approved && repository && (
+ <Button
+ variant="primary"
+ disabled={busy !== ''}
+ onClick={() => void run('approve', async () => {
+ const status = await window.nodeTerminal.githubControl.status(projectId)
+ await window.nodeTerminal.githubControl.approve({
+ projectId,
+ repository,
+ expectedRevision: status.control.revision
+ })
+ }, 'Repository approved on this machine.')}
+ >
+ Approve this machine
+ </Button>
+ )}
+ </div>
+ </div>
+ </SearchableRow>
+
+ <SearchableRow {...ROWS.authentication}>
+ <div className="space-y-4">
+ <FieldRow
+ label="Authentication"
+ description="Auto prefers an authenticated GitHub CLI and otherwise uses the saved token."
+ control={
+ <Select
+ id="github-auth-provider"
+ value={view?.control.authProvider ?? 'auto'}
+ disabled={!view || busy !== ''}
+ onChange={(event) => void run('provider', async () => {
+ const current = await window.nodeTerminal.githubControl.status(projectId)
+ await window.nodeTerminal.githubControl.selectProvider({
+ provider: event.target.value as GitHubAuthProvider,
+ expectedRevision: current.control.revision
+ })
+ }, 'Authentication preference updated.')}
+ >
+ <option value="auto">Auto</option>
+ <option value="gh">GitHub CLI only</option>
+ <option value="token">Personal access token only</option>
+ </Select>
+ }
+ />
+ <FieldRow
+ label="Personal access token"
+ description="Use a fine-grained token with repository metadata read access and issues read and write access. The token is write only in this screen."
+ note={view?.auth.storage === 'restricted-file'
+ ? 'Encrypted key storage is unavailable. The token is protected in a mode 0600 local file.'
+ : undefined}
+ htmlFor="github-personal-access-token"
+ control={
+ <div className="flex items-center gap-2">
+ <Input
+ id="github-personal-access-token"
+ type="password"
+ autoComplete="off"
+ className="w-56"
+ value={token}
+ placeholder={view?.auth.tokenPresent ? 'Token saved' : 'github_pat_…'}
+ onChange={(event) => setToken(event.target.value)}
+ />
+ <Button
+ disabled={!token || busy !== ''}
+ onClick={() => void run('token', async () => {
+ await window.nodeTerminal.githubControl.saveToken(token)
+ setToken('')
+ }, 'Token saved securely.')}
+ >
+ Save token
+ </Button>
+ {view?.auth.tokenPresent && (
+ <Button
+ disabled={busy !== ''}
+ onClick={() => void run('clear-token', async () => {
+ await window.nodeTerminal.githubControl.clearToken()
+ setToken('')
+ }, 'Saved token cleared.')}
+ >
+ Clear
+ </Button>
+ )}
+ </div>
+ }
+ />
+ <p className="text-[13px] text-muted">
+ GitHub CLI {view?.auth.ghAuthenticated ? 'is signed in' : 'is not signed in'}.
+ </p>
+ </div>
+ </SearchableRow>
+
+ <SearchableRow {...ROWS.mapping}>
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-sm font-medium text-text">Column labels</h3>
+ <p className="mt-1 text-[13px] leading-relaxed text-muted">
+ Each issue must have exactly one of these labels. Matching is case insensitive and labels are written with the exact spelling below.
+ </p>
+ </div>
+ {board.columns.map((column) => (
+ <FieldRow
+ key={column.id}
+ label={column.title}
+ htmlFor={`github-label-${column.id}`}
+ control={
+ <Input
+ id={`github-label-${column.id}`}
+ className="w-56"
+ value={mappings.get(column.id) ?? ''}
+ maxLength={50}
+ placeholder={`status:${column.title.toLocaleLowerCase('en-US')}`}
+ onChange={(event) => {
+ const label = event.target.value
+ const next = githubConfig.columnMappings
+ .filter((item) => item.columnId !== column.id)
+ if (label) next.push({ columnId: column.id, label })
+ updateConfig({
+ ...githubConfig,
+ columnMappings: board.columns.flatMap((item) =>
+ next.filter((mapping) => mapping.columnId === item.id)),
+ ...(label || githubConfig.completionColumnId !== column.id
+ ? {}
+ : { completionColumnId: undefined })
+ })
+ }}
+ />
+ }
+ />
+ ))}
+ <FieldRow
+ label="Completion column"
+ description="Moving an issue here closes it. Moving a closed issue elsewhere reopens it."
+ control={
+ <Select
+ id="github-completion-column"
+ value={githubConfig.completionColumnId ?? ''}
+ onChange={(event) => updateConfig({
+ ...githubConfig,
+ completionColumnId: event.target.value || undefined
+ })}
+ >
+ <option value="" disabled>Choose a mapped column</option>
+ {board.columns.filter((column) => mappings.has(column.id)).map((column) => (
+ <option key={column.id} value={column.id}>{column.title}</option>
+ ))}
+ </Select>
+ }
+ />
+ </div>
+ </SearchableRow>
+
+ <SearchableRow {...ROWS.data}>
+ <div className="space-y-3">
+ <div className="flex flex-wrap gap-2">
+ <Button disabled={!ready || busy !== ''} onClick={() => setConfirmation('labels')}>
+ Create missing labels
+ </Button>
+ <Button disabled={!approved || !authenticated || busy !== ''} onClick={() => void run('refresh',
+ () => window.nodeTerminal.githubIssues.refresh(projectId, true),
+ 'GitHub issues refreshed.')}>
+ Refresh now
+ </Button>
+ <Button disabled={!enabled || !repository || busy !== ''} onClick={() => setConfirmation('cache')}>
+ Clear cached data
+ </Button>
+ {view?.project?.approved && (
+ <Button disabled={busy !== ''} onClick={() => setConfirmation('revoke')}>
+ Revoke this machine
+ </Button>
+ )}
+ </div>
+ {approved && !completionReady && (
+ <p className="text-[13px] text-warn" role="status">
+ Choose a mapped completion column before GitHub issue changes are enabled.
+ </p>
+ )}
+ {notice && <p role="status" className="text-[13px] text-muted">{notice}</p>}
+ </div>
+ </SearchableRow>
+ </>
+ )}
+
+ {confirmation === 'labels' && (
+ <ConfirmDialog
+ message="Create any mapped labels that do not yet exist in this repository?"
+ confirmLabel="Create labels"
+ danger={false}
+ onCancel={() => setConfirmation(null)}
+ onConfirm={() => {
+ setConfirmation(null)
+ void run('labels', async () => {
+ const result = await window.nodeTerminal.githubIssues.createMissingLabels(projectId)
+ if (result.status !== 'confirmed') throw new Error('configuration-changed')
+ }, 'Mapped labels are ready.')
+ }}
+ />
+ )}
+ {confirmation === 'cache' && (
+ <ConfirmDialog
+ message="Clear the private GitHub issue cache for this repository? It will be rebuilt on the next refresh."
+ confirmLabel="Clear cache"
+ onCancel={() => setConfirmation(null)}
+ onConfirm={() => {
+ setConfirmation(null)
+ void run('cache', () => window.nodeTerminal.githubIssues.clearCache(projectId), 'Cached data cleared.')
+ }}
+ />
+ )}
+ {confirmation === 'revoke' && (
+ <ConfirmDialog
+ message="Stop this computer from reading or changing issues for this project?"
+ confirmLabel="Revoke"
+ onCancel={() => setConfirmation(null)}
+ onConfirm={() => {
+ setConfirmation(null)
+ void run('revoke', async () => {
+ const current = await window.nodeTerminal.githubControl.status(projectId)
+ await window.nodeTerminal.githubControl.revoke({
+ projectId,
+ expectedRevision: current.control.revision
+ })
+ }, 'This machine has been revoked.')
+ }}
+ />
+ )}
+ </SettingsSection>
+ )
+}
diff --git a/src/renderer/lib/githubIssueMove.test.ts b/src/renderer/lib/githubIssueMove.test.ts
new file mode 100644
index 000000000..25ae60e3c
--- /dev/null
+++ b/src/renderer/lib/githubIssueMove.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest'
+import { githubMoveIntent, githubMoveConfirmation } from './githubIssueMove'
+
+const open = { number: 7, title: 'Fix the thing', state: 'open' as const, columnId: 'doing' }
+const closed = { number: 9, title: 'Old wontfix', state: 'closed' as const, columnId: 'done' }
+
+describe('githubMoveIntent', () => {
+ it('is a no-op when the card lands where it already is', () => {
+ expect(githubMoveIntent(closed, 'done', 'done').kind).toBe('noop')
+ })
+
+ it('closes when an open issue reaches the completion column', () => {
+ expect(githubMoveIntent(open, 'done', 'done').kind).toBe('close')
+ })
+
+ it('reopens when a closed issue leaves the completion column', () => {
+ expect(githubMoveIntent(closed, 'todo', 'done').kind).toBe('reopen')
+ })
+
+ it('reopens when a closed issue is dropped on Ungrouped', () => {
+ // The Ungrouped column sits at the far left of the board and is the easiest thing to hit by
+ // accident. Dropping there is a reopen on GitHub, so it must not be treated as a quiet relabel.
+ expect(githubMoveIntent(closed, null, 'done').kind).toBe('reopen')
+ })
+
+ it('is labels-only when neither end is the completion column', () => {
+ expect(githubMoveIntent(open, 'todo', 'done').kind).toBe('labels-only')
+ })
+
+ it('is labels-only when the board has no completion column', () => {
+ expect(githubMoveIntent(open, 'todo', undefined).kind).toBe('labels-only')
+ })
+})
+
+describe('githubMoveConfirmation', () => {
+ it('asks before a close, naming the issue', () => {
+ const confirmation = githubMoveConfirmation(open, 'done', 'done')
+ expect(confirmation?.confirmLabel).toBe('Close issue')
+ expect(confirmation?.message).toContain('#7')
+ expect(confirmation?.message).toContain('Fix the thing')
+ })
+
+ it('asks before a reopen', () => {
+ const confirmation = githubMoveConfirmation(closed, null, 'done')
+ expect(confirmation?.confirmLabel).toBe('Reopen issue')
+ expect(confirmation?.message).toContain('#9')
+ })
+
+ it('does not ask for a move that only rewrites labels', () => {
+ expect(githubMoveConfirmation(open, 'todo', 'done')).toBeNull()
+ })
+
+ it('does not ask for a no-op', () => {
+ expect(githubMoveConfirmation(closed, 'done', 'done')).toBeNull()
+ })
+})
diff --git a/src/renderer/lib/githubIssueMove.ts b/src/renderer/lib/githubIssueMove.ts
new file mode 100644
index 000000000..a5357341c
--- /dev/null
+++ b/src/renderer/lib/githubIssueMove.ts
@@ -0,0 +1,68 @@
+// What a board move actually DOES to a GitHub issue — decided in one pure place so the drop
+// handler, the card's Move selector and the summary modal cannot disagree about it.
+//
+// Moving a card is not a board-local edit: reaching the completion column closes the issue on
+// GitHub and leaving it reopens the issue, which emails every subscriber and writes the issue's
+// public timeline. Neither is undoable from here. Closed issues all map INTO the completion
+// column, so that column fills with historical closed work, and the Ungrouped column — the easiest
+// drop target to hit by accident — counts as "outside completion", i.e. a reopen. A drag is a
+// cheap, easily mis-aimed gesture; the outcome is not. So state-changing moves ask first, and
+// label-only moves stay immediate.
+
+export type GitHubMoveIntentKind = 'noop' | 'labels-only' | 'close' | 'reopen'
+
+export interface GitHubMoveIntent {
+ kind: GitHubMoveIntentKind
+}
+
+export interface GitHubMoveConfirmation {
+ message: string
+ confirmLabel: string
+ danger: boolean
+}
+
+interface MovableIssue {
+ number: number
+ title: string
+ state: 'open' | 'closed'
+ columnId: string | null
+}
+
+export function githubMoveIntent(
+ issue: MovableIssue,
+ toColumnId: string | null,
+ completionColumnId: string | undefined
+): GitHubMoveIntent {
+ if (issue.columnId === toColumnId) return { kind: 'noop' }
+ // With no completion column configured the service refuses writes outright, so nothing here can
+ // change state — every move is a relabel.
+ if (!completionColumnId) return { kind: 'labels-only' }
+ if (toColumnId === completionColumnId && issue.state === 'open') return { kind: 'close' }
+ if (toColumnId !== completionColumnId && issue.state === 'closed') return { kind: 'reopen' }
+ return { kind: 'labels-only' }
+}
+
+/** The dialog to show before the move, or null when the move needs no confirmation. */
+export function githubMoveConfirmation(
+ issue: MovableIssue,
+ toColumnId: string | null,
+ completionColumnId: string | undefined
+): GitHubMoveConfirmation | null {
+ const { kind } = githubMoveIntent(issue, toColumnId, completionColumnId)
+ const name = `#${issue.number} ${issue.title}`
+ if (kind === 'close') {
+ return {
+ message: `Close ${name} on GitHub? Everyone watching the issue is notified.`,
+ confirmLabel: 'Close issue',
+ danger: true
+ }
+ }
+ if (kind === 'reopen') {
+ return {
+ message: `Reopen ${name} on GitHub? Everyone watching the issue is notified.`,
+ confirmLabel: 'Reopen issue',
+ danger: true
+ }
+ }
+ return null
+}
diff --git a/src/renderer/lib/kanban.test.ts b/src/renderer/lib/kanban.test.ts
index 4b9866e6d..4b20edea2 100644
--- a/src/renderer/lib/kanban.test.ts
+++ b/src/renderer/lib/kanban.test.ts
@@ -37,6 +37,17 @@ describe('columns', () => {
expect(k.columns).toHaveLength(3)
expect(k.columns[2].title).toBe('Review')
})
+ it('addColumn suggests a unique GitHub mapping when sync is configured', () => {
+ const configured: ProjectKanban = {
+ ...board(),
+ github: { columnMappings: [{ columnId: 'a', label: 'status:review' }] }
+ }
+ const next = addColumn(configured, 'Review', '#fff')
+ expect(next.github?.columnMappings.at(-1)).toEqual({
+ columnId: next.columns.at(-1)?.id,
+ label: 'status:review-2'
+ })
+ })
it('renameColumn / recolorColumn touch only the target', () => {
const k = recolorColumn(renameColumn(board(), 'b', 'WIP'), 'b', '#fff')
expect(k.columns[1]).toMatchObject({ id: 'b', title: 'WIP', color: '#fff' })
@@ -47,9 +58,17 @@ describe('columns', () => {
expect(moveColumn(board(), 'a', null).columns.map((c) => c.id)).toEqual(['b', 'a'])
})
it('deleteColumn drops the column AND its assignments (cards return to Ungrouped); unknown id no-op', () => {
- const k = deleteColumn(board(), 'a')
+ const configured: ProjectKanban = {
+ ...board(),
+ github: {
+ repository: 'nodeterm/nodeterm',
+ columnMappings: [{ columnId: 'b', label: 'status:doing' }]
+ }
+ }
+ const k = deleteColumn(configured, 'a')
expect(k.columns.map((c) => c.id)).toEqual(['b'])
expect(k.assignments).toEqual([{ nodeId: 'n2', columnId: 'b' }])
+ expect(k.github).toEqual(configured.github)
expect(deleteColumn(board(), 'nope')).toEqual(board())
})
it('deleting every user column is allowed (Ungrouped always remains)', () => {
@@ -57,6 +76,23 @@ describe('columns', () => {
expect(k.columns).toEqual([])
expect(k.assignments).toEqual([])
})
+ it('deleteColumn removes that column from GitHub mappings and clears it as completion', () => {
+ const configured: ProjectKanban = {
+ ...board(),
+ github: {
+ repository: 'nodeterm/nodeterm',
+ columnMappings: [
+ { columnId: 'a', label: 'status:todo' },
+ { columnId: 'b', label: 'status:doing' }
+ ],
+ completionColumnId: 'a'
+ }
+ }
+ expect(deleteColumn(configured, 'a').github).toEqual({
+ repository: 'nodeterm/nodeterm',
+ columnMappings: [{ columnId: 'b', label: 'status:doing' }]
+ })
+ })
})
describe('assignments', () => {
diff --git a/src/renderer/lib/kanban.ts b/src/renderer/lib/kanban.ts
index 1c1015ebf..74e95434c 100644
--- a/src/renderer/lib/kanban.ts
+++ b/src/renderer/lib/kanban.ts
@@ -28,7 +28,25 @@ export function nextColumnColor(k: ProjectKanban): string {
}
export function addColumn(k: ProjectKanban, title: string, color: string): ProjectKanban {
- return { ...k, columns: [...k.columns, { id: kid('kcol'), title, color }] }
+ const column = { id: kid('kcol'), title, color }
+ if (!k.github) return { ...k, columns: [...k.columns, column] }
+ const base = `status:${title.trim().toLocaleLowerCase('en-US')
+ .normalize('NFKC').replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-|-$/g, '') || 'column'}`
+ const used = new Set(k.github.columnMappings.map((mapping) =>
+ mapping.label.normalize('NFKC').toLocaleLowerCase('en-US')))
+ let label = base.slice(0, 50)
+ for (let suffix = 2; used.has(label.toLocaleLowerCase('en-US')); suffix++) {
+ const ending = `-${suffix}`
+ label = `${base.slice(0, 50 - ending.length)}${ending}`
+ }
+ return {
+ ...k,
+ columns: [...k.columns, column],
+ github: {
+ ...k.github,
+ columnMappings: [...k.github.columnMappings, { columnId: column.id, label }]
+ }
+ }
}
export function renameColumn(k: ProjectKanban, columnId: string, title: string): ProjectKanban {
@@ -55,9 +73,20 @@ export function moveColumn(k: ProjectKanban, columnId: string, beforeId: string
* last-column rule (the virtual Ungrouped column always remains). */
export function deleteColumn(k: ProjectKanban, columnId: string): ProjectKanban {
if (!k.columns.some((c) => c.id === columnId)) return k
+ const github = (() => {
+ if (!k.github) return undefined
+ const { completionColumnId, ...rest } = k.github
+ return {
+ ...rest,
+ columnMappings: k.github.columnMappings.filter((mapping) => mapping.columnId !== columnId),
+ ...(completionColumnId && completionColumnId !== columnId ? { completionColumnId } : {})
+ }
+ })()
return {
+ ...k,
columns: k.columns.filter((c) => c.id !== columnId),
- assignments: k.assignments.filter((a) => a.columnId !== columnId)
+ assignments: k.assignments.filter((a) => a.columnId !== columnId),
+ ...(github ? { github } : {})
}
}
diff --git a/src/renderer/state/githubIssues.test.ts b/src/renderer/state/githubIssues.test.ts
new file mode 100644
index 000000000..036f29232
--- /dev/null
+++ b/src/renderer/state/githubIssues.test.ts
@@ -0,0 +1,155 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import type { GitHubIssuesApi } from '@shared/github-issues'
+import { useGitHubIssues } from './githubIssues'
+
+const page = (number: number, columnId: string | null, nextCursor?: string) => ({
+ items: [{
+ id: number, number, title: `Issue ${number}`, body: '', state: 'open' as const,
+ stateReason: null, htmlUrl: `https://github.com/o/r/issues/${number}`,
+ apiUrl: `https://api.github.com/repos/o/r/issues/${number}`, labels: [], assignees: [],
+ createdAt: '2026-08-09T00:00:00Z', updatedAt: '2026-08-09T00:00:00Z', locked: false,
+ columnId, conflict: null
+ }],
+ counts: { [columnId ?? 'ungrouped']: 1 },
+ partial: false,
+ readOnly: false,
+ ...(nextCursor ? { nextCursor } : {})
+})
+
+function api(): GitHubIssuesApi {
+ return {
+ subscribe: vi.fn(async () => page(1, null)),
+ unsubscribe: vi.fn(async () => {}),
+ query: vi.fn(async (request) => page(request.columnId === 'todo' ? 2 : 3, request.columnId)),
+ refresh: vi.fn(async () => {}),
+ moveIssue: vi.fn(async () => ({ status: 'configuration-changed' as const })),
+ createMissingLabels: vi.fn(async () => ({ status: 'confirmed' as const, created: [], remaining: [] })),
+ clearCache: vi.fn(async () => {}),
+ onChanged: vi.fn(() => () => {})
+ }
+}
+
+beforeEach(() => useGitHubIssues.setState({ projects: {} }))
+
+describe('GitHub issue renderer state', () => {
+ it('lets only the newest overlapping connection publish or tear down project state', async () => {
+ const client = api()
+ let resolveFirst!: (value: ReturnType<typeof page>) => void
+ const first = new Promise<ReturnType<typeof page>>((resolve) => { resolveFirst = resolve })
+ vi.mocked(client.subscribe).mockReturnValueOnce(first)
+
+ const oldConnection = useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ const newConnection = useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ expect(client.subscribe).toHaveBeenCalledTimes(1)
+ resolveFirst(page(1, null))
+ const [oldDisconnect, newDisconnect] = await Promise.all([oldConnection, newConnection])
+
+ expect(useGitHubIssues.getState().projects.p1.pages.ungrouped.items[0].number).toBe(3)
+ oldDisconnect()
+ expect(client.unsubscribe).not.toHaveBeenCalled()
+ expect(useGitHubIssues.getState().projects.p1.pages.ungrouped.items[0].number).toBe(3)
+
+ newDisconnect()
+ expect(client.unsubscribe).toHaveBeenCalledTimes(1)
+ expect(useGitHubIssues.getState().projects.p1).toBeUndefined()
+ })
+
+ it('releases the shared host subscription when a replacement connection fails', async () => {
+ const client = api()
+ const oldDisconnect = await useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ vi.mocked(client.query).mockRejectedValueOnce(new Error('replacement failed'))
+
+ const newDisconnect = await useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ oldDisconnect()
+ expect(client.unsubscribe).not.toHaveBeenCalled()
+
+ newDisconnect()
+ expect(client.unsubscribe).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps pending subscriptions separate when the project changes host API', async () => {
+ const oldApi = api()
+ const newApi = api()
+ let resolveOld!: (value: ReturnType<typeof page>) => void
+ vi.mocked(oldApi.subscribe).mockReturnValue(new Promise((resolve) => { resolveOld = resolve }))
+
+ const oldConnection = useGitHubIssues.getState().connect(oldApi, 'p1', ['todo'])
+ const newDisconnect = await useGitHubIssues.getState().connect(newApi, 'p1', ['todo'])
+ expect(oldApi.subscribe).toHaveBeenCalledTimes(1)
+ expect(newApi.subscribe).toHaveBeenCalledTimes(1)
+ resolveOld(page(1, null))
+ const oldDisconnect = await oldConnection
+
+ expect(oldApi.unsubscribe).toHaveBeenCalledTimes(1)
+ expect(useGitHubIssues.getState().projects.p1.pages.ungrouped.items[0].number).toBe(3)
+ oldDisconnect()
+ newDisconnect()
+ expect(newApi.unsubscribe).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps a refresh delta that arrives while initial column queries are pending', async () => {
+ const client = api()
+ let changed!: (changedIssueNumbers: number[]) => void
+ vi.mocked(client.onChanged).mockImplementation((_projectId, callback) => {
+ changed = callback
+ return () => undefined
+ })
+ let resolveInitial!: (value: ReturnType<typeof page>) => void
+ let initialStarted!: () => void
+ const started = new Promise<void>((resolve) => { initialStarted = resolve })
+ vi.mocked(client.query).mockImplementationOnce(async () => {
+ initialStarted()
+ return new Promise((resolve) => { resolveInitial = resolve })
+ }).mockImplementation(async (request) =>
+ page(request.columnId === 'todo' ? 20 : 30, request.columnId))
+
+ const connecting = useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ await started
+ changed([])
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ resolveInitial(page(2, 'todo'))
+ const disconnect = await connecting
+
+ expect(useGitHubIssues.getState().projects.p1.pages.ungrouped.items[0].number).toBe(30)
+ expect(useGitHubIssues.getState().projects.p1.pages.todo.items[0].number).toBe(20)
+ disconnect()
+ })
+
+ it('subscribes once and loads every visible column', async () => {
+ const client = api()
+ const disconnect = await useGitHubIssues.getState().connect(
+ client, 'p1', ['todo', 'done'], ['github:bug']
+ )
+ expect(client.subscribe).toHaveBeenCalledWith('p1')
+ expect(client.query).toHaveBeenCalledTimes(3)
+ expect(client.query).toHaveBeenCalledWith(expect.objectContaining({ labelFilter: ['github:bug'] }))
+ expect(useGitHubIssues.getState().projects.p1.pages.todo.items[0].number).toBe(2)
+ disconnect()
+ expect(client.unsubscribe).toHaveBeenCalledWith('p1')
+ })
+
+ it('marks only the issue being moved and exposes an actionable non-confirmed status', async () => {
+ const client = api()
+ const disconnect = await useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ let resolveMove!: (value: { status: 'configuration-changed' }) => void
+ vi.mocked(client.moveIssue).mockReturnValue(new Promise((resolve) => { resolveMove = resolve }))
+ const moving = useGitHubIssues.getState().move(client, 'p1', 2, 'done', '2026-08-09T00:00:00Z')
+ expect(useGitHubIssues.getState().projects.p1.moving[2]).toBe(true)
+ resolveMove({ status: 'configuration-changed' })
+ await moving
+ expect(useGitHubIssues.getState().projects.p1.moving[2]).toBeUndefined()
+ expect(useGitHubIssues.getState().projects.p1.issueStatus[2]).toContain('settings changed')
+ disconnect()
+ })
+
+ it('catches a failed move so fire-and-forget UI calls do not reject', async () => {
+ const client = api()
+ const disconnect = await useGitHubIssues.getState().connect(client, 'p1', ['todo'])
+ vi.mocked(client.moveIssue).mockRejectedValue(new Error('network down'))
+ await expect(useGitHubIssues.getState().move(
+ client, 'p1', 2, 'done', '2026-08-09T00:00:00Z'
+ )).resolves.toEqual({ status: 'failed', message: 'network down' })
+ expect(useGitHubIssues.getState().projects.p1.issueStatus[2]).toContain('network down')
+ disconnect()
+ })
+})
diff --git a/src/renderer/state/githubIssues.ts b/src/renderer/state/githubIssues.ts
new file mode 100644
index 000000000..d39715608
--- /dev/null
+++ b/src/renderer/state/githubIssues.ts
@@ -0,0 +1,322 @@
+import { create } from 'zustand'
+import type {
+ GitHubIssuePage,
+ GitHubIssuesApi,
+ GitHubMutationResult
+} from '@shared/github-issues'
+
+export interface GitHubProjectPages {
+ pages: Record<string, GitHubIssuePage>
+ columns: string[]
+ moving: Record<number, true>
+ loading: boolean
+ error?: string
+ labelFilter: string[]
+ issueStatus: Record<number, string>
+ generation: number
+ loadGeneration: number
+}
+
+interface GitHubIssuesState {
+ projects: Record<string, GitHubProjectPages>
+ connect(api: GitHubIssuesApi, projectId: string, columns: string[], labelFilter?: string[]): Promise<() => void>
+ reload(api: GitHubIssuesApi, projectId: string): Promise<void>
+ loadMore(api: GitHubIssuesApi, projectId: string, columnId: string | null): Promise<void>
+ move(
+ api: GitHubIssuesApi,
+ projectId: string,
+ issueNumber: number,
+ toColumnId: string | null,
+ expectedUpdatedAt: string
+ ): Promise<GitHubMutationResult>
+}
+
+const keyFor = (columnId: string | null): string => columnId ?? 'ungrouped'
+let nextConnectionGeneration = 0
+
+type HostSubscription = {
+ api: GitHubIssuesApi
+ refs: number
+ subscribed: boolean
+ pending?: Promise<void>
+}
+
+const hostSubscriptions = new WeakMap<GitHubIssuesApi, Map<string, HostSubscription>>()
+
+function subscriptionsFor(api: GitHubIssuesApi): Map<string, HostSubscription> {
+ let subscriptions = hostSubscriptions.get(api)
+ if (!subscriptions) {
+ subscriptions = new Map()
+ hostSubscriptions.set(api, subscriptions)
+ }
+ return subscriptions
+}
+
+async function acquireHostSubscription(api: GitHubIssuesApi, projectId: string): Promise<() => void> {
+ const subscriptions = subscriptionsFor(api)
+ let record = subscriptions.get(projectId)
+ if (!record) {
+ record = { api, refs: 0, subscribed: false }
+ subscriptions.set(projectId, record)
+ }
+ record.refs += 1
+ try {
+ if (!record.subscribed) {
+ if (!record.pending) {
+ const current = record
+ current.pending = current.api.subscribe(projectId).then(() => {
+ current.subscribed = true
+ }).finally(() => {
+ delete current.pending
+ })
+ }
+ await record.pending
+ }
+ } catch (error) {
+ record.refs -= 1
+ if (record.refs === 0 && subscriptions.get(projectId) === record) {
+ subscriptions.delete(projectId)
+ }
+ throw error
+ }
+ let released = false
+ return () => {
+ if (released) return
+ released = true
+ record!.refs -= 1
+ if (record!.refs !== 0 || subscriptions.get(projectId) !== record) return
+ subscriptions.delete(projectId)
+ if (record!.subscribed) void record!.api.unsubscribe(projectId)
+ }
+}
+
+export const useGitHubIssues = create<GitHubIssuesState>((set, get) => ({
+ projects: {},
+
+ async connect(api, projectId, columns, labelFilter = []) {
+ const generation = ++nextConnectionGeneration
+ const ownsConnection = (): boolean =>
+ get().projects[projectId]?.generation === generation
+ set((state) => ({
+ projects: {
+ ...state.projects,
+ [projectId]: {
+ pages: {}, columns, moving: {}, loading: true, labelFilter, issueStatus: {},
+ generation, loadGeneration: 0
+ }
+ }
+ }))
+ let live = true
+ let releaseHost: (() => void) | undefined
+ const changed = api.onChanged(projectId, () => {
+ if (live && ownsConnection()) void get().reload(api, projectId)
+ })
+ const teardown = (): void => {
+ if (!live) return
+ live = false
+ changed()
+ releaseHost?.()
+ if (!ownsConnection()) return
+ set((state) => {
+ if (state.projects[projectId]?.generation !== generation) return state
+ const projects = { ...state.projects }
+ delete projects[projectId]
+ return { projects }
+ })
+ }
+ try {
+ releaseHost = await acquireHostSubscription(api, projectId)
+ if (!ownsConnection()) {
+ live = false
+ changed()
+ releaseHost()
+ return () => undefined
+ }
+ const loadGeneration = get().projects[projectId]?.loadGeneration ?? 0
+ const columnPages = await Promise.all([null, ...columns].map(async (columnId) => [
+ keyFor(columnId),
+ await api.query({ projectId, columnId, pageSize: 50, labelFilter })
+ ] as const))
+ set((state) => state.projects[projectId]?.generation === generation &&
+ state.projects[projectId]?.loadGeneration === loadGeneration ? ({
+ projects: {
+ ...state.projects,
+ [projectId]: {
+ pages: Object.fromEntries(columnPages),
+ columns,
+ moving: state.projects[projectId]?.moving ?? {},
+ issueStatus: state.projects[projectId]?.issueStatus ?? {},
+ loading: false,
+ labelFilter,
+ generation,
+ loadGeneration
+ }
+ }
+ }) : state)
+ } catch (error) {
+ set((state) => state.projects[projectId]?.generation === generation ? ({
+ projects: {
+ ...state.projects,
+ [projectId]: {
+ pages: {}, columns, moving: {}, loading: false, labelFilter, issueStatus: {},
+ error: error instanceof Error ? error.message : 'GitHub issues are unavailable',
+ generation,
+ loadGeneration: state.projects[projectId]?.loadGeneration ?? 0
+ }
+ }
+ }) : state)
+ }
+ if (!ownsConnection()) {
+ live = false
+ changed()
+ releaseHost?.()
+ return () => undefined
+ }
+ return teardown
+ },
+
+ async reload(api, projectId) {
+ const current = get().projects[projectId]
+ if (!current) return
+ const generation = current.generation
+ const loadGeneration = current.loadGeneration + 1
+ set((state) => {
+ const existing = state.projects[projectId]
+ return existing?.generation === generation ? {
+ projects: {
+ ...state.projects,
+ [projectId]: { ...existing, loadGeneration }
+ }
+ } : state
+ })
+ try {
+ const pages = await Promise.all([null, ...current.columns].map(async (columnId) => [
+ keyFor(columnId),
+ await api.query({ projectId, columnId, pageSize: 50, labelFilter: current.labelFilter })
+ ] as const))
+ set((state) => {
+ const existing = state.projects[projectId]
+ if (existing?.generation !== generation || existing.loadGeneration !== loadGeneration) return state
+ return existing ? {
+ projects: {
+ ...state.projects,
+ [projectId]: { ...existing, pages: Object.fromEntries(pages), loading: false, error: undefined }
+ }
+ } : state
+ })
+ } catch (error) {
+ set((state) => {
+ const existing = state.projects[projectId]
+ if (existing?.generation !== generation || existing.loadGeneration !== loadGeneration) return state
+ return existing ? {
+ projects: {
+ ...state.projects,
+ [projectId]: {
+ ...existing,
+ loading: false,
+ error: error instanceof Error ? error.message : 'GitHub issues are unavailable'
+ }
+ }
+ } : state
+ })
+ }
+ },
+
+ async loadMore(api, projectId, columnId) {
+ const project = get().projects[projectId]
+ const current = project?.pages[keyFor(columnId)]
+ if (!project || !current?.nextCursor) return
+ const generation = project.generation
+ const loadGeneration = project.loadGeneration
+ const next = await api.query({
+ projectId,
+ columnId,
+ pageSize: 50,
+ cursor: current.nextCursor,
+ labelFilter: project.labelFilter
+ })
+ set((state) => {
+ const existing = state.projects[projectId]
+ if (!existing || existing.generation !== generation ||
+ existing.loadGeneration !== loadGeneration) return state
+ return {
+ projects: {
+ ...state.projects,
+ [projectId]: {
+ ...existing,
+ pages: {
+ ...existing.pages,
+ [keyFor(columnId)]: { ...next, items: [...current.items, ...next.items] }
+ }
+ }
+ }
+ }
+ })
+ },
+
+ async move(api, projectId, issueNumber, toColumnId, expectedUpdatedAt) {
+ const generation = get().projects[projectId]?.generation
+ set((state) => {
+ const project = state.projects[projectId]
+ if (!project || project.generation !== generation) return state
+ return {
+ projects: {
+ ...state.projects,
+ [projectId]: { ...project, moving: { ...project.moving, [issueNumber]: true } }
+ }
+ }
+ })
+ try {
+ const result = await api.moveIssue({ projectId, issueNumber, toColumnId, expectedUpdatedAt })
+ const status = result.status === 'confirmed'
+ ? 'Synced with GitHub.'
+ : result.status === 'refresh-pending'
+ ? 'Updated on GitHub. Local refresh is pending.'
+ : result.status === 'stale'
+ ? 'Changed on GitHub. Review the latest issue and retry.'
+ : result.status === 'read-only'
+ ? 'This repository is read only until a complete refresh succeeds.'
+ : result.status === 'invalid-target'
+ ? 'This issue or destination is no longer available.'
+ : result.status === 'configuration-changed'
+ ? 'GitHub settings changed. Refresh and retry.'
+ : result.message
+ set((state) => {
+ const project = state.projects[projectId]
+ if (!project || project.generation !== generation) return state
+ const pages = result.status === 'stale'
+ ? Object.fromEntries(Object.entries(project.pages).map(([key, page]) => [key, {
+ ...page,
+ items: page.items.map((item) => item.number === issueNumber
+ ? { ...item, ...result.issue }
+ : item)
+ }]))
+ : project.pages
+ return { projects: { ...state.projects, [projectId]: {
+ ...project, pages, issueStatus: { ...project.issueStatus, [issueNumber]: status }
+ } } }
+ })
+ if (result.status === 'confirmed' || result.status === 'refresh-pending' || result.status === 'stale') {
+ await get().reload(api, projectId)
+ }
+ return result
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'GitHub sync failed'
+ set((state) => {
+ const project = state.projects[projectId]
+ return project?.generation === generation ? { projects: { ...state.projects, [projectId]: {
+ ...project, issueStatus: { ...project.issueStatus, [issueNumber]: `Sync failed. ${message}` }
+ } } } : state
+ })
+ return { status: 'failed', message }
+ } finally {
+ set((state) => {
+ const project = state.projects[projectId]
+ if (!project || project.generation !== generation) return state
+ const moving = { ...project.moving }
+ delete moving[issueNumber]
+ return { projects: { ...state.projects, [projectId]: { ...project, moving } } }
+ })
+ }
+ }
+}))
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index d22d19920..fb7d56581 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -7027,19 +7027,65 @@ body,
overflow: hidden;
text-overflow: ellipsis;
}
+.kanban-source-filter {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ margin-left: 8px;
+ padding: 2px;
+ border: 1px solid rgba(var(--tint-rgb), 0.1);
+ border-radius: 7px;
+ background: rgba(var(--tint-rgb), 0.04);
+}
+.kanban-source-filter__button {
+ border: 0;
+ border-radius: 5px;
+ background: transparent;
+ color: rgba(var(--tint-rgb), 0.55);
+ padding: 3px 8px;
+ font-size: 11px;
+ cursor: pointer;
+}
+.kanban-source-filter__button:hover {
+ color: var(--text-strong);
+}
+.kanban-source-filter__button.is-active {
+ background: rgba(var(--tint-rgb), 0.1);
+ color: var(--text-strong);
+}
+.kanban-github-status {
+ color: rgba(var(--tint-rgb), 0.5);
+ font-size: 11px;
+}
+.kanban-github-status--error {
+ color: var(--warn);
+}
+.kanban-github-retry {
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+}
+.kanban-github-retry:hover {
+ text-decoration: underline;
+}
.kanban-board {
flex: 1;
overflow-x: auto;
overflow-y: hidden;
- display: flex;
- align-items: flex-start;
- gap: 12px;
- /* Extra bottom room so the columns' cards clear the floating usage pill (bottom-left, z 26)
- — the board's foot mirror of the top title strip. */
+ display: block;
padding: 16px 16px 56px;
height: 100%;
box-sizing: border-box;
}
+.kanban-board__columns {
+ display: flex;
+ align-items: stretch;
+ gap: 12px;
+ width: max-content;
+ min-width: 100%;
+ height: fit-content;
+ max-height: 100%;
+}
.kanban-col {
display: flex;
flex-direction: column;
@@ -7195,6 +7241,208 @@ body,
.kanban-card:hover {
border-color: rgba(var(--tint-rgb), 0.2);
}
+.kanban-card--github {
+ border-left: 2px solid rgba(125, 133, 144, 0.7);
+}
+.github-issue-state {
+ width: 9px;
+ height: 9px;
+ margin-top: 4px;
+ border: 2px solid currentColor;
+ border-radius: 50%;
+ flex: 0 0 auto;
+}
+.github-issue-state--open {
+ color: #3fb950;
+}
+.github-issue-state--closed {
+ color: #a371f7;
+}
+.github-issue-source {
+ flex: 0 0 auto;
+ border: 1px solid rgba(var(--tint-rgb), 0.15);
+ border-radius: 4px;
+ color: rgba(var(--tint-rgb), 0.5);
+ font-size: 8px;
+ font-weight: 800;
+ letter-spacing: 0.04em;
+ padding: 1px 4px;
+}
+.github-issue-card__number {
+ margin: 4px 0 0 17px;
+ color: rgba(var(--tint-rgb), 0.42);
+ font-size: 10px;
+}
+.github-issue-card__labels {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-top: 7px;
+}
+.github-issue-label {
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ border: 1px solid rgba(var(--tint-rgb), 0.18);
+ border-radius: 999px;
+ padding: 1px 6px;
+ font-size: 9px;
+ line-height: 1.4;
+}
+.github-issue-card__footer {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-top: 8px;
+ color: rgba(var(--tint-rgb), 0.45);
+ font-size: 10px;
+}
+.github-issue-conflict {
+ color: var(--warn);
+}
+.github-issue-card__footer .kanban-card__avatars {
+ margin-left: auto;
+}
+.github-issue-card__status {
+ margin-top: 7px;
+ color: rgba(var(--tint-rgb), 0.58);
+ font-size: 10px;
+ line-height: 1.35;
+}
+.github-issue-avatar {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ object-fit: cover;
+ border: 1px solid rgba(var(--tint-rgb), 0.16);
+}
+.github-issue-avatar--initial {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(var(--tint-rgb), 0.15);
+ color: var(--text-strong);
+ font-size: 9px;
+ font-weight: 700;
+}
+.github-issue-move select {
+ max-width: 84px;
+ height: 23px;
+ border: 1px solid rgba(var(--tint-rgb), 0.12);
+ border-radius: 5px;
+ background: var(--surface-deep);
+ color: rgba(var(--tint-rgb), 0.72);
+ font-size: 10px;
+}
+.kanban-github-more {
+ width: 100%;
+ border: 1px dashed rgba(var(--tint-rgb), 0.14);
+ border-radius: 6px;
+ background: transparent;
+ color: rgba(var(--tint-rgb), 0.52);
+ padding: 6px;
+ font-size: 11px;
+ cursor: pointer;
+}
+.kanban-github-more:hover {
+ border-color: var(--accent);
+ color: var(--text-strong);
+}
+.github-issue-modal {
+ width: min(680px, calc(100vw - 32px));
+ max-height: min(720px, calc(100vh - 48px));
+ overflow: auto;
+ border: 1px solid rgba(var(--tint-rgb), 0.14);
+ border-radius: 14px;
+ background: var(--surface-raised);
+ box-shadow: 0 24px 80px rgba(0, 0, 0, calc(0.65 * var(--shadow-k)));
+}
+.github-issue-modal__header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 20px 22px 14px;
+ border-bottom: 1px solid rgba(var(--tint-rgb), 0.08);
+}
+.github-issue-modal__header h2 {
+ margin: 3px 0 0;
+ color: var(--text-strong);
+ font-size: 20px;
+ line-height: 1.3;
+}
+.github-issue-modal__eyebrow {
+ color: rgba(var(--tint-rgb), 0.48);
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+.github-issue-modal__close {
+ border: 0;
+ background: transparent;
+ color: rgba(var(--tint-rgb), 0.55);
+ font-size: 24px;
+ cursor: pointer;
+}
+.github-issue-modal__actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 12px 22px;
+ border-bottom: 1px solid rgba(var(--tint-rgb), 0.08);
+}
+.github-issue-modal__actions label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: rgba(var(--tint-rgb), 0.58);
+ font-size: 12px;
+}
+.github-issue-modal__warning {
+ margin: 14px 22px 0;
+ border: 1px solid color-mix(in srgb, var(--warn) 40%, transparent);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--warn) 9%, transparent);
+ color: var(--warn);
+ padding: 9px 11px;
+ font-size: 12px;
+}
+.github-issue-modal__body {
+ padding: 22px;
+ color: rgba(var(--tint-rgb), 0.78);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ font-size: 13px;
+ line-height: 1.6;
+}
+@media (max-width: 520px) {
+ .kanban-header {
+ gap: 6px;
+ padding-left: 10px;
+ padding-right: 112px;
+ }
+ .kanban-header__name {
+ max-width: 84px;
+ }
+ .kanban-source-filter__button {
+ padding-inline: 6px;
+ }
+ .kanban-board {
+ padding-inline: 10px;
+ }
+ .kanban-col {
+ flex-basis: calc(100vw - 32px);
+ width: calc(100vw - 32px);
+ max-width: calc(100vw - 32px);
+ }
+ .github-issue-modal__actions {
+ align-items: stretch;
+ flex-direction: column;
+ }
+}
.kanban-card__nodedot {
width: 8px;
height: 8px;
@@ -7254,8 +7502,8 @@ body,
background: rgba(var(--tint-rgb), 0.25);
}
.kanban-add-col {
- flex: 0 0 auto;
align-self: flex-start;
+ flex: 0 0 auto;
background: rgba(var(--tint-rgb), 0.04);
border: 1px dashed rgba(var(--tint-rgb), 0.15);
border-radius: 10px;
@@ -8047,6 +8295,14 @@ body,
.kanban-filter-row:hover {
background: rgba(var(--tint-rgb), 0.06);
}
+.kanban-filter-group {
+ padding: 7px 10px 3px;
+ color: rgba(var(--tint-rgb), 0.42);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
.kanban-filter-clear {
margin-top: 4px;
background: none;
diff --git a/src/renderer/styles.kanban.test.ts b/src/renderer/styles.kanban.test.ts
new file mode 100644
index 000000000..d7b79d69f
--- /dev/null
+++ b/src/renderer/styles.kanban.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+const CSS = readFileSync(join(__dirname, 'styles.css'), 'utf8')
+const VIEW = readFileSync(join(__dirname, 'components/kanban/KanbanView.tsx'), 'utf8')
+
+describe('Kanban column row layout', () => {
+ it('stretches empty columns to the height of the tallest column without filling the viewport', () => {
+ expect(VIEW).toContain('className="kanban-board__columns"')
+ expect(CSS).toMatch(
+ /\.kanban-board__columns\s*{[^}]*display:\s*flex;[^}]*align-items:\s*stretch;[^}]*height:\s*fit-content;/s
+ )
+ })
+})
diff --git a/src/server/github-control.test.ts b/src/server/github-control.test.ts
new file mode 100644
index 000000000..4d2f3189a
--- /dev/null
+++ b/src/server/github-control.test.ts
@@ -0,0 +1,67 @@
+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 { IPC } from '../shared/ipc'
+import { ServerPlatform } from './platform-server'
+import { registerServerGitHubControl, ServerGitHubSecretStore } from './github-control'
+
+let userDataDir: string
+
+beforeEach(async () => {
+ userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-server-github-secret-'))
+})
+
+afterEach(async () => {
+ await fs.rm(userDataDir, { recursive: true, force: true })
+})
+
+describe('ServerGitHubSecretStore', () => {
+ it('stores the token atomically at mode 0600 and reports restricted storage', async () => {
+ const store = new ServerGitHubSecretStore(userDataDir)
+ await store.save('github_pat_secret')
+
+ expect(store.availability).toBe('restricted-file')
+ expect(await store.readForHost()).toBe('github_pat_secret')
+ expect((await fs.stat(path.join(userDataDir, 'github-issues-token.json'))).mode & 0o777).toBe(0o600)
+ await expect(fs.access(path.join(userDataDir, 'github-issues-token.json.tmp'))).rejects.toThrow()
+ })
+
+ it('rejects empty or oversized token values without changing the stored token', async () => {
+ const store = new ServerGitHubSecretStore(userDataDir)
+ await store.save('original-token')
+ await expect(store.save('')).rejects.toMatchObject({ code: 'invalid-token' })
+ await expect(store.save('x'.repeat(4097))).rejects.toMatchObject({ code: 'invalid-token' })
+ expect(await store.readForHost()).toBe('original-token')
+ })
+})
+
+describe('registerServerGitHubControl', () => {
+ it('registers control methods on the authenticated server RPC platform', async () => {
+ const platform = new ServerPlatform({ userDataDir, appVersion: '0' })
+ const view = {
+ control: { revision: 0, authProvider: 'auto' as const },
+ auth: {
+ selectedProvider: 'auto' as const,
+ activeProvider: null,
+ ghAuthenticated: false,
+ tokenPresent: false,
+ storage: 'restricted-file' as const
+ }
+ }
+ const controller = {
+ status: vi.fn(async () => view),
+ approve: vi.fn(async () => view),
+ revoke: vi.fn(async () => view),
+ selectProvider: vi.fn(async () => view),
+ saveToken: vi.fn(async () => view),
+ clearToken: vi.fn(async () => view)
+ }
+ registerServerGitHubControl(platform, controller)
+ const response = await platform.dispatch(1, {
+ t: 'req', id: 1, method: IPC.githubControlStatus, args: ['p1']
+ })
+ expect(response).toMatchObject({ ok: true, result: view })
+ expect(controller.status).toHaveBeenCalledWith('p1')
+ })
+})
diff --git a/src/server/github-control.ts b/src/server/github-control.ts
new file mode 100644
index 000000000..f2c350b14
--- /dev/null
+++ b/src/server/github-control.ts
@@ -0,0 +1,73 @@
+import { promises as fs } from 'node:fs'
+import path from 'node:path'
+import type { GitHubSecretStore } from '../core/github/credentials'
+import type { CorePlatform } from '../core/platform'
+import type { GitHubHostController } from '../core/github/host'
+import { IPC } from '../shared/ipc'
+
+const FILE_NAME = 'github-issues-token.json'
+
+export class ServerGitHubSecretError extends Error {
+ constructor(readonly code: 'invalid-token') {
+ super(code)
+ }
+}
+
+function validToken(token: string): boolean {
+ return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)
+}
+
+export class ServerGitHubSecretStore implements GitHubSecretStore {
+ readonly availability = 'restricted-file' as const
+
+ constructor(private readonly userDataDir: string) {}
+
+ private get filePath(): string {
+ return path.join(this.userDataDir, FILE_NAME)
+ }
+
+ async save(token: string): Promise<void> {
+ if (!validToken(token)) throw new ServerGitHubSecretError('invalid-token')
+ await fs.mkdir(this.userDataDir, { recursive: true })
+ const temporary = `${this.filePath}.tmp`
+ await fs.writeFile(temporary, JSON.stringify({ version: 1, token }), {
+ encoding: 'utf-8',
+ mode: 0o600
+ })
+ await fs.chmod(temporary, 0o600)
+ await fs.rename(temporary, this.filePath)
+ await fs.chmod(this.filePath, 0o600)
+ }
+
+ async clear(): Promise<void> {
+ await fs.rm(this.filePath, { force: true })
+ }
+
+ async readForHost(): Promise<string | null> {
+ try {
+ const value: unknown = JSON.parse(await fs.readFile(this.filePath, 'utf-8'))
+ const token = value && typeof value === 'object' &&
+ (value as { version?: unknown }).version === 1
+ ? (value as { token?: unknown }).token
+ : null
+ return typeof token === 'string' && validToken(token) ? token : null
+ } catch {
+ return null
+ }
+ }
+}
+
+type Controller = Pick<GitHubHostController,
+ 'status' | 'approve' | 'revoke' | 'selectProvider' | 'saveToken' | 'clearToken'>
+
+export function registerServerGitHubControl(
+ platform: CorePlatform,
+ controller: Controller
+): void {
+ platform.handle(IPC.githubControlStatus, (projectId?: string) => controller.status(projectId))
+ platform.handle(IPC.githubControlApprove, (input) => controller.approve(input))
+ platform.handle(IPC.githubControlRevoke, (input) => controller.revoke(input))
+ platform.handle(IPC.githubControlSelectProvider, (input) => controller.selectProvider(input))
+ platform.handle(IPC.githubControlSaveToken, (token: string) => controller.saveToken(token))
+ platform.handle(IPC.githubControlClearToken, () => controller.clearToken())
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index 1b4e5f6bb..ed0e77887 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -17,6 +17,9 @@ import { SettingsStore } from '../core/settings-store'
import { WorkspaceStore } from '../core/workspace-store'
import { PtyManager } from '../core/pty-manager'
import { registerCoreHandlers } from './handlers'
+import { registerGitHubIntegration } from '../core/github/integration'
+import { runGitHubCliCommand } from '../core/github/credentials'
+import { registerServerGitHubControl, ServerGitHubSecretStore } from './github-control'
import { DownloadTickets } from '../core/download-tickets'
import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'
import os from 'os'
@@ -215,7 +218,19 @@ export async function startServer(
// between the RPC side (which mints) and the HTTP side (which redeems) — one instance, so a
// ticket minted over the socket is redeemable by the GET that follows it.
const downloadTickets = new DownloadTickets()
- registerCoreHandlers(platform, { getSettings: () => settingsStore.get(), downloadTickets })
+ const { gitService } = registerCoreHandlers(platform, {
+ getSettings: () => settingsStore.get(),
+ downloadTickets
+ })
+ const github = registerGitHubIntegration({
+ platform,
+ userDataDir: config.dataDir,
+ project: (projectId) => workspaceStore.githubProject(projectId),
+ detectRepository: (project) => gitService.originUrl(project.cwd ?? ''),
+ secret: new ServerGitHubSecretStore(config.dataDir),
+ run: runGitHubCliCommand
+ })
+ registerServerGitHubControl(platform, github.controller)
// Board-log: same CorePlatform registrar as desktop, but the Server Edition has no SSH projects
// (terminals are local), so the router only ever resolves a local folder cwd or unsupported —
@@ -427,7 +442,10 @@ export async function startServer(
attachWsServer(server, {
platform,
auth,
- onClientGone: (uiId) => ptyManager.dropClient(uiId),
+ onClientGone: (uiId) => {
+ ptyManager.dropClient(uiId)
+ github.service.dropClient(uiId)
+ },
trustProxy: config.trustProxy
})
diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.ts
new file mode 100644
index 000000000..2b49e7a0e
--- /dev/null
+++ b/src/shared/github-issues.ts
@@ -0,0 +1,202 @@
+export interface ProjectKanbanGitHub {
+ repository?: string
+ columnMappings: Array<{
+ columnId: string
+ label: string
+ }>
+ completionColumnId?: string
+}
+
+export interface NormalisedProjectKanbanGitHub {
+ repository?: string
+ columnMappings: Array<{
+ columnId: string
+ label: string
+ }>
+ completionColumnId?: string
+ revision: string
+}
+
+export type GitHubConfigError =
+ | 'invalid-shape'
+ | 'invalid-repository'
+ | 'unknown-column'
+ | 'duplicate-column'
+ | 'empty-label'
+ | 'label-too-long'
+ | 'duplicate-label'
+ | 'invalid-completion-column'
+
+export type GitHubConfigResult =
+ | { ok: true; value: NormalisedProjectKanbanGitHub }
+ | { ok: false; reason: GitHubConfigError }
+
+export type GitHubAuthProvider = 'auto' | 'gh' | 'token'
+export type GitHubSecretAvailability = 'encrypted' | 'restricted-file' | 'unavailable'
+
+export interface GitHubProjectApproval {
+ localApprovalId: string
+ projectId: string
+ repository: string
+ enabled: true
+ approvedAt: number
+}
+
+export interface GitHubControlState {
+ version: 1
+ revision: number
+ authProvider: GitHubAuthProvider
+ approvals: GitHubProjectApproval[]
+}
+
+export interface GitHubAuthStatus {
+ selectedProvider: GitHubAuthProvider
+ activeProvider: Exclude<GitHubAuthProvider, 'auto'> | null
+ ghAuthenticated: boolean
+ tokenPresent: boolean
+ storage: GitHubSecretAvailability
+ login?: string
+}
+
+export interface GitHubIssueLabel {
+ id: number
+ name: string
+ color: string
+}
+
+export interface GitHubIssueUser {
+ id: number
+ login: string
+ avatarUrl: string
+}
+
+export interface GitHubIssue {
+ id: number
+ number: number
+ title: string
+ body: string
+ state: 'open' | 'closed'
+ stateReason: 'completed' | 'not_planned' | 'reopened' | null
+ htmlUrl: string
+ apiUrl: string
+ labels: GitHubIssueLabel[]
+ assignees: GitHubIssueUser[]
+ createdAt: string
+ updatedAt: string
+ locked: boolean
+}
+
+export interface ListIssueOptions {
+ state: 'open' | 'closed' | 'all'
+ page: number
+ perPage: number
+ since?: string
+ etag?: string
+}
+
+export interface IssuePageResult {
+ items: GitHubIssue[]
+ nextPage?: number
+ etag?: string
+ notModified?: boolean
+}
+
+export interface UpdateIssueInput {
+ state?: 'open' | 'closed'
+ labels?: string[]
+}
+
+export interface GitHubRepositoryLabel extends GitHubIssueLabel {
+ description: string | null
+}
+
+export interface LabelPageResult {
+ items: GitHubRepositoryLabel[]
+ nextPage?: number
+ etag?: string
+ notModified?: boolean
+}
+
+export type GitHubIssueConflict =
+ | 'multiple-mapped-labels'
+ | 'open-with-completion-label'
+ | null
+
+export interface GitHubIssueCardView extends GitHubIssue {
+ columnId: string | null
+ conflict: GitHubIssueConflict
+ avatarDataUrls?: Record<string, string>
+}
+
+export interface GitHubIssueQuery {
+ projectId: string
+ columnId: string | null
+ pageSize: number
+ cursor?: string
+ search?: string
+ labelFilter?: string[]
+}
+
+export interface GitHubIssuePage {
+ items: GitHubIssueCardView[]
+ counts: Record<string, number>
+ nextCursor?: string
+ partial: boolean
+ readOnly: boolean
+ lastSuccessfulRefreshAt?: number
+ lastFullReconciliationAt?: number
+}
+
+export type GitHubMutationResult =
+ | { status: 'confirmed'; issue: GitHubIssue }
+ | { status: 'refresh-pending'; issue: GitHubIssue }
+ | { status: 'stale'; issue: GitHubIssue }
+ | { status: 'configuration-changed' }
+ | { status: 'read-only' }
+ | { status: 'invalid-target' }
+ | { status: 'failed'; message: string }
+
+export interface CreateMappedLabelsResult {
+ status: 'confirmed' | 'configuration-changed' | 'read-only' | 'partial'
+ created: string[]
+ remaining: string[]
+}
+
+export interface GitHubControlView {
+ control: {
+ revision: number
+ authProvider: GitHubAuthProvider
+ }
+ auth: GitHubAuthStatus
+ project?: {
+ projectId: string
+ repository?: string
+ detectedRepository?: string
+ approved: boolean
+ }
+}
+
+export interface GitHubIssuesApi {
+ subscribe(projectId: string): Promise<GitHubIssuePage>
+ unsubscribe(projectId: string): Promise<void>
+ query(request: GitHubIssueQuery): Promise<GitHubIssuePage>
+ refresh(projectId: string, full?: boolean): Promise<void>
+ moveIssue(request: {
+ projectId: string
+ issueNumber: number
+ toColumnId: string | null
+ expectedUpdatedAt: string
+ }): Promise<GitHubMutationResult>
+ createMissingLabels(projectId: string): Promise<CreateMappedLabelsResult>
+ clearCache(projectId: string): Promise<void>
+ onChanged(projectId: string, listener: (changedIssueNumbers: number[]) => void): () => void
+}
+
+export interface GitHubControlApi {
+ status(projectId?: string): Promise<GitHubControlView>
+ approve(input: { projectId: string; repository: string; expectedRevision: number }): Promise<GitHubControlView>
+ revoke(input: { projectId: string; expectedRevision: number }): Promise<GitHubControlView>
+ selectProvider(input: { provider: GitHubAuthProvider; expectedRevision: number }): Promise<GitHubControlView>
+ saveToken(token: string): Promise<GitHubControlView>
+ clearToken(): Promise<GitHubControlView>
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 5d92b3e92..2f0912fec 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -164,6 +164,20 @@ export const IPC = {
// main → renderer events
workspaceMigrated: 'workspace:migrated',
workspaceExternalChange: 'workspace:external-change',
+ githubIssuesSubscribe: 'githubIssues:subscribe',
+ githubIssuesUnsubscribe: 'githubIssues:unsubscribe',
+ githubIssuesQuery: 'githubIssues:query',
+ githubIssuesRefresh: 'githubIssues:refresh',
+ githubIssuesMove: 'githubIssues:move',
+ githubIssuesCreateLabels: 'githubIssues:create-labels',
+ githubIssuesClearCache: 'githubIssues:clear-cache',
+ githubIssuesChanged: (projectId: string) => `githubIssues:changed:${projectId}`,
+ githubControlStatus: 'githubControl:status',
+ githubControlApprove: 'githubControl:approve',
+ githubControlRevoke: 'githubControl:revoke',
+ githubControlSelectProvider: 'githubControl:select-provider',
+ githubControlSaveToken: 'githubControl:save-token',
+ githubControlClearToken: 'githubControl:clear-token',
dialogSelectFolder: 'dialog:select-folder',
dialogSelectFile: 'dialog:select-file',
shellReveal: 'shell:reveal',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 68cd836d2..7f6aabdc0 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -6,6 +6,7 @@ import type { AgentId, AgentPermissionMode, PromptInjectionMode } from './agents
import type { GroupWorktree } from './worktree'
import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from './presence'
import type { WhisperModelInfo } from './speech'
+import type { ProjectKanbanGitHub } from './github-issues'
export interface PtyCreateOptions {
shell?: string
@@ -348,6 +349,8 @@ export interface ProjectKanban {
/** Board-level label palette (Notion-style). Cards reference these by id in `meta[].labels`;
* tolerated as absent/malformed by every reader. */
labels?: KanbanLabel[]
+ /** Shared, non-secret GitHub issue label mapping. Local approval and credentials live elsewhere. */
+ github?: ProjectKanbanGitHub
}
/** Who produced a board-log entry (a teammate on a shared board, or this user). */
@@ -1931,6 +1934,8 @@ export interface NodeTerminalApi {
license: LicenseApi
contextLink: ContextLinkApi
boardLog: BoardLogApi
+ githubIssues: import('./github-issues').GitHubIssuesApi
+ githubControl: import('./github-issues').GitHubControlApi
usage: UsageApi
context: ContextApi
canvas: CanvasApi