From 010fa29e516eabb88be9d9438286672b3edb1d27 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:50:52 +0000 Subject: [PATCH 1/2] GitHub App user lane: answered actions run as the answering operator with their user token, waiting states on decisions, Retry and an 'act as you' authorization --- src/act/dupe-groups.ts | 7 + src/act/index.ts | 60 ++++++- src/conversations/act.ts | 17 +- src/core/guard.ts | 9 +- src/dash/api/decisions.ts | 18 +- src/dash/api/index.ts | 1 + src/dash/server/github-app.ts | 13 +- src/dash/server/index.ts | 34 +++- src/db.ts | 3 + src/decisions-used.ts | 2 + src/decisions.ts | 1 + src/fixup/git.ts | 4 +- src/github/user-lane.ts | 172 +++++++++++++++++++ src/github/write.ts | 5 +- src/labels/github.ts | 43 ++++- src/merge/index.ts | 37 +++- src/mirror.ts | 8 +- src/schema.sql | 3 +- test/user-lane.test.ts | 59 +++++++ web/src/api/client.ts | 2 + web/src/api/http.ts | 1 + web/src/api/mock/adminMock.ts | 2 +- web/src/api/mock/fixtures.ts | 57 ++++++ web/src/api/mock/mockApi.ts | 9 +- web/src/api/types.ts | 6 + web/src/modules/admin/githubAppViews.tsx | 5 + web/src/modules/decisions/DecisionDetail.tsx | 2 + web/src/modules/decisions/ExecLine.tsx | 44 +++++ web/src/modules/decisions/InboxList.tsx | 2 + 29 files changed, 581 insertions(+), 45 deletions(-) create mode 100644 src/github/user-lane.ts create mode 100644 test/user-lane.test.ts create mode 100644 web/src/modules/decisions/ExecLine.tsx diff --git a/src/act/dupe-groups.ts b/src/act/dupe-groups.ts index 0440d344..dbfda6b6 100644 --- a/src/act/dupe-groups.ts +++ b/src/act/dupe-groups.ts @@ -20,6 +20,10 @@ export type GroupIo = { /** Returns the comment's URL. */ comment(live: GroupLive, body: string, at: { number: number; decision: string }): Promise; close(live: GroupLive, at: { number: number; decision: string }): Promise; + /** Called before a decision's writes: a string says why the decision waits (its operator has no token or no access), and it is left for a later run. */ + begin?(decision: string): Promise; + /** A write of the decision failed with `why`; true when that is a wait for the operator's access, not a failure to count. */ + failed?(decision: string, why: string): boolean; }; export type GroupRun = { repo: string; io: GroupIo; at: () => string; log: (line: string) => void; @@ -70,6 +74,8 @@ export async function actOnGroups(db: DatabaseSync, run: GroupRun): Promise { record(dec.id, n, step, null); if (release) { @@ -152,6 +158,7 @@ export async function actOnGroups(db: DatabaseSync, run: GroupRun): Promise null, comment: async () => "", close: async () => {} }; @@ -44,7 +45,7 @@ const KIND = "comment-close"; const DUP_FACT = "duplicate of "; const REASON_FACT = "review reason: "; -export type ActDeps = { querier: Querier; now: () => Date }; +export type ActDeps = { querier: Querier; now: () => Date; /** The user lane's token source and transports; default: the secrets file's app. */ lane?: LaneDeps }; export const defaultDeps = (): ActDeps => ({ querier: new Client(1000), now: () => new Date() }); export type ActParams = { @@ -260,8 +261,17 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st handled++; params.onHandled?.(handled); const prev = rowOf(db, t); + // An answer in a repo on the app's identity is carried out as the operator who gave it, with their token; it waits when there is none. + const lr = await laneForDecision(db, d.lane, t.decisionId, [t.repo]); + if (lr && !("lane" in lr)) { + if ("transient" in lr) jobItem(db, t.repo, t.number, `not closed yet: ${lr.transient}`, log); + else { setExecState(db, t.decisionId, lr.state, lr.reason); jobItem(db, t.repo, t.number, `waiting: ${lr.reason}`, log); } + continue; + } + if (lr) setExecState(db, t.decisionId, "pending"); + const q = lr ? lr.lane.querier : d.querier; try { - const live = await readLive(d.querier, t.repo, t.number); + const live = await readLive(q, t.repo, t.number); if (!live) { skip(t, "GitHub returned no such item"); continue; } if (live.state !== "OPEN") { skip(t, `already ${live.state.toLowerCase()} on GitHub`); continue; } if (t.kind === "close" || t.kind === "merge") { @@ -276,15 +286,15 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st if (t.kind === "duplicate") { const orig = /^([\w.-]+)#(\d+)$/.exec(factValue(dec, DUP_FACT) ?? ""); if (!orig || orig[1] !== t.repo || Number(orig[2]) === t.number) { skip(t, "the decision names no other item of this repo as the original"); continue; } - const o = await readLive(d.querier, t.repo, Number(orig[2])); + const o = await readLive(q, t.repo, Number(orig[2])); if (!o) { skip(t, "GitHub returned no such original"); continue; } body = duplicateComment({ repo: t.repo, original: `${orig[1]}#${orig[2]}`, closed: o.state !== "OPEN" }); } else body = commentFor(dec, t); - url = await commentOn(w, g, d.querier, "act-comment", { repo: t.repo, number: t.number, id: live.id }, decisionNote(dec), body, { decision: t.decisionId }); + url = await commentOn(w, g, q, "act-comment", { repo: t.repo, number: t.number, id: live.id }, decisionNote(dec), body, { decision: t.decisionId }); // Saved before the close so a retry after a failed close does not comment twice. save(t, "failed", "comment posted; close not done yet", url); } - await closeItem(w, g, d.querier, { repo: t.repo, number: t.number, id: live.id, pr: live.type === "PullRequest" }, { decision: t.decisionId, head: live.head }); + await closeItem(w, g, q, { repo: t.repo, number: t.number, id: live.id, pr: live.type === "PullRequest" }, { decision: t.decisionId, head: live.head }); save(t, "done", null, url); db.prepare("INSERT INTO stages (repo, number, stage, at, actor, note) VALUES (?, ?, 'closed', ?, ?, ?)").run(t.repo, t.number, at(), ACTOR, `closed after ${t.kind} decision ${t.decisionId}`); summary.done.push(refOf(t)); @@ -292,6 +302,14 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st settle(t); } catch (e) { const why = (e as Error).message.replace(/\s+/g, " ").slice(0, 300); + const denied = lr ? authFailure(why) : null; + if (denied) { + // The user's token may not do this write: wait for access instead of failing, and write nothing as anyone else. + setExecState(db, t.decisionId, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(t.repo)); + jobItem(db, t.repo, t.number, `waiting: ${why}`, log); + continue; + } + if (lr) setExecState(db, t.decisionId, "failed", why); const row = rowOf(db, t); save(t, "failed", why, row?.comment_url ?? null); summary.failed.push({ ref: refOf(t), reason: why }); @@ -303,10 +321,33 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st const groupGrant = summary.failed.length ? null : guardRepo(db, repo, "comment", params.by ?? CLI_BY); if (groupGrant && "refused" in groupGrant) log(` duplicate groups: not applied: ${groupGrant.refused}`); else if (groupGrant) { + // Each group decision is carried out as the operator who answered it; `begin` picks that operator's lane. + let lane: Lane | null = null; + const q = (): Querier => lane?.querier ?? d.querier; + const asAnswerer = (decision: string): GuardedRepo => { + const g = guardRepo(db, repo, "comment", params.by ?? CLI_BY, decision); + if ("refused" in g) throw new Error(g.refused); + return g; + }; const io: GroupIo = { - live: (n) => readLive(d.querier, repo, n), - comment: (live, body, at) => commentOn(w, groupGrant, d.querier, "act-comment", { repo, number: at.number, id: live.id }, decisionNote(getDecision(db, at.decision)!), body, { decision: at.decision }), - close: (live, at) => closeItem(w, groupGrant, d.querier, { repo, number: at.number, id: live.id, pr: live.type === "PullRequest" }, { decision: at.decision, head: live.head }), + async begin(decision) { + lane = null; + const lr = await laneForDecision(db, d.lane, decision, [repo]); + if (!lr) return null; + if ("lane" in lr) { lane = lr.lane; setExecState(db, decision, "pending"); return null; } + if ("transient" in lr) return lr.transient; + setExecState(db, decision, lr.state, lr.reason); + return lr.reason; + }, + failed(decision, why) { + const denied = lane ? authFailure(why) : null; + if (denied) { setExecState(db, decision, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(repo)); return true; } + if (lane) setExecState(db, decision, "failed", why); + return false; + }, + live: (n) => readLive(q(), repo, n), + comment: (live, body, at) => commentOn(w, asAnswerer(at.decision), q(), "act-comment", { repo, number: at.number, id: live.id }, decisionNote(getDecision(db, at.decision)!), body, { decision: at.decision }), + close: (live, at) => closeItem(w, asAnswerer(at.decision), q(), { repo, number: at.number, id: live.id, pr: live.type === "PullRequest" }, { decision: at.decision, head: live.head }), }; const g = await actOnGroups(db, { repo, io, at, log, dryRun: false, @@ -317,6 +358,7 @@ export async function runAct(db: DatabaseSync, params: ActParams, log: (line: st summary.skipped.push(...g.skipped); summary.failed.push(...g.failed); } + markExecDone(db); log(`act ${repo}: ${summary.done.length} closed, ${summary.skipped.length} skipped, ${summary.failed.length} failed, ${summary.asked.length} asked`); return summary; } diff --git a/src/conversations/act.ts b/src/conversations/act.ts index 931613e8..deb79ccb 100644 --- a/src/conversations/act.ts +++ b/src/conversations/act.ts @@ -1,8 +1,9 @@ // Runs one action card once through the existing write paths (src/github/write.ts, the decision answer, // the per-repo approvals) with the operator's login on every audit row. Cards never run on their own. import { guardRepo } from "../core/guard.ts"; +import { initExecState, laneForOperator, type LaneDeps } from "../github/user-lane.ts"; import type { DatabaseSync } from "node:sqlite"; -import { readLive } from "../act/index.ts"; +import { readLive, writeEffect } from "../act/index.ts"; import { duplicateComment } from "../act/templates.ts"; import { audit } from "../dash/audit.ts"; import { optionsOf, BACKLOG, HANDLED, getDecision, reposOf, replaceProposedCards } from "../decisions.ts"; @@ -26,7 +27,7 @@ export type CardRow = { }; /** `canWrite` is the signed-in operator's write access to a repo; the shell has none to check. */ -export type ActDeps = StoreDeps & { querier?: Querier; /** Runs `gh` for the open_issue step. */ exec?: Exec; canWrite?: (repo: string) => Promise; /** Indexes into a resolution's steps the operator removed. */ skip?: number[]; /** The operator's note with the choice. */ note?: string }; +export type ActDeps = StoreDeps & { querier?: Querier; /** Runs `gh` for the open_issue step. */ exec?: Exec; canWrite?: (repo: string) => Promise; /** Indexes into a resolution's steps the operator removed. */ skip?: number[]; /** The user lane's token source and transports; default: the secrets file's app. */ lane?: LaneDeps; /** The operator's note with the choice. */ note?: string }; export const cardOf = (db: DatabaseSync, id: number): CardRow | undefined => db.prepare("SELECT * FROM conversation_cards WHERE id = ?").get(id) as CardRow | undefined; @@ -115,6 +116,7 @@ async function answerDecision(db: DatabaseSync, c: CardRow, decisionId: string | replaceProposedCards(db, d.repo, d.number); audit(db, by, "answer", d.id, { answer: key, source: "conversation" }); db.exec("COMMIT"); + if (writeEffect(d.kind, key)) initExecState(db, d.id); return { result: `Answered the decision with "${o.label}"`, url: null }; } catch (e) { db.exec("ROLLBACK"); @@ -235,7 +237,8 @@ function actRoom(db: DatabaseSync): void { /** The Act approval of `repo` for the operator's write, and room under the daily limit. */ function actGrant(db: DatabaseSync, repo: string, by: string, need: "comment" | "labels" = "comment") { - const g = guardRepo(db, repo, need, { operator: by }); + // The operator who presses the button acts as themselves (as `user:` once the repo is on the app's identity). + const g = guardRepo(db, repo, need, { operator: by }, undefined, by); if ("refused" in g) throw new Error(g.refused); actRoom(db); return g; @@ -465,12 +468,18 @@ export async function doCard(db: DatabaseSync, id: number, by: string, deps: Act noteIsSummary = true; } } + // A card's GitHub writes are the pressing operator's own: on a repo with the app's identity they use that operator's token, and a card that cannot stays proposed. + const repos = [c.repo, ...(params.kind === "resolution" ? params.steps.flatMap((x) => (x.kind === "transfer" ? [x.to] : x.kind === "open_issue" ? [x.repo] : [])) : [])]; + const writes = params.kind === "comment" || params.kind === "label" || params.kind === "close" || params.kind === "duplicate" + || (params.kind === "resolution" && params.steps.some((x) => x.kind !== "review" && x.kind !== "fixup")); + const lr = writes ? await laneForOperator(db, deps.lane, by, repos) : null; + if (lr && !("lane" in lr)) throw new ConversationError("transient" in lr ? 503 : 409, "transient" in lr ? `GitHub could not be reached to check your access: ${lr.transient}` : lr.reason); const at = (deps.now?.() ?? new Date()).toISOString(); const claim = db.prepare("UPDATE conversation_cards SET state = 'running', acted_by = ?, acted_at = ? WHERE id = ? AND state = 'proposed'").run(by, at, id); if (claim.changes !== 1) return { card: c, ran: false }; let out: Outcome | null = null, error: string | null = null, posted = false; try { - out = await run(db, c, params, by, deps.querier ?? new Client(1000), at, deps.canWrite, noteIsSummary ? undefined : note, deps.exec); + out = await run(db, c, params, by, lr ? lr.lane.querier : deps.querier ?? new Client(1000), at, deps.canWrite, noteIsSummary ? undefined : note, lr ? lr.lane.exec : deps.exec); } catch (e) { error = oneLine(String((e as Error).message ?? e)); posted = e instanceof StepError && e.posted; diff --git a/src/core/guard.ts b/src/core/guard.ts index 9c3a87d9..41fc0444 100644 --- a/src/core/guard.ts +++ b/src/core/guard.ts @@ -119,7 +119,7 @@ export async function guardBatchMerge(db: DatabaseSync, batch: Ref & { head: str } /** Lets an issue or PR write of the item steps through while decideItem still has the action for the item. No GitHub read: the caller reads what it needs. */ -export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by: By): Promise { +export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by: By, asDecision?: string): Promise { const name = `${ref.repo}#${ref.number}`; const f = loadItemFact(db, ref.repo, ref.number); if (!f) return { refused: `${name}: not an open item the pipeline tracks` }; @@ -134,7 +134,7 @@ export async function guardItem(db: DatabaseSync, ref: Ref, action: ItemWant, by const now = plan.actions.map((x) => x.kind + (typeof x.params?.bucket === "string" ? `:${x.params.bucket}` : "")).join(", ") || "none"; return { refused: `${name}: the plan no longer has ${action.kind}${action.bucket ? `:${action.bucket}` : ""} (state ${plan.state}, actions: ${now})` }; } - return { scope: "item", action, repo: ref.repo, number: ref.number, as: identityOfDecision(db, action.decisionId) } as unknown as GuardedItem; + return { scope: "item", action, repo: ref.repo, number: ref.number, as: identityOfDecision(db, asDecision ?? action.decisionId) } as unknown as GuardedItem; } /** The approvals of a repo and the global switch, read now. */ @@ -147,7 +147,8 @@ export function repoApprovals(db: DatabaseSync, repo: string): Parameters { if (!canUndo(db, d)) throw new HttpError(409, "the pipeline already wrote to GitHub for this answer"); - const r = db.prepare(`UPDATE main.decisions SET answer = NULL, answer_note = NULL, exceptions = NULL, answered_by = NULL, answered_at = NULL, applied_at = NULL, adopted_opinion = NULL, snoozed_by = NULL, snoozed_at = NULL + const r = db.prepare(`UPDATE main.decisions SET answer = NULL, answer_note = NULL, exceptions = NULL, answered_by = NULL, answered_at = NULL, applied_at = NULL, adopted_opinion = NULL, snoozed_by = NULL, snoozed_at = NULL, exec_state = NULL, exec_reason = NULL WHERE id = ? AND answer IS NOT NULL AND (applied_at IS NULL OR answer = '${HANDLED.key}')`).run(d.id); if (r.changes !== 1) throw new HttpError(409, "the pipeline acted on this a moment ago"); resetGroupAnswer(db, d.id); @@ -467,6 +470,16 @@ export async function undo(db: DatabaseSync, req: Req, via?: "mcp"): Promise { + const d = await needDecision(db, req, req.params.id!); + await requireOperator(req, d); + if (!d.answer || d.applied_at) throw new HttpError(409, "that decision has nothing waiting to run"); + if (!retryDecision(db, d.id)) throw new HttpError(409, "that decision is not waiting or failed"); + audit(db, req.user.login, "retry", d.id, { answer: d.answer }); + return toDecision(db, getDecision(db, d.id)!, await viewerWith(db, req)); +} + export async function reopen(db: DatabaseSync, req: Req): Promise { const d = await needDecision(db, req, req.params.id!); await requireOperator(req, d); @@ -509,6 +522,7 @@ export async function adopt(db: DatabaseSync, req: Req): Promise { WHERE id = ? AND answer IS NULL`).run(option, isBatch(d) ? "[]" : null, req.user.login, new Date().toISOString(), o.id, d.id); if (r.changes !== 1) throw new HttpError(409, "someone answered this a moment ago"); }); + if (writeEffect(d.kind, option)) initExecState(db, d.id); audit(db, req.user.login, "adopt", d.id, { answer: o.option, opinion: o.id, of: o.login }); return await settled(db, req, d.id); } diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index c8d821d8..4eb86e11 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -381,6 +381,7 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { get("/api/decisions/:id/thread", dec.thread), post("/api/decisions/:id/answer", dec.answer), post("/api/decisions/:id/undo", dec.undo), + post("/api/decisions/:id/retry", dec.retry), { method: "POST", pattern: "/api/decisions/:id/snooze", operator: true, handler: ok(dec.snooze) }, post("/api/decisions/:id/reopen", dec.reopen), { method: "POST", pattern: "/api/decisions/backlog", operator: true, handler: ok(dec.backlogBulk) }, diff --git a/src/dash/server/github-app.ts b/src/dash/server/github-app.ts index f68192ff..1ef78694 100644 --- a/src/dash/server/github-app.ts +++ b/src/dash/server/github-app.ts @@ -24,7 +24,14 @@ export const publicBase = (config: Config, req: IncomingMessage): string => conf export function githubAppRoutes(config: Config, deps: AppDeps): Route[] { return [{ method: "GET", pattern: "/api/admin/github-app", operator: true, - handler: async (db, r): Promise => ({ json: { ...(await githubAppStatus(db, config, deps)), csrf: r.csrf } }), + handler: async (db, r): Promise => ({ + json: { + ...(await githubAppStatus(db, config, deps)), + csrf: r.csrf, + // Whether the signed-in operator has let the app act as them (their user token is stored and still good). + authorized: config.secrets.app ? !!db.prepare("SELECT 1 FROM user_tokens WHERE login = ? AND status = 'ok'").get(r.user.login) : null, + }, + }), }, { // Forgets the registered app's keys so another app can be registered; the operator deletes the app on GitHub. method: "POST", pattern: "/api/admin/github-app/remove", operator: true, @@ -61,9 +68,9 @@ export function githubAppRoutes(config: Config, deps: AppDeps): Route[] { }]; } -export async function githubAppStatus(db: DatabaseSync, config: Config, deps: AppDeps): Promise> { +export async function githubAppStatus(db: DatabaseSync, config: Config, deps: AppDeps): Promise> { const app = config.secrets.app; - const status: Omit = { + const status: Omit = { configured: !!app, loginMode: config.loginApp, canRegister: !!config.secretsFile, defaultName: envVar("GITHUB_APP_NAME") ?? DEFAULT_APP_NAME, app: null, installations: [], links: openLinks(db), error: null, }; diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 06877f8b..4b690482 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -20,13 +20,16 @@ import { auditLoginMode, finishRegistration, githubAppRoutes, startRegistration import { OrgSetup } from "./github-setup.ts"; import { Vault } from "../../github/vault.ts"; import { saveUserTokens } from "./user-tokens.ts"; -import { FakeProvider, oauthProviderFor, providerFor, type GithubUser, type Provider, type Tokens } from "./provider.ts"; +import { FakeProvider, GitHubProvider, oauthProviderFor, providerFor, type GithubUser, type Provider, type Tokens } from "./provider.ts"; +import { retryWaiting } from "../../github/user-lane.ts"; import { createSession, deleteSession, loadSession, makeUser, pruneExpired, SESSION_TTL, userForLogin, type Session } from "./sessions.ts"; import { answering, handleMcp, writes as mcpWrites, type Msg as McpMsg } from "../mcp/index.ts"; import { loadToken, pruneTokens } from "../mcp/tokens.ts"; import { esc, HttpError, parseCookies, plainPage, RateLimiter, safeReturnTo } from "./util.ts"; export const SESSION_COOKIE = "__Host-craft_session"; +/** `oauth_states.return_to` of an "act as you" authorization, which the shared sign-in callback tells apart from a sign-in by this prefix. */ +const AUTHORIZE_PREFIX = "authorize:"; const STATE_COOKIE = "__Host-craft_oauth"; const BODY_LIMIT = 64 * 1024; const FILE_TYPES: Record = { @@ -145,7 +148,10 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { // The org setup link signs in with the OAuth App even when dashboard sign-in uses the GitHub App. const setupProvider = opts.provider ?? (config.devAuth ? provider : oauthProviderFor(config)); const box = new TokenBox(config.secrets.sessionKey); - const vault = new Vault(db, box, provider); + // The GitHub App's own provider: it signs users in under login=github-app, and always makes and refreshes their user tokens (the "act as you" authorization). + const appKeys = config.secrets.app; + const appProvider: Provider | null = opts.provider ?? (config.devAuth ? provider : appKeys ? new GitHubProvider(appKeys.clientId, appKeys.clientSecret) : null); + const vault = new Vault(db, box, appProvider ?? provider); const appDeps = { apiBase: opts.githubApi }; const routes = compile([...opts.routes, ...githubAppRoutes(config, appDeps)]); auditLoginMode(db, config); @@ -321,6 +327,15 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { if (loadSession(db, cookies.get(SESSION_COOKIE))) return { r: { redirect: returnTo } }; return startOAuth(returnTo, url.searchParams.get("select") === "1"); } + if (req.method === "GET" && path === "/auth/authorize-app") { + if (!signinLimit.allow(ip)) return { r: errorPage(nonce, 429, "Too many attempts", "Wait a few minutes and try again.") }; + const returnTo = safeReturnTo(url.searchParams.get("return_to")); + const s = loadSession(db, cookies.get(SESSION_COOKIE)); + if (!s) return { r: { redirect: `/auth/signin?${new URLSearchParams({ return_to: `/auth/authorize-app?${new URLSearchParams({ return_to: returnTo })}` })}` } }; + if (s.role !== "operator") return { r: errorPage(nonce, 403, "Not authorised", "Only operators authorize AutoCraft to act as them.") }; + if (!appProvider) return { r: errorPage(nonce, 409, "No GitHub App", "No GitHub App is registered, so there is nothing to authorize.") }; + return startOAuth(`${AUTHORIZE_PREFIX}${returnTo}`, false, undefined, appProvider); + } if (req.method === "GET" && path === "/auth/callback") { if (!signinLimit.allow(ip)) return { r: errorPage(nonce, 429, "Too many attempts", "Wait a few minutes and try again.") }; const clear = [cookie(STATE_COOKIE, "", 0)]; @@ -337,7 +352,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { } let tokens: Tokens | null, who: GithubUser | null; try { - const p = row.return_to?.startsWith("setup:") ? setupProvider : provider; + const p = row.return_to?.startsWith("setup:") ? setupProvider : row.return_to?.startsWith(AUTHORIZE_PREFIX) ? (appProvider ?? provider) : provider; tokens = await p.exchange(code, row.verifier, callbackUrl); who = tokens ? await p.identity(tokens.access) : null; } catch (e) { @@ -351,6 +366,17 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { const out = await setup.signedIn(row.return_to, tokens, who, nonce, cookies); return { r: out.r, cookies: [...clear, ...(out.cookies ?? [])] }; } + if (row.return_to?.startsWith(AUTHORIZE_PREFIX)) { + // "Act as you": only the user token is stored. The session and the sign-in are untouched. + const s = loadSession(db, cookies.get(SESSION_COOKIE)); + if (!s || s.role !== "operator" || s.login.toLowerCase() !== who.login.toLowerCase() || checkGithubId(db, s.login, who.id) === "mismatch") { + return { r: errorPage(nonce, 403, "Not authorised", "Sign in to the dashboard as the GitHub account you authorize, then try again."), cookies: clear }; + } + saveUserTokens(db, box, s.login, who.id, tokens); + retryWaiting(db, s.login); + audit(db, s.login, "github-app-authorize", s.login, { ip }); + return { r: { redirect: safeReturnTo(row.return_to.slice(AUTHORIZE_PREFIX.length)) }, cookies: clear }; + } const login = who.login; const access = getAccess(db, login); if (!access) { @@ -362,7 +388,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { return { r: errorPage(nonce, 403, "Not authorised", `The GitHub account ${login} is not the account that was added to this dashboard's access list.`), cookies: clear }; } const id = createSession(db, box, access.login, tokens, req.headers["user-agent"]); - if (config.loginApp === "github-app") saveUserTokens(db, box, access.login, who.id, tokens); + if (config.loginApp === "github-app") { saveUserTokens(db, box, access.login, who.id, tokens); retryWaiting(db, access.login); } audit(db, access.login, "sign-in", access.login, { ip }); return { r: { redirect: safeReturnTo(row.return_to) }, diff --git a/src/db.ts b/src/db.ts index b9ed4cac..706d19bf 100644 --- a/src/db.ts +++ b/src/db.ts @@ -55,6 +55,9 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [ // What Opus had seen of the item when it proposed the card: JSON {head, last_comment}; null for cards stored before this. ["conversation_cards", "seen", "TEXT"], ["decisions", "snoozed_at", "TEXT"], + // Where the GitHub write of an answer stands under repo_identity=app (src/github/user-lane.ts): pending | waiting-token | waiting-permission | done | failed; null before any attempt. + ["decisions", "exec_state", "TEXT"], + ["decisions", "exec_reason", "TEXT"], ["classifications", "probs", "TEXT"], ["token_usage", "cost_usd", "REAL"], ["classifications", "input_hash", "TEXT"], diff --git a/src/decisions-used.ts b/src/decisions-used.ts index acbed574..2eb1cb00 100644 --- a/src/decisions-used.ts +++ b/src/decisions-used.ts @@ -12,6 +12,7 @@ import { audit } from "./dash/audit.ts"; import { actionable, getDecision } from "./decisions.ts"; import { PLUGIN_LABEL } from "./labels/plan.ts"; import { sameLabel } from "./labels/set.ts"; +import { markExecDone } from "./github/user-lane.ts"; const ACTOR = "pipeline"; @@ -43,6 +44,7 @@ export function applyUsedAnswers(db: DatabaseSync, at: string = new Date().toISO audit(db, ACTOR, "answer-used", a.id, { answer: a.answer }); n++; } + markExecDone(db); return n; } diff --git a/src/decisions.ts b/src/decisions.ts index 0a1fd58d..8f679770 100644 --- a/src/decisions.ts +++ b/src/decisions.ts @@ -23,6 +23,7 @@ export type DecisionRow = { answered_by: string | null; answered_at: string | null; applied_at: string | null; prepared_at?: string | null; prepared_head?: string | null; prepare_failed_head?: string | null; recommend_failures?: number | null; recommend_failed_at?: string | null; summary: string | null; summary_by: string | null; summary_at: string | null; adopted_opinion: string | null; snoozed_by: string | null; snoozed_at: string | null; + exec_state?: string | null; exec_reason?: string | null; }; const j = (s: string | null, d: T): T => { diff --git a/src/fixup/git.ts b/src/fixup/git.ts index f7784f02..ddfd5883 100644 --- a/src/fixup/git.ts +++ b/src/fixup/git.ts @@ -9,12 +9,12 @@ import { join } from "node:path"; import { envVar } from "../env.ts"; export type ExecResult = { code: number; stdout: string; stderr: string }; -export type ExecOpts = { cwd?: string; env?: Record; input?: string }; +export type ExecOpts = { cwd?: string; env?: Record; input?: string; /** `env` is the child's whole environment instead of additions to the process's. */ replaceEnv?: boolean }; /** Runs a command; resolves with its exit code, rejects only when it can't be started. */ export type Exec = (cmd: string, args: string[], opts?: ExecOpts) => Promise; export const exec: Exec = (cmd, args, opts = {}) => new Promise((resolve, reject) => { - const p = spawn(cmd, args, { cwd: opts.cwd, env: { ...process.env, ...opts.env }, stdio: ["pipe", "pipe", "pipe"], timeout: 300_000 }); + const p = spawn(cmd, args, { cwd: opts.cwd, env: opts.replaceEnv ? opts.env : { ...process.env, ...opts.env }, stdio: ["pipe", "pipe", "pipe"], timeout: 300_000 }); let stdout = "", stderr = ""; p.stdout.on("data", (d) => (stdout += d)); p.stderr.on("data", (d) => (stderr += d)); diff --git a/src/github/user-lane.ts b/src/github/user-lane.ts new file mode 100644 index 00000000..f6d58f5e --- /dev/null +++ b/src/github/user-lane.ts @@ -0,0 +1,172 @@ +// The user lane: a GitHub write that carries out an operator's answer is made as that operator, with the operator's +// GitHub App user token (src/github/vault.ts), never as the box account or the app. Only repos whose `repo_identity` +// is `app` use it; under `legacy` nothing here runs and the box account writes as before. +// +// A decision whose operator has no usable token, or no write access on the repo, does not fail: it waits +// (`decisions.exec_state` waiting-token / waiting-permission, with a plain reason) and runs again after that operator +// signs in or authorizes again, or when someone presses Retry. +import type { DatabaseSync } from "node:sqlite"; +import { AppError, call, GITHUB_API } from "./app.ts"; +import { identityOfDecision, repoIdentity } from "./identity.ts"; +import { openVault, type Vault } from "./vault.ts"; +import { withIdentityEnv } from "./install-token.ts"; +import { exec as defaultExec, type Exec } from "../fixup/git.ts"; +import { Client, type Querier } from "../mirror.ts"; +import { slugOf } from "../owners.ts"; + +export type ExecState = "pending" | "waiting-token" | "waiting-permission" | "done" | "failed"; +export const WAITING: readonly ExecState[] = ["waiting-token", "waiting-permission"]; + +export const SIGN_IN_REASON = "Sign in to let AutoCraft finish this as you"; +export const noWriteReason = (repo: string): string => `You have no write access to ${slugOf(repo)}`; + +/** Sets the state shown on the decision. Writes nothing when it is already that, so the planner is not woken for nothing. */ +export function setExecState(db: DatabaseSync, id: string, state: ExecState, reason: string | null = null): void { + db.prepare("UPDATE main.decisions SET exec_state = ?, exec_reason = ? WHERE id = ? AND (exec_state IS NOT ? OR exec_reason IS NOT ?)").run(state, reason, id, state, reason); +} + +/** Decisions the pipeline applied are done. */ +export function markExecDone(db: DatabaseSync): void { + db.prepare("UPDATE main.decisions SET exec_state = 'done', exec_reason = NULL WHERE applied_at IS NOT NULL AND exec_state IS NOT NULL AND exec_state <> 'done'").run(); +} + +/** + * Sets a decision answered under an app repo to pending, or to waiting-token when its operator has no stored token set + * (a database read only: the network checks happen when the write runs). + */ +export function initExecState(db: DatabaseSync, id: string): void { + const d = db.prepare("SELECT repo, answered_by FROM main.decisions WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL").get(id) as { repo: string | null; answered_by: string | null } | undefined; + if (!d?.repo || !d.answered_by || repoIdentity(db, d.repo) !== "app") return; + const has = db.prepare("SELECT 1 FROM main.user_tokens WHERE login = ? AND status = 'ok'").get(d.answered_by); + if (has) setExecState(db, id, "pending"); + else setExecState(db, id, "waiting-token", SIGN_IN_REASON); +} + +/** Puts the waiting (and, for one decision, failed) decisions back to pending so the stages take them up again. Returns how many changed. */ +export function retryWaiting(db: DatabaseSync, login?: string): number { + const r = db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL + WHERE exec_state IN ('waiting-token', 'waiting-permission') AND applied_at IS NULL AND answer IS NOT NULL AND (? IS NULL OR answered_by = ? COLLATE NOCASE)`).run(login ?? null, login ?? null); + return Number(r.changes); +} + +export function retryDecision(db: DatabaseSync, id: string): boolean { + const r = db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL + WHERE id = ? AND exec_state IN ('waiting-token', 'waiting-permission', 'failed') AND applied_at IS NULL AND answer IS NOT NULL`).run(id); + return Number(r.changes) > 0; +} + +// ---- the lane ---------------------------------------------------------------------- + +/** What a write made as a user needs: the user's name for the audit row, and the transports that carry the token. */ +export type Lane = { + login: string; + /** The whole environment of the child: the user's token as GH_TOKEN, and none of the box's own tokens. */ + env: Record; + querier: Querier; + exec: Exec; +}; + +export type Permission = "write" | "none" | "rejected"; + +export type LaneDeps = { + vault: Pick | null; + /** The user's permission on the repo, read with the user's token. Throws when GitHub cannot answer. */ + permission?: (token: string, repo: string) => Promise; + /** Tests replace the transports. */ + transports?: (env: Record) => { querier: Querier; exec: Exec }; +}; + +export type Waiting = { state: "waiting-token" | "waiting-permission"; reason: string }; +/** `transient`: GitHub or the token refresh could not answer now; nothing is recorded and the next run tries again. */ +export type LaneResult = { lane: Lane } | Waiting | { transient: string }; + +/** The repo's permission for the token, from GitHub's `permissions` field of the repository. */ +export async function githubPermission(token: string, repo: string, apiBase = GITHUB_API): Promise { + try { + const r = (await call(apiBase, `/repos/${slugOf(repo)}`, token)) as { permissions?: { admin?: boolean; maintain?: boolean; push?: boolean } }; + const p = r.permissions; + return p?.push || p?.maintain || p?.admin ? "write" : "none"; + } catch (e) { + if (e instanceof AppError) { + if (e.status === 401) return "rejected"; + if (e.status === 403 || e.status === 404) return "none"; + } + throw e; + } +} + +const memo = new WeakMap(); +/** The vault of the secrets file (null without a registered app) and GitHub's own permission read. */ +export function defaultLaneDeps(db: DatabaseSync): LaneDeps { + let d = memo.get(db); + if (!d) { + let vault: Vault | null = null; + try { vault = openVault(db); } catch { /* no readable secrets: no token can be had */ } + d = { vault }; + memo.set(db, d); + } + return d; +} + +export function laneOf(deps: LaneDeps, login: string, token: string): Lane { + const env = withIdentityEnv({ kind: "app", token }); + const t = deps.transports?.(env); + return { + login, env, + querier: t?.querier ?? new Client(1000, env), + exec: t?.exec ?? ((cmd, args, opts) => defaultExec(cmd, args, { ...opts, env: { ...env, ...opts?.env }, replaceEnv: true })), + }; +} + +/** A usable token for the login and write access on every repo, or the reason it waits. */ +export async function resolveLane(deps: LaneDeps, login: string, repos: string[]): Promise { + if (!deps.vault) return { state: "waiting-token", reason: SIGN_IN_REASON }; + const permission = deps.permission ?? githubPermission; + let t = await deps.vault.userToken(login); + for (let attempt = 0; ; attempt++) { + if (!t.ok) return t.needsSignIn ? { state: "waiting-token", reason: SIGN_IN_REASON } : { transient: "the user token could not be refreshed now" }; + let rejected = false; + for (const repo of repos) { + let p: Permission; + try { + p = await permission(t.access, repo); + } catch (e) { + return { transient: String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 200) }; + } + if (p === "none") return { state: "waiting-permission", reason: noWriteReason(repo) }; + if (p === "rejected") { rejected = true; break; } + } + if (!rejected) return { lane: laneOf(deps, login, t.access) }; + // GitHub refused the access token as expired or revoked: one refresh, then the person has to sign in again. + if (attempt > 0) return { state: "waiting-token", reason: SIGN_IN_REASON }; + t = await deps.vault.userToken(login, t.access); + } +} + +/** + * The lane for the operator who answered `decisionId`, or null when every repo is on the box account (`legacy`): the + * caller then uses its own transports and nothing changes. Only the repos on `app` are checked. + */ +export async function laneForDecision(db: DatabaseSync, deps: LaneDeps | undefined, decisionId: string, repos: string[]): Promise { + const app = repos.filter((r) => repoIdentity(db, r) === "app"); + if (!app.length) return null; + // A decision that waits stays put until its operator signs in or someone retries it: no network call per run. + const row = db.prepare("SELECT exec_state, exec_reason FROM main.decisions WHERE id = ?").get(decisionId) as { exec_state: string | null; exec_reason: string | null } | undefined; + if (row && (row.exec_state === "waiting-token" || row.exec_state === "waiting-permission")) return { state: row.exec_state, reason: row.exec_reason ?? SIGN_IN_REASON }; + const who = identityOfDecision(db, decisionId); + if (who === "app") return { state: "waiting-token", reason: SIGN_IN_REASON }; + return resolveLane(deps ?? defaultLaneDeps(db), who.slice("user:".length), app); +} + +/** The lane for an operator acting right now (a conversation card), or null when every repo is on the box account. */ +export async function laneForOperator(db: DatabaseSync, deps: LaneDeps | undefined, login: string, repos: string[]): Promise { + const app = repos.filter((r) => repoIdentity(db, r) === "app"); + return app.length ? resolveLane(deps ?? defaultLaneDeps(db), login, app) : null; +} + +/** What GitHub says when the user's token may not do the write: 401, 403 or 404, or an integration without access. */ +export function authFailure(message: string): "waiting-token" | "waiting-permission" | null { + if (/\b401\b|bad credentials/i.test(message)) return "waiting-token"; + if (/\b(403|404)\b|not accessible by integration|must have (admin|write)|resource not accessible|could not resolve to a repository/i.test(message)) return "waiting-permission"; + return null; +} diff --git a/src/github/write.ts b/src/github/write.ts index 26bbe2f7..c6cb517e 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -460,8 +460,9 @@ export const MERGE_RECORDED_ENV = "AUTOCRAFT_MERGE_RECORDED"; * Runs the merge command for the guarded PR and records the merge or the refusal. The command gets * `OWNER/REPO PR --squash|--merge --head `, and must refuse when GitHub's head * differs from that head. Every merge command, the built-in safe-merge and any `$AUTOCRAFT_MERGE_CMD`, takes `--head` as part of this contract. + * `env`, when given, is the command's whole environment (a user's token replaces the box's). */ -export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string[]) => Promise, cmd: string, g: Guarded<"merge">, o: { method: "squash" | "merge"; extra?: string[] }, details: Details = {}, landed?: () => Promise): Promise { +export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string[], env?: Record) => Promise, cmd: string, g: Guarded<"merge">, o: { method: "squash" | "merge"; extra?: string[] }, details: Details = {}, landed?: () => Promise, env?: Record): Promise { const args = [`${slugOf(g.repo)}`, String(g.number), `--${o.method}`, ...(o.extra ?? []), "--head", g.head]; const repo = g.repo; const method: string = o.method; @@ -470,7 +471,7 @@ export async function mergeViaCommand(w: Writer, run: (cmd: string, args: string const id = begin(w, "merge", target, base); let r: CommandResult; try { - r = await run(cmd, args); + r = await run(cmd, args, env); } catch (e) { finish(w, id, base, oneLine(String((e as Error).message ?? e))); throw e; diff --git a/src/labels/github.ts b/src/labels/github.ts index fbda9a0f..fd5a399a 100644 --- a/src/labels/github.ts +++ b/src/labels/github.ts @@ -11,6 +11,8 @@ import { plannedItems } from "../core/select-items.ts"; import { ALL_LABELS, type LabelDef } from "./set.ts"; import { jobItem } from "../runner/job-items.ts"; import { ownerOf } from "../owners.ts"; +import { repoIdentity } from "../github/identity.ts"; +import { authFailure, laneForDecision, noWriteReason, setExecState, SIGN_IN_REASON, type LaneDeps } from "../github/user-lane.ts"; export const BATCH = 10; // mutations per request export const WRITES_PER_MIN = 60; // GitHub asks integrators to stay near this for content-creating writes @@ -65,7 +67,15 @@ export async function ensureLabels(client: Querier, repo: string, apply: boolean export type ApplyResult = { planned: number; labeled: number; failed: number[]; skipped: number; batches: number; dryRun: boolean }; export type ApplyOpts = { runId: string; limit?: number; apply: boolean; login?: string; /** Who asked; default: an operator at the command line. */ by?: By; wait?: Wait; log?: (s: string) => void; /** Called with the running count of items labelled, after each batch. */ - onLabeled?: (labeled: number) => void }; + onLabeled?: (labeled: number) => void; + /** The user lane's token source and transports; default: the secrets file's app. */ + lane?: LaneDeps }; + +/** The scope decision an operator answered "plugin" for this item: its answer is what adds the plugin candidate label, so its operator writes it. */ +export function pluginDecisionOf(db: DatabaseSync, repo: string, number: number): string | undefined { + return (db.prepare(`SELECT id FROM main.decisions WHERE kind = 'scope' AND repo = ? AND number = ? AND answer = 'plugin' AND answered_by IN (SELECT login FROM main.access WHERE role = 'operator') + ORDER BY answered_at DESC LIMIT 1`).get(repo, number) as { id: string } | undefined)?.id; +} /** An item the Plans give labels to, and the labels to add. */ type Todo = { number: number; add: string[] }; @@ -106,12 +116,37 @@ export async function applyLabels(db: DatabaseSync, client: Querier, repo: strin const idMap = new Map([...ids].map(([n, v]) => [n, v.id] as [number, string | null])); // Each item is guarded right before its labels are written: the Plan must still add them. const grants = new Map(); + // A label an operator's answer adds (plugin candidate) is written as that operator in a repo on the app's identity; the rest stay with the stage's own account. + const asUser = new Map(); for (const r of writable) { - const g = await guardItem(db, { repo, number: r.number }, { kind: "label" }, o.by ?? CLI_BY); - if ("refused" in g) { log(`${repo}#${r.number}: not labelled: ${g.refused}`); res.skipped++; } else grants.set(r.number, g); + const dec = repoIdentity(db, repo) === "app" ? pluginDecisionOf(db, repo, r.number) : undefined; + const g = await guardItem(db, { repo, number: r.number }, { kind: "label" }, o.by ?? CLI_BY, dec); + if ("refused" in g) { log(`${repo}#${r.number}: not labelled: ${g.refused}`); res.skipped++; } else { grants.set(r.number, g); if (dec) asUser.set(r.number, dec); } } const guarded = writable.filter((r) => grants.has(r.number)); - const done = guarded.length ? await mutate(w, client, repo, guarded, idMap, have, wait, o.runId, grants) : []; + const done: number[] = []; + const plain = guarded.filter((r) => !asUser.has(r.number)); + if (plain.length) done.push(...await mutate(w, client, repo, plain, idMap, have, wait, o.runId, grants)); + for (const r of guarded.filter((x) => asUser.has(x.number))) { + const dec = asUser.get(r.number)!; + const lr = await laneForDecision(db, o.lane, dec, [repo]); + if (lr && !("lane" in lr)) { + if (!("transient" in lr)) { setExecState(db, dec, lr.state, lr.reason); log(`${repo}#${r.number}: waiting: ${lr.reason}`); } + res.skipped++; + continue; + } + if (lr) setExecState(db, dec, "pending"); + try { + done.push(...await addLabels(w, lr ? lr.lane.querier : client, repo, + [{ number: r.number, id: idMap.get(r.number)!, labelIds: r.add.map((a) => have.labels.get(a.toLowerCase())!), names: r.add, g: grants.get(r.number)! }], (f) => retrying(f, wait), { run: o.runId })); + } catch (e) { + const why = String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 300); + const denied = lr ? authFailure(why) : null; + if (denied) { setExecState(db, dec, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(repo)); res.skipped++; continue; } + if (lr) setExecState(db, dec, "failed", why); + throw e; + } + } for (const r of guarded) if (!done.includes(r.number)) res.failed.push(r.number); const ok = guarded.filter((r) => done.includes(r.number)); if (ok.length) { diff --git a/src/merge/index.ts b/src/merge/index.ts index c8db1982..159efa1d 100644 --- a/src/merge/index.ts +++ b/src/merge/index.ts @@ -37,6 +37,7 @@ export { buildQueue, countStates, QUEUE_STATES, type QueueEntry, type QueueState import { envVar } from "../env.ts"; import { effectiveCi, optionalChecks } from "../optional-checks.ts"; import { jobItem } from "../runner/job-items.ts"; +import { authFailure, laneForDecision, markExecDone, noWriteReason, setExecState, SIGN_IN_REASON, type Lane, type LaneDeps } from "../github/user-lane.ts"; import { ownerOf } from "../owners.ts"; /** Name of the built-in guarded merge (`autocraft safe-merge`); any other `$AUTOCRAFT_MERGE_CMD` is run as an external command that must accept `--head ` and refuse when the PR head differs. */ @@ -53,8 +54,10 @@ export type CommandResult = { code: number; stdout: string; stderr: string }; export type MergeDeps = { querier: Querier; /** Runs the merge command; throws only when it can't be started. */ - run: (cmd: string, args: string[]) => Promise; + run: (cmd: string, args: string[], env?: Record) => Promise; now: () => Date; + /** The user lane's token source and transports; default: the secrets file's app. */ + lane?: LaneDeps; /** `$AUTOCRAFT_MERGE_CMD`, default the built-in `safe-merge`. */ mergeCommand: string; }; @@ -86,9 +89,9 @@ export type MergeSummary = { asked: string[]; }; -export function spawnRun(cmd: string, args: string[], env?: Record): Promise { +export function spawnRun(cmd: string, args: string[], env?: Record, replaceEnv = false): Promise { return new Promise((resolve, reject) => { - const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: env ? { ...process.env, ...env } : process.env }); + const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], env: env ? (replaceEnv ? env : { ...process.env, ...env }) : process.env }); let stdout = "", stderr = ""; p.stdout.on("data", (d) => (stdout += d)); p.stderr.on("data", (d) => (stderr += d)); @@ -98,8 +101,9 @@ export function spawnRun(cmd: string, args: string[], env?: Record { - return cmd === DEFAULT_MERGE_COMMAND ? spawnRun(process.execPath, ["--no-warnings", CLI, "safe-merge", ...args], { [MERGE_RECORDED_ENV]: "1" }) : spawnRun(cmd, args); +export function mergeRun(cmd: string, args: string[], env?: Record): Promise { + // With `env` (a user's token set) the child gets exactly that environment: no box token is left in it. + return cmd === DEFAULT_MERGE_COMMAND ? spawnRun(process.execPath, ["--no-warnings", CLI, "safe-merge", ...args], { ...env, [MERGE_RECORDED_ENV]: "1" }, !!env) : spawnRun(cmd, args, env, !!env); } export function defaultDeps(): MergeDeps { @@ -313,6 +317,17 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line if (!mergeApprovalOf(db, repo)) { log(` merging in ${repo} is no longer approved; stopping`); break; } if (mergeHeld(db, repo, e.number)) { log(` ${refOf(e)}: merge held since the queue was read; skipped`); continue; } if (backlogHeld(db, repo, e.number) || duplicateHeld(db, repo, e.number)) { log(` ${refOf(e)}: held since the queue was read; skipped`); continue; } + // An operator's Merge answer in a repo on the app's identity is carried out as that operator, with their token. + let lane: Lane | null = null; + if (e.path === "operator" && e.decisionId) { + const lr = await laneForDecision(db, d.lane, e.decisionId, [repo]); + if (lr && !("lane" in lr)) { + if (!("transient" in lr)) setExecState(db, e.decisionId, lr.state, lr.reason); + log(` ${refOf(e)}: ${"transient" in lr ? `not merged yet: ${lr.transient}` : `waiting: ${lr.reason}`}`); + continue; + } + if (lr) { lane = lr.lane; setExecState(db, e.decisionId, "pending"); } + } summary.attempted.push(refOf(e)); seen = null; const [ch] = await refreshChecks(db, d.querier, repo, [e.number]); @@ -361,9 +376,18 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line log(` ${refOf(e)}: not merged: ${g.refused}`); continue; } - const r = await mergeViaCommand(w, d.run, d.mergeCommand, g, { method, extra: allowFailedArgs(db, repo, d.mergeCommand) }, { run: runId, head: e.head, path: e.path }); + const r = await mergeViaCommand(w, d.run, d.mergeCommand, g, { method, extra: allowFailedArgs(db, repo, d.mergeCommand) }, { run: runId, head: e.head, path: e.path }, undefined, lane?.env); if (r.code !== 0) { const why = oneLine(r.stderr) || oneLine(r.stdout) || `exit code ${r.code}`; + const denied = lane && e.decisionId ? authFailure(why) : null; + if (denied) { + // The user's token may not merge: wait for their access. No refusal is recorded, so the PR stays queued. + setExecState(db, e.decisionId!, denied, denied === "waiting-token" ? SIGN_IN_REASON : noWriteReason(repo)); + log(` ${refOf(e)}: waiting: ${why}`); + summary.attempted.pop(); + continue; + } + if (lane && e.decisionId) setExecState(db, e.decisionId, "failed", why); refuse(e, method, `${d.mergeCommand}: ${why}`); continue; } @@ -377,6 +401,7 @@ export async function runMerge(db: DatabaseSync, params: MergeParams, log: (line params.onMerged?.(summary.merged.length); log(` ${refOf(e)}: merged (${method})`); } + markExecDone(db); log(`merge ${repo}: ${summary.merged.length} merged, ${summary.refused.length} refused, ${summary.asked.length} asked; run ${runId}`); return summary; } diff --git a/src/mirror.ts b/src/mirror.ts index 09007c12..8e51ce5e 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -85,8 +85,12 @@ export class Client { resetAt: Date | null = null; spent = 0; - constructor(reserve: number) { + /** The child's whole environment when set (a user's token replaces the box's); the process environment otherwise. */ + #env: Record | undefined; + + constructor(reserve: number, env?: Record) { this.reserve = reserve; + this.#env = env; } async sleepUntilReset(why: string): Promise { @@ -98,7 +102,7 @@ export class Client { private run(query: string, variables: object): { data?: Node; errors: Node[]; text: string; failed: boolean; stderr: string } { const p = spawnSync("gh", ["api", "graphql", "--input", "-"], { - input: JSON.stringify({ query, variables }), encoding: "utf8", timeout: 120_000, maxBuffer: 256 << 20, + input: JSON.stringify({ query, variables }), encoding: "utf8", timeout: 120_000, maxBuffer: 256 << 20, ...(this.#env ? { env: this.#env } : {}), }); if (p.error) throw new Transient("timeout"); let json: Node = {}; diff --git a/src/schema.sql b/src/schema.sql index 523b9a2d..fe407334 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -153,7 +153,8 @@ CREATE TABLE IF NOT EXISTS decisions ( summary TEXT, summary_by TEXT, summary_at TEXT, -- AI summary of the item or batch, by which model, when adopted_opinion TEXT, -- decision_opinions.id when the answer adopted an opinion snoozed_by TEXT, -- operator who snoozed the open question - snoozed_at TEXT -- the question is snoozed while the item has no activity after this (SNOOZED_SQL) + snoozed_at TEXT, -- the question is snoozed while the item has no activity after this (SNOOZED_SQL) + exec_state TEXT, exec_reason TEXT -- the answer's GitHub write: pending | waiting-token | waiting-permission | done | failed, and why it waits or failed ); CREATE INDEX IF NOT EXISTS decisions_open ON decisions(answer, kind, repo); CREATE INDEX IF NOT EXISTS decisions_asked ON decisions(answer, asked_at); diff --git a/test/user-lane.test.ts b/test/user-lane.test.ts new file mode 100644 index 00000000..e08d1c44 --- /dev/null +++ b/test/user-lane.test.ts @@ -0,0 +1,59 @@ +// The user lane: an answered close in a repo on the app's identity is written as the answering operator with their +// token; without a token it waits and writes nothing. Under the default (legacy) setting nothing changes. +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { runAct } from "../src/act/index.ts"; +import { setRepoIdentity } from "../src/github/identity.ts"; +import { retryWaiting, type LaneDeps } from "../src/github/user-lane.ts"; +import { OPERATOR, world, type World } from "./world-db.ts"; + +const quiet = () => {}; +let current: World | null = null; +const fresh = (): World => (current = world().repo()); +afterEach(() => current?.close()); + +const askedAndAnswered = async (w: World) => { + const asked = await runAct(w.db, { repo: "app", dryRun: false }, quiet, w.gh.actDeps()); + w.answerDecision(asked.asked[0]!, "close"); + return asked.asked[0]!; +}; +const execOf = (w: World, id: string) => w.rows("SELECT exec_state AS s, exec_reason AS r FROM decisions WHERE id = ?", id)[0] as { s: string | null; r: string | null }; + +test("legacy repos close as before; an app repo without the operator's token waits and writes nothing, then closes as the operator after a sign-in", async () => { + // legacy: the box transports close it and no state is recorded + const a = fresh().pr(1).review(1, { verdict: "close", reason: "Does not match the reference app" }); + const idA = await askedAndAnswered(a); + assert.deepEqual((await runAct(a.db, { repo: "app", dryRun: false }, quiet, a.gh.actDeps())).done, ["app#1"]); + assert.deepEqual(a.gh.writes.map((x) => x.kind), ["comment", "close"]); + assert.deepEqual(execOf(a, idA), { s: null, r: null }); + a.close(); + + // app: no token for the answering operator + const w = fresh().pr(1).review(1, { verdict: "close", reason: "Does not match the reference app" }); + setRepoIdentity(w.db, "op", "app", "app"); + const id = await askedAndAnswered(w); + const userQuerier = { query: async (_q: string, _v?: object): Promise> => ({}), spent: 0, remaining: null as number | null }; + let token: string | null = null; + const lane: LaneDeps = { + vault: { userToken: async () => (token ? { ok: true, access: token } : { ok: false, needsSignIn: true, why: "no-token" }) }, + permission: async () => "write", + transports: () => ({ querier: userQuerier, exec: async () => ({ code: 0, stdout: "", stderr: "" }) }), + }; + const deps = { ...w.gh.actDeps(), lane }; + const waiting = await runAct(w.db, { repo: "app", dryRun: false }, quiet, deps); + assert.deepEqual(waiting.done, []); + assert.equal(w.gh.writes.length, 0, "the box account writes nothing in a repo on the app's identity"); + assert.deepEqual(execOf(w, id), { s: "waiting-token", r: "Sign in to let AutoCraft finish this as you" }); + + // The operator authorizes: the decision is pending again and the next run uses their lane (its own querier, not the box's). + token = "user-token"; + assert.equal(retryWaiting(w.db, OPERATOR), 1); + assert.deepEqual(execOf(w, id), { s: "pending", r: null }); + const queries: string[] = []; + userQuerier.query = async (q: string) => { queries.push(q.includes("closeIssue") || q.includes("closePullRequest") ? "close" : q.includes("addComment") ? "comment" : "read"); return q.includes("issueOrPullRequest") ? { repository: { issueOrPullRequest: { __typename: "PullRequest", id: "PR_1", state: "OPEN", headRefOid: (w.rows("SELECT head_oid FROM items WHERE number = 1")[0] as { head_oid: string }).head_oid } } } : {}; }; + await runAct(w.db, { repo: "app", dryRun: false }, quiet, deps); + assert.equal(w.gh.writes.length, 0, "still nothing through the box's transports"); + assert.ok(queries.includes("comment") && queries.includes("close"), `the user's transports made the writes: ${queries.join(",")}`); + const row = w.rows("SELECT details FROM audit WHERE action = 'act-close'")[0] as { details: string }; + assert.equal((JSON.parse(row.details) as { identity: string }).identity, `user:${OPERATOR}`); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index d0f13c5d..c6ef66d2 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -108,6 +108,8 @@ export interface Api { forItem(repo: RepoName, number: number, kind?: DecisionKind): Promise; answer(id: string, input: AnswerInput): Promise; undo(id: string): Promise; + /** Operator: runs the GitHub write of a waiting or failed answer again. */ + retry(id: string): Promise; /** Operator: clear a Backlog answer so the decision is open again. */ reopen(id: string): Promise; /** Operator: snooze (`on`) or wake an open decision. */ diff --git a/web/src/api/http.ts b/web/src/api/http.ts index a97c9c83..f4b6d8fa 100644 --- a/web/src/api/http.ts +++ b/web/src/api/http.ts @@ -115,6 +115,7 @@ export function createHttpApi(): Api { forItem: (repo, number, kind) => get(`/api/items/${encodeURIComponent(repo)}/${encodeURIComponent(String(number))}/decision${qs({ kind })}`), answer: (id, input) => post(dec(id, "/answer"), input), undo: (id) => post(dec(id, "/undo")), + retry: (id) => post(dec(id, "/retry")), snooze: (id, on) => post(dec(id, "/snooze"), { on }), reopen: (id) => post(dec(id, "/reopen")), feedback: (id, input) => post(dec(id, "/feedback"), input), diff --git a/web/src/api/mock/adminMock.ts b/web/src/api/mock/adminMock.ts index 6a32012d..48248bbb 100644 --- a/web/src/api/mock/adminMock.ts +++ b/web/src/api/mock/adminMock.ts @@ -391,7 +391,7 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { // The mock shows the registered app; ?unregistered shows the registration form. const registered = !appRemoved && (typeof location === "undefined" || !location.search.includes("unregistered")); const status: GithubAppStatus = { - configured: registered, loginMode: "oauth", canRegister: true, defaultName: "AutoCraft", csrf: "mock", + configured: registered, loginMode: "oauth", canRegister: true, defaultName: "AutoCraft", csrf: "mock", authorized: registered ? false : null, app: registered ? { id: "1234567", slug: "autocraft-demo", name: "AutoCraft", installUrl: "https://github.com/apps/autocraft-demo/installations/new", transferUrl: "https://github.com/settings/apps/autocraft-demo/advanced" } : null, links: [...setupLinks], installations: registered ? [{ owner: "glasswing", selection: "selected", repos: ["glasswing/photocraft", "glasswing/designcraft", "glasswing/filmcraft"] }] : [], diff --git a/web/src/api/mock/fixtures.ts b/web/src/api/mock/fixtures.ts index 8e7cdbe1..12a2678d 100644 --- a/web/src/api/mock/fixtures.ts +++ b/web/src/api/mock/fixtures.ts @@ -12,6 +12,7 @@ import type { DecisionKind, Preapproval, DecisionOption, + ExecState, Item, Progress, RelatedItem, @@ -157,6 +158,8 @@ interface Seed { answer?: [string, string, number, boolean, string?, number?]; // answer, by, hoursAgo, applied, note, index of the adopted opinion opinions?: [string, string | null, string | null, number][]; // login, option, note, minutes ago docket?: string; + /** An answer whose GitHub write has not run: where it stands and why. */ + exec?: [ExecState, string | null]; } const SEEDS: Seed[] = [ @@ -549,6 +552,59 @@ const SEEDS: Seed[] = [ size: [344, 61, 5], cls: [["haiku", "missing feature", "yes"], ["jev", "missing feature", "yes"]], }, + // answered, the GitHub write waits or failed + { + kind: "close", + repo: "texturecraft", + number: 230, + title: "Replace the brush engine with a shader pipeline", + question: "Close this PR?", + context: [], + facts: ["+3,120 −2,004 · 22 files", "author: 0 merged"], + options: [ + { key: "close", label: "Close with note" }, + { key: "hold", label: "Hold" }, + { key: "keep", label: "Keep open" }, + ], + recommended: "close", + publicText: "Thanks for the work here. A replacement of the whole brush engine is more than we can review as one PR.", + ageH: 5, + author: "gridlock-9", + answer: ["close", "ochre-fox", 1, false], + exec: ["waiting-token", "Sign in to let AutoCraft finish this as you"], + }, + { + kind: "merge", + repo: "filmcraft", + number: 3362, + title: "Show the frame counter while scrubbing", + question: "Merge now?", + context: [], + facts: ["+64 −9 · 3 files", "CI passing · mergeable"], + options: [ + { key: "merge", label: "Merge" }, + { key: "hold", label: "Hold" }, + ], + recommended: "merge", + ageH: 8, + author: "larkspur-dev", + answer: ["merge", "kiri-n", 2, false], + exec: ["waiting-permission", "You have no write access to storytold/filmcraft"], + }, + { + kind: "scope", + repo: "designcraft", + number: 2251, + title: "Export artboards as animated SVG", + question: "Is animated SVG export in scope?", + context: [], + facts: ["+410 −12 · 6 files"], + ...spread(scopeOpts("close")), + ageH: 12, + author: "kiln-and-reed", + answer: ["close", "ochre-fox", 3, false], + exec: ["failed", "GitHub answered 502 while closing the item"], + }, // answered { kind: "scope", @@ -771,6 +827,7 @@ function toDecision(s: Seed): Decision { answeredBy: s.answer?.[1] ?? null, answeredAt: s.answer ? iso(s.answer[2] * H) : null, appliedAt: s.answer?.[3] ? iso(s.answer[2] * H - 20 * M) : null, + exec: s.exec ? { state: s.exec[0], reason: s.exec[1] } : null, opinions, adoptedOpinion: s.answer?.[5] !== undefined ? opinions[s.answer[5]] : null, exceptions: [], diff --git a/web/src/api/mock/mockApi.ts b/web/src/api/mock/mockApi.ts index a2cff3c5..84b8bf4e 100644 --- a/web/src/api/mock/mockApi.ts +++ b/web/src/api/mock/mockApi.ts @@ -96,7 +96,7 @@ export function createMockApi(): Api { }; const settle = (d: Decision, answer: string, note: string | null, adoptedOpinion: Decision["adoptedOpinion"], exceptions: Decision["exceptions"] = []) => - Object.assign(d, { answer, answerNote: note, exceptions, answeredBy: me.login, answeredAt: nowIso(), adoptedOpinion, claim: null, undoable: true }); + Object.assign(d, { answer, answerNote: note, exceptions, answeredBy: me.login, answeredAt: nowIso(), adoptedOpinion, claim: null, undoable: true, exec: null }); return { me: () => wait(me, 10), @@ -125,6 +125,13 @@ export function createMockApi(): Api { changed(); return wait(d, 30); }, + async retry(id) { + const d = find(id); + requireOperator(d); + if (d.exec) Object.assign(d, { exec: { state: "pending", reason: null } }); + changed(); + return wait(d, 30); + }, async undo(id) { const d = find(id); requireOperator(d); diff --git a/web/src/api/types.ts b/web/src/api/types.ts index bceb8fe3..b8dfcbca 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -94,6 +94,8 @@ export interface DuplicateMember { adds: string[]; } +export type ExecState = "pending" | "waiting-token" | "waiting-permission" | "done" | "failed"; + export interface Decision { id: string; kind: DecisionKind; @@ -138,6 +140,8 @@ export interface Decision { answeredBy: string | null; answeredAt: string | null; appliedAt: string | null; + /** The GitHub write of the answer while it is not done (repos on the app's identity only): waiting for the answering operator's sign-in or access, failed, or pending. null otherwise. */ + exec: { state: ExecState; reason: string | null } | null; /** The opinion the operator adopted as the answer, if any. */ adoptedOpinion: Opinion | null; opinions: Opinion[]; @@ -857,6 +861,8 @@ export interface GithubAppStatus { defaultName: string; /** The session's CSRF token, for the registration form. */ csrf: string; + /** The signed-in operator has let the app act as them; null when no app is registered. */ + authorized: boolean | null; app: { id: string; slug: string; name: string | null; installUrl: string; transferUrl: string } | null; /** Each account the app is installed on, with the repos it covers. */ installations: { owner: string; selection: "all" | "selected"; repos: string[] }[]; diff --git a/web/src/modules/admin/githubAppViews.tsx b/web/src/modules/admin/githubAppViews.tsx index 6d412ca6..1bc5fa70 100644 --- a/web/src/modules/admin/githubAppViews.tsx +++ b/web/src/modules/admin/githubAppViews.tsx @@ -13,6 +13,7 @@ import { Block } from "../../ui/molecules/Block"; import { ConfirmButton } from "../../ui/molecules/ConfirmButton"; import { Facts } from "../../ui/molecules/Facts"; import { Page } from "../../ui/organisms/Page"; +import { authorizeHref } from "../decisions/ExecLine"; const LOGIN_MODE = { oauth: "OAuth App", "github-app": "GitHub App" } as const; @@ -60,9 +61,13 @@ function AppBlock({ s, onChange }: { s: GithubAppStatus; onChange: () => void }) ["Slug", {s.app.slug}], ["App id", {s.app.id}], ["Sign-in", LOGIN_MODE[s.loginMode]], + ["Acts as you", s.authorized ? "Authorized" : "Not authorized"], ]} />
+ + {s.authorized ? "Authorize again" : "Authorize AutoCraft to act as you"} + Install Transfer void remove()} /> diff --git a/web/src/modules/decisions/DecisionDetail.tsx b/web/src/modules/decisions/DecisionDetail.tsx index 3d9e1889..f37c1fe5 100644 --- a/web/src/modules/decisions/DecisionDetail.tsx +++ b/web/src/modules/decisions/DecisionDetail.tsx @@ -16,6 +16,7 @@ import { } from "../../lib/format"; import { TimeAgo } from "../../ui/atoms/TimeAgo"; import { ClaimPill, ClassifierLines, Disclosure, Facts, KindTag, RelatedList } from "./parts"; import { Refs } from "./Refs"; +import { ExecLine } from "./ExecLine"; import { AnswerNotice } from "./AnswerNotice"; import { DuplicateGroup, RiskList } from "./Group"; import { localActions, ordered, refOf, useDecisionFilter, useDecisionList, useLocal, usePinned, useSelection, useUndo, type AnswerEntry } from "./state"; @@ -348,6 +349,7 @@ export function AnsweredState({ d, canUndo }: { d: Decision; canUndo: boolean }) {d.adoptedOpinion ? `, using ${d.adoptedOpinion.login}'s answer` : ""} · {closed ? "" : ` · ${d.appliedAt ? "applied" : "not applied yet"}`} {d.answerNote && “{d.answerNote}”} + {backlog && canUndo && ( {write.error && {write.error}} diff --git a/web/src/modules/decisions/ExecLine.tsx b/web/src/modules/decisions/ExecLine.tsx new file mode 100644 index 00000000..0f3713ea --- /dev/null +++ b/web/src/modules/decisions/ExecLine.tsx @@ -0,0 +1,44 @@ +import { ArrowClockwiseIcon, HourglassIcon, KeyIcon, WarningCircleIcon } from "@phosphor-icons/react"; +import { useApi } from "../../api/client"; +import type { Decision } from "../../api/types"; +import { Button } from "../../ui/atoms/Button"; +import { cn } from "../../ui/cn"; +import { useWrite } from "../../lib/hooks"; + +/** Starts the GitHub App user authorization for the signed-in operator and returns to this page. The session is not touched. */ +export const authorizeHref = (): string => `/auth/authorize-app?${new URLSearchParams({ return_to: window.location.pathname + window.location.search })}`; + +const TONE = { pending: "text-ink/55", "waiting-token": "text-warn", "waiting-permission": "text-warn", failed: "text-bad", done: "text-ink/55" } as const; + +/** + * Where the GitHub write of an answer stands while it is not done: why it waits, with the actions that unblock it. + * Shown under the answer on the decision and the item, and under the row in the answered list. + */ +export function ExecLine({ d, canRetry, compact }: { d: Decision; canRetry: boolean; compact?: boolean }) { + const api = useApi(); + const write = useWrite(); + const exec = d.exec; + if (!exec || exec.state === "done") return null; + const Icon = exec.state === "pending" ? HourglassIcon : WarningCircleIcon; + const text = exec.reason ?? "Waiting to run"; + return ( +
e.stopPropagation()}> + + + {text} + + {canRetry && exec.state === "waiting-token" && ( + + + Authorize AutoCraft to act as you + + )} + {canRetry && exec.state !== "pending" && ( + + )} + {write.error && {write.error}} +
+ ); +} diff --git a/web/src/modules/decisions/InboxList.tsx b/web/src/modules/decisions/InboxList.tsx index be2f38a1..6d78b705 100644 --- a/web/src/modules/decisions/InboxList.tsx +++ b/web/src/modules/decisions/InboxList.tsx @@ -14,6 +14,7 @@ import { ItemRef } from "../../ui/molecules/ItemRef"; import { ClaimPill, KIND_ICON } from "./parts"; import { canActOn } from "./DecisionDetail"; import { AnswerNotice } from "./AnswerNotice"; +import { ExecLine } from "./ExecLine"; import { KIND_LABEL, KINDS, localActions, ordered, useDecisionFilter, useDecisionList, useLocal, useSelection, useUndo } from "./state"; import { useNow } from "../../lib/useNow"; import { itemPath } from "../../lib/links"; @@ -164,6 +165,7 @@ function Row({ d, canUndo, active, checked, mine, onOpen, activeRef }: { d: Deci {d.answer && d.undoable && canUndo && }
+ ); From ea512be5d2c0c34be7342fe131cda32dc78020a9 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:53:33 +0000 Subject: [PATCH 2/2] Show the authorize action to any operator on a waiting-token decision --- web/src/modules/decisions/ExecLine.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/web/src/modules/decisions/ExecLine.tsx b/web/src/modules/decisions/ExecLine.tsx index 0f3713ea..5b570f0c 100644 --- a/web/src/modules/decisions/ExecLine.tsx +++ b/web/src/modules/decisions/ExecLine.tsx @@ -4,6 +4,7 @@ import type { Decision } from "../../api/types"; import { Button } from "../../ui/atoms/Button"; import { cn } from "../../ui/cn"; import { useWrite } from "../../lib/hooks"; +import { useUser } from "../../shell/UserContext"; /** Starts the GitHub App user authorization for the signed-in operator and returns to this page. The session is not touched. */ export const authorizeHref = (): string => `/auth/authorize-app?${new URLSearchParams({ return_to: window.location.pathname + window.location.search })}`; @@ -17,6 +18,7 @@ const TONE = { pending: "text-ink/55", "waiting-token": "text-warn", "waiting-pe export function ExecLine({ d, canRetry, compact }: { d: Decision; canRetry: boolean; compact?: boolean }) { const api = useApi(); const write = useWrite(); + const operator = useUser().role === "operator"; const exec = d.exec; if (!exec || exec.state === "done") return null; const Icon = exec.state === "pending" ? HourglassIcon : WarningCircleIcon; @@ -27,7 +29,7 @@ export function ExecLine({ d, canRetry, compact }: { d: Decision; canRetry: bool {text} - {canRetry && exec.state === "waiting-token" && ( + {operator && exec.state === "waiting-token" && ( Authorize AutoCraft to act as you