P1 — cut showcases:
- Delete gallery.tsx (Primitives) and StatesScreen/Specimen from states.tsx
(keep the reusable EmptyState/OfflineBanner/ModelAwayState).
- Delete placeholder-screen.tsx ('built in a later phase' stub).
- app-shell: drop the states/primitives views, the dev-rail block, the
PHASE/TITLE maps, the INBOX_UNREAD=3 fixture fallback, and the now-dead demo state.
P2 — real connectivity:
- Replace the fake 'toggle the connection (demo)' button with a live status dot
derived from the reconcile: green online, red when serving the stale cache
(gitea unreachable), amber while connecting. OfflineBanner + chat offline now
reflect real state, not a manual toggle.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
388 lines
15 KiB
TypeScript
388 lines
15 KiB
TypeScript
/**
|
|
* Main-process gitea bridge. All gitea traffic runs here — the token never
|
|
* reaches the renderer (which is CSP-locked to 'self' anyway). The renderer
|
|
* calls these over IPC (see preload). Config for the dogfood slice comes from
|
|
* the environment or the repo's .env.local; Settings/Onboarding wire it up
|
|
* properly later.
|
|
*/
|
|
|
|
import { randomUUID } from 'node:crypto'
|
|
import { readFileSync } from 'node:fs'
|
|
import { dirname, join } from 'node:path'
|
|
|
|
import {
|
|
appendDirective,
|
|
createGiteaClient,
|
|
discoverRepos,
|
|
GiteaApiError,
|
|
type DirectiveEntry,
|
|
type GiteaClient,
|
|
type GiteaConfig,
|
|
type GiteaLabel,
|
|
type IssueChange,
|
|
isLabelChange,
|
|
type LifecycleEvent,
|
|
makeDirectiveEntry,
|
|
parseCapacityConfig,
|
|
parseDirectiveLog,
|
|
planIssueChange,
|
|
type ProjectSnapshot,
|
|
type DirectiveInput,
|
|
} from '@commitea/core'
|
|
import { ipcMain } from 'electron'
|
|
|
|
import { type AppConfig, clearConfig, loadConfig, publicConfig, saveConfig } from './config-store.js'
|
|
import { loadSnapshot, saveSnapshot } from './snapshot-store.js'
|
|
|
|
/** Walk up from cwd looking for a .env.local with a GITEA_TOKEN (dev convenience). */
|
|
function loadEnvLocalToken(): string | undefined {
|
|
let dir = process.cwd()
|
|
for (let i = 0; i < 6; i++) {
|
|
try {
|
|
const txt = readFileSync(join(dir, '.env.local'), 'utf8')
|
|
const m = /^GITEA_TOKEN\s*=\s*(.+?)\s*$/m.exec(txt)
|
|
if (m) return m[1].trim()
|
|
} catch {
|
|
// not in this dir — keep walking up
|
|
}
|
|
const parent = dirname(dir)
|
|
if (parent === dir) break
|
|
dir = parent
|
|
}
|
|
return undefined
|
|
}
|
|
|
|
/** Saved config wins (team build); a `.env.local` is the dev fallback; e2e uses fixtures. */
|
|
export function resolveConfig(): GiteaConfig | null {
|
|
// E2E runs against fixtures — never hit the network from the test harness.
|
|
if (process.env.COMMITEA_E2E === '1') return null
|
|
const saved = loadConfig()
|
|
if (saved) return { baseUrl: saved.baseUrl, token: saved.token, owner: saved.owner, repo: saved.repo }
|
|
// COMMITEA_NO_ENV_LOCAL forces the onboarding path (no .env.local fallback) for testing.
|
|
if (process.env.COMMITEA_NO_ENV_LOCAL === '1') return null
|
|
// dev fallback — .env.local / env vars
|
|
const token = process.env.GITEA_TOKEN ?? loadEnvLocalToken()
|
|
if (!token) return null
|
|
return {
|
|
baseUrl: process.env.GITEA_BASE_URL ?? 'https://gitea.stephenmann.io',
|
|
token,
|
|
owner: process.env.GITEA_OWNER ?? 'christian',
|
|
repo: process.env.GITEA_REPO ?? 'commitea',
|
|
}
|
|
}
|
|
|
|
/** The pm-state repo name: configured, else `${repo}-pm-state`, else the env override. */
|
|
function pmStateRepoName(config: GiteaConfig): string {
|
|
return loadConfig()?.pmStateRepo ?? process.env.COMMITEA_PMSTATE_REPO ?? `${config.repo}-pm-state`
|
|
}
|
|
|
|
// Memoized clients; reset via resetClients() when the config changes.
|
|
let sharedClient: GiteaClient | null | undefined
|
|
let pmStateClient: GiteaClient | null | undefined
|
|
|
|
/** Drop the cached clients + snapshot so the next call re-reads the new config. */
|
|
export function resetClients(): void {
|
|
sharedClient = undefined
|
|
pmStateClient = undefined
|
|
labelCache = null
|
|
invalidateSnapshot()
|
|
}
|
|
|
|
export function getGiteaClient(): GiteaClient | null {
|
|
if (sharedClient === undefined) {
|
|
const config = resolveConfig()
|
|
sharedClient = config ? createGiteaClient(config, fetch) : null
|
|
}
|
|
return sharedClient
|
|
}
|
|
|
|
// The pm-state repo holds machine-derived state (the directive ledger). Same
|
|
// token/host as the work repo, a different repo (the purity split, decisions D4).
|
|
export function getPmStateClient(): GiteaClient | null {
|
|
if (pmStateClient === undefined) {
|
|
const config = resolveConfig()
|
|
pmStateClient = config ? createGiteaClient({ ...config, repo: pmStateRepoName(config) }, fetch) : null
|
|
}
|
|
return pmStateClient
|
|
}
|
|
|
|
const DIRECTIVE_LOG_PATH = 'directives/log.jsonl'
|
|
|
|
async function readDirectiveLog(client: GiteaClient): Promise<{ text: string; sha: string | null }> {
|
|
const file = await client.getFile(DIRECTIVE_LOG_PATH)
|
|
if (!file) return { text: '', sha: null }
|
|
return { text: Buffer.from(file.contentBase64, 'base64').toString('utf8'), sha: file.sha }
|
|
}
|
|
|
|
/** Record a directive: read the ledger, append, write it back (concatenation merge). */
|
|
export async function appendDirectiveEntry(client: GiteaClient, input: DirectiveInput): Promise<DirectiveEntry> {
|
|
const entry = makeDirectiveEntry(input, randomUUID(), new Date().toISOString())
|
|
const { text, sha } = await readDirectiveLog(client)
|
|
const next = appendDirective(text, entry)
|
|
await client.putFile(DIRECTIVE_LOG_PATH, {
|
|
contentBase64: Buffer.from(next, 'utf8').toString('base64'),
|
|
message: `directive: ${entry.kind}`,
|
|
sha: sha ?? undefined,
|
|
})
|
|
return entry
|
|
}
|
|
|
|
export async function readDirectives(client: GiteaClient) {
|
|
const { text } = await readDirectiveLog(client)
|
|
return parseDirectiveLog(text)
|
|
}
|
|
|
|
const CAPACITY_PATH = 'capacity/members.json'
|
|
|
|
/** Read the capacity config from the pm-state repo (empty when absent). */
|
|
export async function readCapacity(client: GiteaClient) {
|
|
const file = await client.getFile(CAPACITY_PATH)
|
|
if (!file) return []
|
|
try {
|
|
return parseCapacityConfig(JSON.parse(Buffer.from(file.contentBase64, 'base64').toString('utf8')))
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
/** Full reconcile: issues + milestones + native deps + lifecycle timelines. */
|
|
export async function reconcileSnapshot(
|
|
client: GiteaClient,
|
|
): Promise<ProjectSnapshot & { milestones: Awaited<ReturnType<GiteaClient['listMilestones']>> }> {
|
|
const [issues, milestones] = await Promise.all([client.listIssues(), client.listMilestones()])
|
|
// dependency edges among the open scope (the scheduler only plans what's left)
|
|
const open = issues.filter((i) => i.state === 'open')
|
|
const perIssue = await Promise.all(
|
|
open.map(async (i) => ({ issue: i.number, dependsOn: await client.getIssueDependencies(i.number) })),
|
|
)
|
|
const deps = perIssue.flatMap(({ issue, dependsOn }) => dependsOn.map((d) => ({ issue, dependsOn: d })))
|
|
// lifecycle timelines for every issue (open → columns/badges, closed → calibration actuals)
|
|
const timelineEntries = await Promise.all(
|
|
issues.map(async (i) => [i.number, await client.getIssueTimeline(i.number)] as const),
|
|
)
|
|
const timelines: Record<number, LifecycleEvent[]> = Object.fromEntries(timelineEntries)
|
|
return { issues, milestones, deps, timelines }
|
|
}
|
|
|
|
type Snapshot = Awaited<ReturnType<typeof reconcileSnapshot>>
|
|
|
|
/**
|
|
* A single in-memory reconcile cache shared across the app. A full reconcile is
|
|
* ~2N gitea calls (deps + timelines per issue); without this, every agent tool
|
|
* call refetched the whole repo. Reads within `maxAgeMs` reuse the cache;
|
|
* `getSnapshot({ maxAgeMs: 0 })` forces a fresh pull (the explicit UI reconcile),
|
|
* and any write calls `invalidateSnapshot()` so the next read sees it. The cache
|
|
* is rebuildable — the durable truth stays in gitea (the purity split, D4).
|
|
*/
|
|
let snapshotCache: { snap: Snapshot; at: number } | null = null
|
|
|
|
export async function getSnapshot(client: GiteaClient, opts?: { maxAgeMs?: number }): Promise<Snapshot> {
|
|
const maxAgeMs = opts?.maxAgeMs ?? 0
|
|
if (snapshotCache && maxAgeMs > 0 && Date.now() - snapshotCache.at <= maxAgeMs) {
|
|
return snapshotCache.snap
|
|
}
|
|
const snap = await reconcileSnapshot(client)
|
|
snapshotCache = { snap, at: Date.now() }
|
|
saveSnapshot(snap, new Date().toISOString()) // persist for instant boot + offline
|
|
return snap
|
|
}
|
|
|
|
/** Drop the cache so the next read reflects a just-made write. */
|
|
export function invalidateSnapshot(): void {
|
|
snapshotCache = null
|
|
}
|
|
|
|
/**
|
|
* The last persisted snapshot (from a previous session), for instant boot. The
|
|
* renderer shows it immediately, then a real reconcile supersedes it
|
|
* (stale-while-revalidate). Returns null when there's nothing on disk; its
|
|
* `savedAt` marks staleness. It does NOT seed the cache — agent tool calls
|
|
* always reconcile fresh so they never reason over stale data.
|
|
*/
|
|
export function bootSnapshot(): (Snapshot & { savedAt: string }) | null {
|
|
const persisted = loadSnapshot()
|
|
if (!persisted) return null
|
|
return {
|
|
issues: persisted.issues,
|
|
milestones: persisted.milestones,
|
|
deps: persisted.deps,
|
|
timelines: persisted.timelines,
|
|
savedAt: persisted.savedAt,
|
|
} as unknown as Snapshot & { savedAt: string }
|
|
}
|
|
|
|
/** Agent tool calls tolerate a slightly stale snapshot (seconds) to stay responsive. */
|
|
export const AGENT_SNAPSHOT_TTL_MS = 30_000
|
|
|
|
// Label cache is reset with the clients (module-level so resetClients can clear it).
|
|
let labelCache: GiteaLabel[] | null = null
|
|
async function resolveLabelIds(client: GiteaClient, names: string[]): Promise<number[]> {
|
|
const lookup = () => new Map(labelCache!.map((l) => [l.name, l.id]))
|
|
if (!labelCache) labelCache = await client.listLabels()
|
|
let byName = lookup()
|
|
if (names.some((n) => !byName.has(n))) {
|
|
labelCache = await client.listLabels() // a name we don't know — refetch once
|
|
byName = lookup()
|
|
}
|
|
return names.map((n) => byName.get(n)).filter((id): id is number => id != null)
|
|
}
|
|
|
|
export function registerGiteaIpc(): void {
|
|
ipcMain.handle('gitea:status', () => {
|
|
const cfg = resolveConfig()
|
|
return {
|
|
configured: !!cfg,
|
|
repo: cfg ? `${cfg.owner}/${cfg.repo}` : null,
|
|
demo: process.env.COMMITEA_E2E === '1',
|
|
}
|
|
})
|
|
|
|
// Instant boot: the last persisted snapshot, shown before the fresh reconcile lands.
|
|
ipcMain.handle('gitea:boot', () => {
|
|
if (!getGiteaClient()) return { configured: false }
|
|
const persisted = bootSnapshot()
|
|
return persisted ? { configured: true, cached: true, ...persisted } : { configured: true, cached: false }
|
|
})
|
|
|
|
ipcMain.handle('gitea:reconcile', async () => {
|
|
const client = getGiteaClient()
|
|
if (!client) return { configured: false, issues: [], milestones: [], deps: [], timelines: {} }
|
|
try {
|
|
// explicit UI sync — force fresh, and warm the cache for agent tool calls
|
|
const snap = await getSnapshot(client, { maxAgeMs: 0 })
|
|
return { configured: true, stale: false, ...snap }
|
|
} catch (e) {
|
|
// offline / gitea down — serve the last persisted snapshot rather than error out
|
|
const persisted = bootSnapshot()
|
|
if (persisted) return { configured: true, stale: true, ...persisted }
|
|
throw e
|
|
}
|
|
})
|
|
|
|
ipcMain.handle('gitea:getIssue', async (_event, index: number) => {
|
|
const client = getGiteaClient()
|
|
if (!client) return null
|
|
return client.getIssue(index)
|
|
})
|
|
|
|
// The write path (apply_changes), applied only after the renderer's propose-
|
|
// approve. Label swaps (est/p) return the plan; field writes (assign, milestone)
|
|
// return the freshly-read issue directly. Either way the snapshot is invalidated
|
|
// so the board + forecast reflect the change.
|
|
ipcMain.handle('gitea:applyChange', async (_event, change: IssueChange) => {
|
|
const client = getGiteaClient()
|
|
if (!client) return { ok: false as const, reason: 'unconfigured' as const }
|
|
|
|
if (isLabelChange(change)) {
|
|
const current = await client.getIssue(change.issue)
|
|
const plan = planIssueChange(current.labels, change)
|
|
if (plan.noop) return { ok: true as const, plan, issue: current }
|
|
const ids = await resolveLabelIds(client, plan.labels)
|
|
await client.setIssueLabels(change.issue, ids)
|
|
const issue = await client.getIssue(change.issue)
|
|
invalidateSnapshot()
|
|
return { ok: true as const, plan, issue }
|
|
}
|
|
|
|
// Field writes — the client returns the updated issue.
|
|
const issue =
|
|
change.kind === 'assign'
|
|
? await client.setIssueAssignees(change.issue, change.assignee ? [change.assignee] : [])
|
|
: await client.setIssueMilestone(change.issue, change.milestone)
|
|
invalidateSnapshot()
|
|
return { ok: true as const, issue }
|
|
})
|
|
|
|
// capture_work filing: open each approved issue with its est/* + p/* labels.
|
|
// Only touches the CommiTea label namespaces — no invented labels (zero-pollution).
|
|
ipcMain.handle(
|
|
'gitea:createIssues',
|
|
async (_event, issues: { title: string; body?: string; estimate?: string; priority?: string }[]) => {
|
|
const client = getGiteaClient()
|
|
if (!client) return { ok: false as const, reason: 'unconfigured' as const }
|
|
const created: { number: number; title: string }[] = []
|
|
for (const it of issues) {
|
|
const names = [it.estimate, it.priority].filter((n): n is string => !!n)
|
|
const labelIds = await resolveLabelIds(client, names)
|
|
const issue = await client.createIssue({ title: it.title, body: it.body, labelIds })
|
|
created.push({ number: issue.number, title: issue.title })
|
|
}
|
|
if (created.length) invalidateSnapshot() // new issues enter the board/scope
|
|
return { ok: true as const, created }
|
|
},
|
|
)
|
|
|
|
// Read the directive ledger from the pm-state repo (for the Directives screen).
|
|
ipcMain.handle('pmstate:directives', async () => {
|
|
const pm = getPmStateClient()
|
|
if (!pm) return { ok: false as const, reason: 'unconfigured' as const }
|
|
try {
|
|
return { ok: true as const, directives: await readDirectives(pm) }
|
|
} catch (e) {
|
|
return { ok: false as const, reason: 'error' as const, message: e instanceof Error ? e.message : String(e) }
|
|
}
|
|
})
|
|
|
|
// Read the capacity config from the pm-state repo (for capacity-aware forecasts).
|
|
ipcMain.handle('pmstate:capacity', async () => {
|
|
const pm = getPmStateClient()
|
|
if (!pm) return { ok: false as const, reason: 'unconfigured' as const, members: [] }
|
|
try {
|
|
return { ok: true as const, members: await readCapacity(pm) }
|
|
} catch {
|
|
return { ok: true as const, members: [] }
|
|
}
|
|
})
|
|
|
|
// Assignable people (repo collaborators) for the Adjust dialog's assignee picker.
|
|
ipcMain.handle('gitea:collaborators', async () => {
|
|
const client = getGiteaClient()
|
|
if (!client) return []
|
|
try {
|
|
return await client.listCollaborators()
|
|
} catch {
|
|
return []
|
|
}
|
|
})
|
|
|
|
// ---- config (team onboarding) ----
|
|
ipcMain.handle('config:get', () => publicConfig())
|
|
|
|
ipcMain.handle('config:set', (_event, cfg: AppConfig) => {
|
|
saveConfig(cfg)
|
|
resetClients() // new config takes effect without a restart
|
|
return { ok: true as const }
|
|
})
|
|
|
|
ipcMain.handle('config:clear', () => {
|
|
clearConfig()
|
|
resetClients()
|
|
return { ok: true as const }
|
|
})
|
|
|
|
// Discover the owners + repos a token can reach, so onboarding can offer them
|
|
// as dropdowns. Token-scoped (not repo-scoped) — no owner/repo needed yet.
|
|
ipcMain.handle('config:discover', async (_event, conn: { baseUrl: string; token: string }) => {
|
|
try {
|
|
const found = await discoverRepos({ baseUrl: conn.baseUrl.replace(/\/+$/, ''), token: conn.token }, fetch)
|
|
return { ok: true as const, ...found }
|
|
} catch (e) {
|
|
return { ok: false as const, error: e instanceof GiteaApiError ? `${e.status}` : e instanceof Error ? e.message : String(e) }
|
|
}
|
|
})
|
|
|
|
// Validate a token + repo before saving: any authed read on the repo proves access.
|
|
ipcMain.handle('config:test', async (_event, cfg: AppConfig) => {
|
|
try {
|
|
const c = createGiteaClient(
|
|
{ baseUrl: cfg.baseUrl.replace(/\/+$/, ''), owner: cfg.owner.trim(), repo: cfg.repo.trim(), token: cfg.token },
|
|
fetch,
|
|
)
|
|
await c.listLabels()
|
|
return { ok: true as const }
|
|
} catch (e) {
|
|
return { ok: false as const, error: e instanceof GiteaApiError ? `${e.status}` : e instanceof Error ? e.message : String(e) }
|
|
}
|
|
})
|
|
}
|