From 561f3847ae25dd154f52ec3d8b576a8092d96aa2 Mon Sep 17 00:00:00 2001 From: Hyo Date: Sat, 21 Nov 2026 00:31:27 +0900 Subject: [PATCH] fix: post auth 2.0 follow-ups for connect, usage and cli - Connect page offers Install to users without an installation and keeps Verify GitHub access as a secondary action; screen choice moved to a tested resolveConnectScreen - Usage shows whether saved keys work, are broken or are paused by an outage, and waits for own-key cost before rendering - Consent page explains why a GitHub sign-in failed - CLI github verify reuses the redirect check; install hints mention verify - Ticket usage hides lifecycle-only tickets; long-context price note; shared action label helper; accessible request count - Tests for session auth, sign-in redirects and CLI port fallback - Docs updated for @convex-dev/auth 2.0 --- .claude/commands/convex-function.md | 4 +- .claude/guides/convex-patterns.md | 2 +- AGENTS.md | 2 +- convex/_ai/config.ts | 5 +- convex/github/accessVerification.ts | 5 +- convex/tokenUsage/query.ts | 13 ++- convex/tokenUsage/usageSummary.ts | 15 +-- docs/github-app-setup.md | 4 +- packages/cli/docs/REFERENCE.md | 8 +- packages/cli/src/auth.ts | 9 +- packages/cli/src/commands.ts | 9 +- packages/cli/src/projects.ts | 2 +- packages/cli/test/auth.test.mjs | 37 +++++++ packages/cli/test/commands.test.mjs | 7 +- src/i18n/locales/en.json | 23 ++-- src/i18n/locales/ja.json | 23 ++-- src/i18n/locales/ko.json | 23 ++-- src/pages/legal/consent.tsx | 21 +++- src/pages/profile/ProviderKeysSection.tsx | 27 +++-- src/pages/repositories/connect.tsx | 104 +++++++++--------- src/pages/repositories/connectFlow.ts | 40 +++++++ src/pages/tickets/ActionUsageChip.tsx | 8 +- src/pages/tickets/[id].tsx | 9 +- src/pages/usage/UserKeyUsageSection.tsx | 16 ++- src/pages/usage/index.tsx | 7 +- src/utils/actionTypes.ts | 10 +- .../repositories/connectIdentity.test.ts | 2 +- test/convex/setup.ts | 2 + test/convex/tokenUsage/userKeyUsage.test.ts | 4 +- test/convex/users/sessionAuth.test.ts | 91 +++++++++++++++ test/helpers/auth.ts | 2 - test/pages/legalConsentPage.test.ts | 13 +++ test/pages/repositoryConnectFlow.test.ts | 60 ++++++++++ 33 files changed, 453 insertions(+), 154 deletions(-) create mode 100644 test/convex/users/sessionAuth.test.ts diff --git a/.claude/commands/convex-function.md b/.claude/commands/convex-function.md index 2738049..b5153e3 100644 --- a/.claude/commands/convex-function.md +++ b/.claude/commands/convex-function.md @@ -18,7 +18,7 @@ convex/[feature]/ ```typescript import { query } from "../_generated/server"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; export const myQuery = query({ args: { @@ -45,7 +45,7 @@ export const myQuery = query({ ```typescript import { mutation } from "../_generated/server"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; export const myMutation = mutation({ args: { diff --git a/.claude/guides/convex-patterns.md b/.claude/guides/convex-patterns.md index 73a120a..2558dd2 100644 --- a/.claude/guides/convex-patterns.md +++ b/.claude/guides/convex-patterns.md @@ -167,7 +167,7 @@ const enrichedLogs = logs.map((log) => { ```typescript // convex/admin/utils.ts -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import type { Id } from "../_generated/dataModel"; import type { MutationCtx, QueryCtx } from "../_generated/server"; diff --git a/AGENTS.md b/AGENTS.md index e486174..5b6482a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,7 +45,7 @@ Gitdog is an AI-powered GitHub assistant for repository automation. It is built - Do not create barrel export files in the `convex/` root. - Organize functions in subdirectories with `query.ts`, `mutation.ts`, and `action.ts`. - Use the new Convex function syntax with validators. -- Authenticate with `getAuthUserId(ctx)` from `@convex-dev/auth/server`. +- Authenticate with `getAuthUserId(ctx)` from `convex/_utils/auth.ts`; it works in queries, mutations and actions. - Use dot-notation API references such as `api.repositories.query.list`. - Use `.withIndex()` instead of `.filter()` for database queries. - Avoid unbounded `.collect()`; use `paginatedCollect()` for large reads. diff --git a/convex/_ai/config.ts b/convex/_ai/config.ts index 3b9f788..d229992 100644 --- a/convex/_ai/config.ts +++ b/convex/_ai/config.ts @@ -185,6 +185,8 @@ export type UserKeyModel = { // USD per 1M tokens, so owners can compare models before choosing one. inputPer1M: number; outputPer1M: number; + // Requests with more input tokens than this are billed at a higher rate. + longContextInputTokens?: number; }; const EFFORTS: readonly ModelEffort[] = ["low", "medium", "high"]; @@ -193,7 +195,7 @@ function userKeyOption( modelId: string, defaultEffort: ModelEffort, ): UserKeyModel { - const { name, inputPer1M, outputPer1M } = CHAT_MODELS[modelId]; + const { name, inputPer1M, outputPer1M, longContext } = CHAT_MODELS[modelId]; return { modelId, name, @@ -201,6 +203,7 @@ function userKeyOption( defaultEffort, inputPer1M, outputPer1M, + ...(longContext && { longContextInputTokens: longContext.inputTokens }), }; } diff --git a/convex/github/accessVerification.ts b/convex/github/accessVerification.ts index 9a387e5..e734854 100644 --- a/convex/github/accessVerification.ts +++ b/convex/github/accessVerification.ts @@ -20,8 +20,9 @@ export const ACCESS_VERIFICATION_TTL_MS = 10 * 60 * 1_000; const DEFAULT_RETURN_PATH = "/repositories/connect"; /** - * Where GitHub sends the user back: the same site as sign-in's OAuth - * callback, so one GitHub App lists both under one host. + * Where GitHub sends the user back. Sign-in's callback always uses + * CONVEX_SITE_URL; a CUSTOM_AUTH_SITE_URL moves only this one, and the + * GitHub App must list both. */ export function accessVerificationRedirectUri(): string | null { const site = diff --git a/convex/tokenUsage/query.ts b/convex/tokenUsage/query.ts index 325da98..8099625 100644 --- a/convex/tokenUsage/query.ts +++ b/convex/tokenUsage/query.ts @@ -372,8 +372,9 @@ export const getUserKeyUsage = query({ return { ...usage, actionType: action.actionType, - // Deleted tickets keep their cost but no longer link anywhere. - ticketId: ticket.deletedAt ? null : ticket._id, + // Hidden tickets keep their cost but no longer link anywhere. + ticketId: + ticket.deletedAt || ticket.githubLifecycleOnly ? null : ticket._id, ticketType: ticket.ticketType, githubRepo: ticket.githubRepo, githubNumber: ticket.githubNumber, @@ -402,7 +403,13 @@ export const getTicketUsage = query({ const userId = await getAuthUserId(ctx); if (!userId) return []; const ticket = await ctx.db.get(args.ticketId); - if (!ticket || ticket.userId !== userId || ticket.deletedAt) return []; + if ( + !ticket || + ticket.userId !== userId || + ticket.deletedAt || + ticket.githubLifecycleOnly === true + ) + return []; const actions = await ctx.db .query("ticketActions") diff --git a/convex/tokenUsage/usageSummary.ts b/convex/tokenUsage/usageSummary.ts index 1ae9ae7..226ecbd 100644 --- a/convex/tokenUsage/usageSummary.ts +++ b/convex/tokenUsage/usageSummary.ts @@ -55,11 +55,7 @@ export function summarizeUserKeyUsage(rows: UsageRow[]) { const models = new Map }>(); const repositories = new Map< string, - { - repositoryId?: Id<"repositories">; - costCents: number; - actionIds: Set; - } + { repositoryId?: Id<"repositories">; costCents: number } >(); const actions = new Map(); @@ -83,10 +79,8 @@ export function summarizeUserKeyUsage(rows: UsageRow[]) { const repository = repositories.get(repositoryKey) ?? { ...(row.repositoryId ? { repositoryId: row.repositoryId } : {}), costCents: 0, - actionIds: new Set(), }; repository.costCents += row.baseCostCents; - if (row.ticketActionId) repository.actionIds.add(row.ticketActionId); repositories.set(repositoryKey, repository); if (!row.ticketActionId) continue; @@ -108,12 +102,7 @@ export function summarizeUserKeyUsage(rows: UsageRow[]) { models: [...models.values()] .map(({ actionIds, ...model }) => ({ ...model, actions: actionIds.size })) .sort((a, b) => b.costCents - a.costCents), - repositories: [...repositories.values()].map( - ({ actionIds, ...repository }) => ({ - ...repository, - actions: actionIds.size, - }), - ), + repositories: [...repositories.values()], actions: [...actions.values()].sort((a, b) => b.lastAt - a.lastAt), }; } diff --git a/docs/github-app-setup.md b/docs/github-app-setup.md index ad17077..85e4fa2 100644 --- a/docs/github-app-setup.md +++ b/docs/github-app-setup.md @@ -282,10 +282,10 @@ For production deployment: ```text User Login Flow: -GitHub App → convex/auth.ts → User session created +GitHub OAuth → convex/auth.ts (@convex-dev/auth 2.0) → User session created Repository Access Flow: -GitHub OAuth login → Short-lived `/user/installations` attestation → Recover personal installations +Verify GitHub access (`/github/access/callback`) → Short-lived `/user/installations` attestation → Recover personal installations Organization installation/update → Signed webhook → Save installation Setup callback → Coordinate verification and repository reconnect UI User requests repos → convex/github/action.ts → Generate JWT → Get installation token → Fetch repos diff --git a/packages/cli/docs/REFERENCE.md b/packages/cli/docs/REFERENCE.md index bdbc622..503b410 100644 --- a/packages/cli/docs/REFERENCE.md +++ b/packages/cli/docs/REFERENCE.md @@ -11,7 +11,8 @@ For example: `npx gitdog@latest login`. An optional global installation with `gitdog login` opens GitHub in your browser. Use a browser on the same computer, or pass `--no-browser` to open the printed URL yourself. Ctrl+C cancels the entire -sign-in flow. The browser callback times out after five minutes. When sign-in +sign-in flow. The browser callback listens on the first free loopback port from +41721 to 41725 and times out after five minutes. When sign-in finishes, your browser shows the result on Gitdog and the tab can be closed. ## Projects, like Firebase @@ -311,8 +312,9 @@ gitdog login --api-url https://your-deployment.convex.cloud --site-url http://lo gitdog github install --app gitdogbot-dev ``` -Custom URLs require HTTPS except for loopback development. The sign-in URL must -use the selected backend's origin or its matching `convex.site` origin. +Custom URLs require HTTPS except for loopback development. The CLI opens only +GitHub's `https://github.com/login/oauth/authorize` page for sign-in and +`gitdog github verify`. ## Development and verification diff --git a/packages/cli/src/auth.ts b/packages/cli/src/auth.ts index 8c56a56..e648472 100644 --- a/packages/cli/src/auth.ts +++ b/packages/cli/src/auth.ts @@ -217,17 +217,20 @@ export async function createLoginListener( }; } -/** GitHub's authorization page is the only place sign-in may send the user. */ +/** GitHub's authorization page is the only place the CLI may send the user. */ export function validateAuthRedirect(value: string): void { - const url = new URL(value); + const url = URL.canParse(value) ? new URL(value) : undefined; if ( + !url || url.origin !== "https://github.com" || url.pathname !== "/login/oauth/authorize" || url.username || url.password || url.hash ) { - throw new Error("The server returned an unexpected sign-in URL."); + throw new Error( + "The server returned an unexpected GitHub authorization URL.", + ); } } diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 332be55..dc663e8 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -4,7 +4,7 @@ import { join, resolve } from "node:path"; import { rm } from "node:fs/promises"; import type { Value } from "convex/values"; import { GitdogApi, type Api, type Args, type Kind } from "./client.js"; -import { login, logout, openBrowser } from "./auth.js"; +import { login, logout, openBrowser, validateAuthRedirect } from "./auth.js"; import { API_CATALOG, publicOperation } from "./catalog.js"; import { BOOLEAN_SETTINGS, @@ -1429,7 +1429,7 @@ export function createProgram( if (!ui.json && !flag(opts.print)) await openBrowser(url); ui.output({ url, - next: "After GitHub authorization, run npx gitdog@latest github recover, then npx gitdog@latest projects available.", + next: "After installing, run npx gitdog@latest github verify, then npx gitdog@latest github recover and npx gitdog@latest projects available.", }); }, ) @@ -1449,9 +1449,8 @@ export function createProgram( returnPath: "/repositories/connect", }), ); - const url = typeof result?.url === "string" ? result.url : undefined; - if (!url?.startsWith("https://github.com/")) - throw new Error("Gitdog returned an invalid GitHub authorization URL."); + const url = typeof result?.url === "string" ? result.url : ""; + validateAuthRedirect(url); if (!ui.json && !flag(opts.print)) await openBrowser(url); ui.output({ url, diff --git a/packages/cli/src/projects.ts b/packages/cli/src/projects.ts index 0697e84..406f436 100644 --- a/packages/cli/src/projects.ts +++ b/packages/cli/src/projects.ts @@ -265,7 +265,7 @@ export class ProjectContext { ); if (matches.length !== 1) throw new Error( - `Repository ${name} is unavailable. Run npx gitdog@latest github install, authorize it, then npx gitdog@latest github recover. Check projects available.`, + `Repository ${name} is unavailable. Run npx gitdog@latest github install, then npx gitdog@latest github verify and npx gitdog@latest github recover. Check projects available.`, ); const item = matches[0]; if (typeof item.installationId !== "number" || typeof item.id !== "number") diff --git a/packages/cli/test/auth.test.mjs b/packages/cli/test/auth.test.mjs index 74f987b..c8affc4 100644 --- a/packages/cli/test/auth.test.mjs +++ b/packages/cli/test/auth.test.mjs @@ -2,8 +2,10 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, readFile, rmdir, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; +import { createServer } from "node:net"; import { createLoginListener, + LOGIN_CALLBACK_PORTS, login, logout, validateAuthRedirect, @@ -84,6 +86,41 @@ test("loopback listener times out and supports cancellation", async () => { await assert.rejects(cancelled.code, /cancelled/); }); +// Holds each port another process is not already using. +async function occupy(ports) { + const servers = []; + for (const port of ports) { + const server = createServer(); + const bound = await new Promise((resolve, reject) => { + server.once("error", (error) => + error.code === "EADDRINUSE" ? resolve(false) : reject(error), + ); + server.listen(port, "127.0.0.1", () => resolve(true)); + }); + if (bound) servers.push(server); + } + return async () => { + await Promise.all( + servers.map((server) => new Promise((resolve) => server.close(resolve))), + ); + }; +} + +test("loopback listener falls back to the next fixed port", async (t) => { + const release = await occupy(LOGIN_CALLBACK_PORTS.slice(0, 1)); + t.after(release); + const listener = await createLoginListener(5000); + t.after(listener.close); + const port = Number(new URL(listener.redirectTo).port); + assert.ok(LOGIN_CALLBACK_PORTS.slice(1).includes(port)); +}); + +test("loopback listener fails clearly when every fixed port is busy", async (t) => { + const release = await occupy(LOGIN_CALLBACK_PORTS); + t.after(release); + await assert.rejects(createLoginListener(5000), /are all in use/); +}); + test("Convex OAuth cancellation without a code fails immediately", async (t) => { const listener = await createLoginListener(5000); t.after(listener.close); diff --git a/packages/cli/test/commands.test.mjs b/packages/cli/test/commands.test.mjs index f607112..ffd747b 100644 --- a/packages/cli/test/commands.test.mjs +++ b/packages/cli/test/commands.test.mjs @@ -324,8 +324,13 @@ test("github verify starts access verification and accepts only GitHub URLs", as ); await assert.rejects( run("https://evil.example/login"), - /invalid GitHub authorization URL/, + /unexpected GitHub authorization URL/, ); + await assert.rejects( + run("https://github.com/evil/login/oauth/authorize"), + /unexpected GitHub authorization URL/, + ); + await assert.rejects(run(undefined), /unexpected GitHub authorization URL/); }); test("mutation confirmation happens before a GitHub action executes", async () => { diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 80160af..f669d65 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -73,7 +73,10 @@ "signOut": "Sign out instead", "policyChangedError": "The Terms or Privacy Policy changed while this page was open. Reloading the current policies…", "saveError": "We could not save your confirmation. Please try again.", - "signInError": "We could not start GitHub sign-in. Please try again." + "signInError": "We could not start GitHub sign-in. Please try again.", + "signInCancelled": "GitHub sign-in was cancelled.", + "signInExpired": "GitHub sign-in took too long. Please try again.", + "signInFailed": "GitHub sign-in did not finish. Please try again." } }, "home": { @@ -220,16 +223,17 @@ "title": "Install Gitdog GitHub App", "description": "To access your repositories (including private and organization repos), you need to install the Gitdog GitHub App.", "maybeLater": "Maybe later", - "installButton": "Install GitHub App" + "installButton": "Install GitHub App", + "alreadyInstalled": "Already installed? Verify GitHub access" }, "verificationPending": { "title": "Finishing GitHub connection", "description": "Gitdog is waiting for GitHub to confirm this installation. Keep this page open and retry verification shortly.", "organizationDescription": "For security, GitHub must confirm organization access through a signed installation update before Gitdog can connect it.", - "reauthDescription": "Gitdog needs a fresh GitHub authorization to verify this existing installation.", - "recoveryInstructions": "Refresh GitHub authorization, or use Manage GitHub access and make an actual repository selection change. If access is already correct, uninstall and reinstall the GitHub App before retrying.", - "reauthorize": "Refresh GitHub authorization", - "reauthorizing": "Opening GitHub...", + "reauthDescription": "Gitdog needs to confirm your GitHub access to this installation.", + "recoveryInstructions": "Verify GitHub access, or use Manage GitHub access and make an actual repository selection change. If access is already correct, uninstall and reinstall the GitHub App before retrying.", + "verifyAccess": "Verify GitHub access", + "verifyingAccess": "Opening GitHub...", "retry": "Retry verification", "retrying": "Checking...", "manageAccess": "Manage GitHub access", @@ -566,7 +570,9 @@ "runsOn": "Reviews run on your {{provider}} key ••••{{last4}}", "effort": "{{effort}} effort", "backup": "If it runs out of credit, your {{provider}} key takes over with {{model}}.", - "noActiveKey": "No key is working right now, so reviews run on Gitdog tokens.", + "noKey": "No key is saved, so reviews run on Gitdog tokens.", + "noWorkingKey": "None of your saved keys works right now, so reviews stop until you fix or replace one.", + "keyChecksUnavailable": "Your saved keys can't be used right now because of a temporary Gitdog problem. Reviews resume once it is fixed.", "changeModel": "Change model", "manageKeys": "Manage keys", "costLabel": "Provider cost this period", @@ -662,13 +668,14 @@ }, "defaultModel": "Default", "price": "{{input}} in · {{output}} out per 1M tokens", + "longContextPrice": "Higher rate above {{tokens}} input tokens", "efforts": { "low": "Low", "medium": "Medium", "high": "High" }, "effortHint": "Higher effort reads more and costs more per run.", - "thisPeriod": "This period: {{cost}} on this key" + "thisPeriod": "{{provider}} cost this period: {{cost}}" } }, "footer": { diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index dfa169a..05ef718 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -73,7 +73,10 @@ "signOut": "代わりにサインアウト", "policyChangedError": "このページを開いている間に利用規約またはプライバシーポリシーが変更されました。最新のポリシーを再読み込みしています…", "saveError": "確認内容を保存できませんでした。もう一度お試しください。", - "signInError": "GitHubサインインを開始できませんでした。もう一度お試しください。" + "signInError": "GitHubサインインを開始できませんでした。もう一度お試しください。", + "signInCancelled": "GitHubサインインがキャンセルされました。", + "signInExpired": "GitHubサインインの時間が切れました。もう一度お試しください。", + "signInFailed": "GitHubサインインを完了できませんでした。もう一度お試しください。" } }, "home": { @@ -220,16 +223,17 @@ "title": "Gitdog GitHubアプリをインストール", "description": "リポジトリ(個人および組織リポジトリを含む)にアクセスするには、Gitdog GitHubアプリをインストールする必要があります。", "maybeLater": "後で", - "installButton": "GitHubアプリをインストール" + "installButton": "GitHubアプリをインストール", + "alreadyInstalled": "インストール済みですか?GitHubアクセスを確認" }, "verificationPending": { "title": "GitHub接続を完了しています", "description": "GitdogはGitHubによるインストール確認を待っています。このページを開いたまま、しばらくしてから確認を再試行してください。", "organizationDescription": "セキュリティ上、組織のインストールはGitHubが署名したインストール更新でアクセスを確認した後に接続できます。", - "reauthDescription": "この既存のインストールを確認するには、GitHubの認証を更新する必要があります。", - "recoveryInstructions": "GitHub認証を更新するか、GitHubアクセス管理でリポジトリの選択を実際に変更してください。選択がすでに正しい場合は、GitHub Appをアンインストールしてから再インストールし、もう一度お試しください。", - "reauthorize": "GitHub認証を更新", - "reauthorizing": "GitHubを開いています...", + "reauthDescription": "このインストールへのGitHubアクセスを確認する必要があります。", + "recoveryInstructions": "GitHubアクセスを確認するか、GitHubアクセス管理でリポジトリの選択を実際に変更してください。選択がすでに正しい場合は、GitHub Appをアンインストールしてから再インストールし、もう一度お試しください。", + "verifyAccess": "GitHubアクセスを確認", + "verifyingAccess": "GitHubを開いています...", "retry": "確認を再試行", "retrying": "確認中...", "manageAccess": "GitHubアクセスを管理", @@ -564,7 +568,9 @@ "runsOn": "レビューは {{provider}} キー ••••{{last4}} で実行されます", "effort": "推論の強さ: {{effort}}", "backup": "クレジットが切れると {{provider}} キーの {{model}} が引き継ぎます。", - "noActiveKey": "使えるキーがないため、レビューは Gitdog のトークンで実行されます。", + "noKey": "保存されたキーがないため、レビューは Gitdog のトークンで実行されます。", + "noWorkingKey": "保存されたキーに今使えるものがないため、キーを直すか差し替えるまでレビューは止まります。", + "keyChecksUnavailable": "一時的な Gitdog の問題で、保存されたキーを今は使えません。解決するとレビューは再開します。", "changeModel": "モデルを変更", "manageKeys": "キーを管理", "costLabel": "今期間のプロバイダー費用", @@ -659,13 +665,14 @@ }, "defaultModel": "デフォルト", "price": "100万トークンあたり 入力 {{input}} · 出力 {{output}}", + "longContextPrice": "入力 {{tokens}} トークン超は高い料金", "efforts": { "low": "低", "medium": "中", "high": "高" }, "effortHint": "強さを上げるほど多く読み、1 回あたりの費用が増えます。", - "thisPeriod": "今期間このキーで {{cost}}" + "thisPeriod": "今期間の {{provider}} 利用額: {{cost}}" } }, "footer": { diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.json index d6b5b56..dabc5aa 100644 --- a/src/i18n/locales/ko.json +++ b/src/i18n/locales/ko.json @@ -73,7 +73,10 @@ "signOut": "대신 로그아웃", "policyChangedError": "이 페이지가 열린 동안 이용약관 또는 개인정보 처리방침이 변경되었습니다. 최신 정책을 다시 불러오는 중입니다…", "saveError": "확인 내용을 저장하지 못했습니다. 다시 시도해 주세요.", - "signInError": "GitHub 로그인을 시작하지 못했습니다. 다시 시도해 주세요." + "signInError": "GitHub 로그인을 시작하지 못했습니다. 다시 시도해 주세요.", + "signInCancelled": "GitHub 로그인이 취소되었습니다.", + "signInExpired": "GitHub 로그인 시간이 초과되었습니다. 다시 시도해 주세요.", + "signInFailed": "GitHub 로그인을 마치지 못했습니다. 다시 시도해 주세요." } }, "home": { @@ -220,16 +223,17 @@ "title": "Gitdog GitHub 앱 설치", "description": "저장소(개인 및 조직 저장소 포함)에 접근하려면 Gitdog GitHub 앱을 설치해야 합니다.", "maybeLater": "나중에", - "installButton": "GitHub 앱 설치" + "installButton": "GitHub 앱 설치", + "alreadyInstalled": "이미 설치했나요? GitHub 접근 확인" }, "verificationPending": { "title": "GitHub 연결 마무리 중", "description": "Gitdog가 GitHub의 설치 확인을 기다리고 있습니다. 이 페이지를 열어 둔 채 잠시 후 확인을 다시 시도하세요.", "organizationDescription": "보안을 위해 조직 설치는 GitHub가 서명한 설치 업데이트로 접근 권한을 확인한 뒤 연결할 수 있습니다.", - "reauthDescription": "기존 설치를 확인하려면 GitHub 권한을 새로 인증해야 합니다.", - "recoveryInstructions": "GitHub 권한을 새로 인증하거나, GitHub 접근 관리에서 저장소 선택을 실제로 변경하세요. 이미 선택이 맞다면 GitHub 앱을 제거한 뒤 다시 설치하고 재시도하세요.", - "reauthorize": "GitHub 권한 새로 인증", - "reauthorizing": "GitHub 여는 중...", + "reauthDescription": "이 설치에 대한 GitHub 접근 권한을 확인해야 합니다.", + "recoveryInstructions": "GitHub 접근 확인을 하거나, GitHub 접근 관리에서 저장소 선택을 실제로 변경하세요. 이미 선택이 맞다면 GitHub 앱을 제거한 뒤 다시 설치하고 재시도하세요.", + "verifyAccess": "GitHub 접근 확인", + "verifyingAccess": "GitHub 여는 중...", "retry": "확인 다시 시도", "retrying": "확인 중...", "manageAccess": "GitHub 접근 관리", @@ -564,7 +568,9 @@ "runsOn": "리뷰는 {{provider}} 키 ••••{{last4}}로 실행됩니다", "effort": "추론 강도 {{effort}}", "backup": "크레딧이 떨어지면 {{provider}} 키의 {{model}}이(가) 이어서 실행합니다.", - "noActiveKey": "지금 쓸 수 있는 키가 없어 리뷰는 Gitdog 토큰으로 실행됩니다.", + "noKey": "저장된 키가 없어 리뷰는 Gitdog 토큰으로 실행됩니다.", + "noWorkingKey": "저장된 키 중 지금 쓸 수 있는 키가 없어, 키를 고치거나 바꿀 때까지 리뷰가 멈춥니다.", + "keyChecksUnavailable": "일시적인 Gitdog 문제로 저장된 키를 지금 쓸 수 없습니다. 해결되면 리뷰가 다시 실행됩니다.", "changeModel": "모델 변경", "manageKeys": "키 관리", "costLabel": "이번 기간 제공자 비용", @@ -659,13 +665,14 @@ }, "defaultModel": "기본", "price": "1M 토큰당 입력 {{input}} · 출력 {{output}}", + "longContextPrice": "입력 {{tokens}} 토큰 초과 시 더 높은 요금", "efforts": { "low": "낮음", "medium": "중간", "high": "높음" }, "effortHint": "강도가 높을수록 더 많이 읽고 실행당 비용이 커집니다.", - "thisPeriod": "이번 기간 이 키 사용액: {{cost}}" + "thisPeriod": "이번 기간 {{provider}} 사용액: {{cost}}" } }, "footer": { diff --git a/src/pages/legal/consent.tsx b/src/pages/legal/consent.tsx index 8eb08d3..5dcbe77 100644 --- a/src/pages/legal/consent.tsx +++ b/src/pages/legal/consent.tsx @@ -1,5 +1,9 @@ import { useAuthActions } from "@convex-dev/auth/react"; -import { useSignInWithGithub } from "@convex-dev/auth/methods/github/react"; +import { + useOauth, + useSignInWithGithub, + type OauthFlowError, +} from "@convex-dev/auth/methods/github/react"; import { SiGithub } from "@icons-pack/react-simple-icons"; import { useConvexAuth, useMutation, useQuery } from "convex/react"; import { FormEvent, useCallback, useEffect, useRef, useState } from "react"; @@ -24,6 +28,13 @@ import { shouldReleasePendingConsent, } from "../../utils/legalConsent"; +const SIGN_IN_FLOW_ERRORS: Record = { + ACCESS_DENIED: "auth.legalConsent.signInCancelled", + EXPIRED: "auth.legalConsent.signInExpired", + INVALID_FLOW: "auth.legalConsent.signInFailed", + OTHER_ERROR: "auth.legalConsent.signInFailed", +}; + export function LegalConsentPage() { const { t } = useTranslation(); const location = useLocation(); @@ -34,6 +45,7 @@ export function LegalConsentPage() { ); const { signOut } = useAuthActions(); const { signIn } = useSignInWithGithub(api.auth); + const { flowError } = useOauth(); const { isAuthenticated, isLoading: isAuthResolving } = useConvexAuth(); // Captured once: the visitor already confirmed eligibility on this tab and is // coming back from the GitHub redirect, so the form must not restart empty. @@ -220,6 +232,9 @@ export function LegalConsentPage() { } }; + const alertMessage = + error ?? (flowError ? t(SIGN_IN_FLOW_ERRORS[flowError.error]) : null); + const handleSignOut = async () => { clearPendingLegalConsent(); await signOut(); @@ -330,12 +345,12 @@ export function LegalConsentPage() { - {error && ( + {alertMessage && (

- {error} + {alertMessage}

)} diff --git a/src/pages/profile/ProviderKeysSection.tsx b/src/pages/profile/ProviderKeysSection.tsx index c70865e..8e2ee44 100644 --- a/src/pages/profile/ProviderKeysSection.tsx +++ b/src/pages/profile/ProviderKeysSection.tsx @@ -1,4 +1,5 @@ import { useAction, useMutation, useQuery } from "convex/react"; +import type { FunctionReturnType } from "convex/server"; import { ConvexError } from "convex/values"; import { useEffect, useState } from "react"; import { useLocation } from "react-router"; @@ -9,7 +10,11 @@ import { LoadingIndicator } from "../../components/uis/LoadingIndicator"; import { cn } from "../../utils/cn"; import { summarizeProviderKeys } from "../../utils/providerKeyState"; import { useRelativeTime } from "../../hooks/useRelativeTime"; -import { formatPerMillion, formatUsdCents } from "../../utils/usageFormat"; +import { + formatPerMillion, + formatTokens, + formatUsdCents, +} from "../../utils/usageFormat"; export const PROVIDER_KEYS_ANCHOR = "ai-keys"; @@ -26,14 +31,9 @@ type SavedKey = { effort: string; }; -type ModelOption = { - modelId: string; - name: string; - efforts: readonly string[]; - defaultEffort: string; - inputPer1M: number; - outputPer1M: number; -}; +type ModelOption = FunctionReturnType< + typeof api.providerApiKeys.query.models +>[KeyProvider][number]; // Which saved key reviews run on: Claude first, OpenAI when Claude cannot. type KeyRole = "primary" | "backup"; @@ -325,6 +325,10 @@ function ProviderKeyCard({ input: formatPerMillion(model.inputPer1M), output: formatPerMillion(model.outputPer1M), })} + {model.longContextInputTokens !== undefined && + ` · ${t("profile.providerKeys.longContextPrice", { + tokens: formatTokens(model.longContextInputTokens), + })}`} @@ -370,7 +374,10 @@ function ProviderKeyCard({

{periodCost && (

- {t("profile.providerKeys.thisPeriod", { cost: periodCost })} + {t("profile.providerKeys.thisPeriod", { + provider: label, + cost: periodCost, + })}

)} diff --git a/src/pages/repositories/connect.tsx b/src/pages/repositories/connect.tsx index f22e6b4..3edc45f 100644 --- a/src/pages/repositories/connect.tsx +++ b/src/pages/repositories/connect.tsx @@ -28,6 +28,7 @@ import { needsGitHubAppInstallation, type OAuthInstallationRecoveryOutcome, recoverOAuthInstallations, + resolveConnectScreen, resolveGitHubAppSlug, resolveInstallationReconnect, storePendingReconnectMapping, @@ -135,29 +136,14 @@ export function RepositoryConnect() { ? "invalid" : "ready"; - const hasNoDurableInstallations = - installations !== undefined && installations.length === 0; - const needsOAuthReauthorization = - hasNoDurableInstallations && - oauthInstallationRecovery.status === "reauth_required"; - const needsInstallation = - oauthInstallationRecovery.status === "none" && - oauthInstallationRecovery.recoveredCount === 0 && - needsGitHubAppInstallation(installations); - const waitingForRecoveredInstallations = - hasNoDurableInstallations && - oauthInstallationRecovery.recoveredCount > 0 && - error === null; - const oauthRecoveryLoading = - oauthInstallationRecovery.status === "pending" && - verificationPendingInstallationId === null && - error === null; - const showInstallationVerification = - verificationPendingInstallationId !== null || needsOAuthReauthorization; - const installationVerificationRequiresReauth = - verificationPendingInstallationId === null - ? needsOAuthReauthorization - : verificationReauthRequired; + const screen = resolveConnectScreen({ + loading, + installations, + recovery: oauthInstallationRecovery, + verificationPending: verificationPendingInstallationId !== null, + hasError: error !== null, + }); + const hasNoDurableInstallations = needsGitHubAppInstallation(installations); const installationVerificationRequiresConfiguration = hasNoDurableInstallations && oauthInstallationRecovery.status === "configure_required"; @@ -475,7 +461,7 @@ export function RepositoryConnect() { ); }, [t]); - const handleRefreshGitHubAuthorization = async () => { + const handleVerifyGitHubAccess = async () => { setIsStartingVerification(true); try { const { url } = await startAccessVerification({ @@ -557,10 +543,7 @@ export function RepositoryConnect() {

- {loading || - installations === undefined || - oauthRecoveryLoading || - waitingForRecoveredInstallations ? ( + {screen === "loading" ? (
- ) : showInstallationVerification ? ( + ) : screen === "verification" ? (
- {installationVerificationRequiresReauth || + {verificationReauthRequired || installationVerificationRequiresConfiguration ? (

) : null}

- {installationVerificationRequiresReauth ? ( + {verificationReauthRequired ? ( ) : null} @@ -657,25 +640,23 @@ export function RepositoryConnect() { > {t("repositories.connect.verificationPending.manageAccess")} - {verificationPendingInstallationId !== null ? ( - - ) : null} +
- ) : error ? ( + ) : screen === "error" ? (
- ) : needsInstallation ? ( + ) : screen === "install" ? (
+ {oauthInstallationRecovery.status === "reauth_required" ? ( + + ) : null} ) : ( diff --git a/src/pages/repositories/connectFlow.ts b/src/pages/repositories/connectFlow.ts index 8a5877a..304d687 100644 --- a/src/pages/repositories/connectFlow.ts +++ b/src/pages/repositories/connectFlow.ts @@ -207,6 +207,46 @@ export function needsGitHubAppInstallation( return installations !== undefined && installations.length === 0; } +export type ConnectScreen = + "loading" | "verification" | "error" | "install" | "repositories"; + +/** + * Which connect screen to show. Without a fresh attestation recovery cannot + * tell a new user from one whose installation predates it, so a user with no + * installation is offered Install first, with verification to reclaim one. + */ +export function resolveConnectScreen(state: { + loading: boolean; + installations: ReadonlyArray | undefined; + recovery: { status: string; recoveredCount: number }; + verificationPending: boolean; + hasError: boolean; +}): ConnectScreen { + const { recovery } = state; + const noInstallations = needsGitHubAppInstallation(state.installations); + switch (true) { + case state.loading || state.installations === undefined: + case recovery.status === "pending" && + !state.verificationPending && + !state.hasError: + case noInstallations && + // Recovered installations are still reaching the installations query. + recovery.recoveredCount > 0 && + !state.hasError: + return "loading"; + case state.verificationPending: + return "verification"; + case state.hasError: + return "error"; + case noInstallations && + (recovery.status === "reauth_required" || + (recovery.status === "none" && recovery.recoveredCount === 0)): + return "install"; + default: + return "repositories"; + } +} + export function getReconnectRepositoryIdFromSearch( search: string, ): string | null { diff --git a/src/pages/tickets/ActionUsageChip.tsx b/src/pages/tickets/ActionUsageChip.tsx index ba040b4..40ebb4c 100644 --- a/src/pages/tickets/ActionUsageChip.tsx +++ b/src/pages/tickets/ActionUsageChip.tsx @@ -30,12 +30,13 @@ export function ActionUsageChip({ usage }: { usage: ActionUsage | undefined }) { tokens: `${formatTokens(gitdog.quotaTokens)}${more}`, }), ].filter(Boolean); + const requests = t("tickets.detail.usage.requests", { + count: (userKey?.requests ?? 0) + (gitdog?.requests ?? 0), + }); return ( ); } diff --git a/src/pages/tickets/[id].tsx b/src/pages/tickets/[id].tsx index e00e756..6a9b833 100644 --- a/src/pages/tickets/[id].tsx +++ b/src/pages/tickets/[id].tsx @@ -35,7 +35,7 @@ import { import { useState, useMemo } from "react"; import { parseGitdogBody } from "../../utils/parseGitdogContent"; import { ActionUsageChip } from "./ActionUsageChip"; -import { actionTypeLabelKey } from "../../utils/actionTypes"; +import { actionTypeLabel } from "../../utils/actionTypes"; export function TicketDetailPage() { const { t, i18n } = useTranslation(); @@ -234,11 +234,6 @@ export function TicketDetailPage() { } }; - const getActionTypeName = (actionType: string) => { - const key = actionTypeLabelKey(actionType); - return key ? t(key) : actionType; - }; - if (!id) { return ( @@ -618,7 +613,7 @@ export function TicketDetailPage() { {action.reviewVerificationOnly === true ? t("tickets.detail.reviewVerification") - : getActionTypeName(action.actionType)} + : actionTypeLabel(t, action.actionType)}
= { @@ -61,7 +61,15 @@ export function UserKeyUsageSection() { if (keys === undefined || usage === undefined || usage === null) return null; if (keys.length === 0 && usage.totals.requests === 0) return null; - const { activeKey, backupKey } = summarizeProviderKeys(keys); + const { keyChecksUnavailable, activeKey, backupKey } = + summarizeProviderKeys(keys); + // Saved keys never fall back to Gitdog tokens: reviews stop until one works. + const inactiveKeyMessage = + keys.length === 0 + ? "noKey" + : keyChecksUnavailable + ? "keyChecksUnavailable" + : "noWorkingKey"; const { totals } = usage; const average = totals.actions > 0 ? totals.costCents / totals.actions : 0; @@ -117,7 +125,7 @@ export function UserKeyUsageSection() {
) : (

- {t("usage.userKey.noActiveKey")} + {t(`usage.userKey.${inactiveKeyMessage}`)}

)} @@ -233,7 +241,7 @@ export function UserKeyUsageSection() { >
- {t(actionTypeLabelKey(run.actionType) ?? run.actionType)} + {actionTypeLabel(t, run.actionType)} {run.ticketId ? ( u.repositoryId === repo._id, )?.costCents ?? 0, )}${userKeyUsage.isPartial ? "+" : ""}` - : "…"; + : "—"; return (
= { follow_up: "tickets.actionTypes.followUp", }; -/** The translation key naming a ticket action type, if it has one. */ -export function actionTypeLabelKey(actionType: string): string | undefined { - return ACTION_TYPE_LABELS[actionType]; +/** A ticket action type's name, or the raw type when it has no label. */ +export function actionTypeLabel( + t: (key: string) => string, + actionType: string, +): string { + const key = ACTION_TYPE_LABELS[actionType]; + return key ? t(key) : actionType; } diff --git a/test/convex/repositories/connectIdentity.test.ts b/test/convex/repositories/connectIdentity.test.ts index 6d71973..d8a5b4f 100644 --- a/test/convex/repositories/connectIdentity.test.ts +++ b/test/convex/repositories/connectIdentity.test.ts @@ -2,11 +2,11 @@ import { convexTest } from "convex-test"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { MockedFunction } from "vitest"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; import { api } from "../../../convex/_generated/api"; import type { Id } from "../../../convex/_generated/dataModel"; import { internalMutation } from "../../../convex/_generated/server"; +import { getAuthUserId } from "../../../convex/_utils/auth"; import * as githubHelpers from "../../../convex/github/helpers"; import schema from "../../../convex/schema"; import { asUser } from "../../helpers/auth"; diff --git a/test/convex/setup.ts b/test/convex/setup.ts index fdd76ae..5aee0d8 100644 --- a/test/convex/setup.ts +++ b/test/convex/setup.ts @@ -16,6 +16,8 @@ process.env.GITHUB_APP_ID = "test-app-id"; process.env.GITHUB_APP_PRIVATE_KEY = "test-private-key"; process.env.GITHUB_APP_SLUG = "gitdogbot"; process.env.FREE_TIER_ENABLED = "true"; +// Convex Auth checks token issuers against the deployment's cloud URL. +process.env.CONVEX_CLOUD_URL = "https://gitdog-test.convex.cloud"; process.env.PAID_PROJECT_BILLING_ENABLED = "true"; // Unit tests must never inherit a real provider key from local development files. diff --git a/test/convex/tokenUsage/userKeyUsage.test.ts b/test/convex/tokenUsage/userKeyUsage.test.ts index 7278fe5..83adb8d 100644 --- a/test/convex/tokenUsage/userKeyUsage.test.ts +++ b/test/convex/tokenUsage/userKeyUsage.test.ts @@ -1028,9 +1028,7 @@ describe("usage reporting for user keys", () => { costCents: 4, }, ], - repositories: [ - { repositoryId: fixture.repositoryId, actions: 2, costCents: 10 }, - ], + repositories: [{ repositoryId: fixture.repositoryId, costCents: 10 }], }); expect(usage?.recentActions).toEqual([ expect.objectContaining({ diff --git a/test/convex/users/sessionAuth.test.ts b/test/convex/users/sessionAuth.test.ts new file mode 100644 index 0000000..d47c91e --- /dev/null +++ b/test/convex/users/sessionAuth.test.ts @@ -0,0 +1,91 @@ +import { convexTest } from "convex-test"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { registerGithubOauth } from "@convex-dev/auth/components/github/test"; +import { api, components } from "../../../convex/_generated/api"; +import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; + +const modules = { + "../../../convex/_generated/api.ts": () => + import("../../../convex/_generated/api"), + "../../../convex/auth.ts": () => import("../../../convex/auth"), + "../../../convex/users/query.ts": () => import("../../../convex/users/query"), +}; + +const createUser = (t: ReturnType) => + t.run((ctx) => + ctx.db.insert("users", { name: "octocat", githubAccountId: "654" }), + ); + +describe("session authentication", () => { + it("resolves the user only through a live session", async () => { + const t = convexTest(schema, modules); + const userId = await createUser(t); + const signedIn = await asUser(t, userId); + + expect(await signedIn.query(api.users.query.getCurrentUser)).toMatchObject({ + _id: userId, + }); + // A token whose subject is a user id rather than a session is not a sign-in. + expect( + await t + .withIdentity({ subject: userId }) + .query(api.users.query.getCurrentUser), + ).toBeNull(); + }); + + it("rejects a session after it is revoked", async () => { + const t = convexTest(schema, modules); + const userId = await createUser(t); + const signedIn = await asUser(t, userId); + expect(await signedIn.query(api.users.query.getCurrentUser)).not.toBeNull(); + const sessionIds = await t.run((ctx) => + ctx.runQuery(components.auth.public.listSessions, { userId }), + ); + + await t.run((ctx) => + ctx.runMutation(components.auth.public.revokeSessions, { + sessionIds: sessionIds.map((session) => session.sessionId), + }), + ); + + expect(await signedIn.query(api.users.query.getCurrentUser)).toBeNull(); + }); +}); + +describe("GitHub sign-in redirects", () => { + beforeEach(() => { + vi.stubEnv("SITE_URL", "https://gitdog.dev"); + vi.stubEnv("CONVEX_SITE_URL", "https://gitdog-test.convex.site"); + vi.stubEnv("CLIENT_ID", "test-client-id"); + }); + afterEach(() => vi.unstubAllEnvs()); + + it.each([ + "https://gitdog.dev/repositories", + "http://127.0.0.1:41721/callback", + ])("accepts a sign-in that returns to %s", async (redirectTo) => { + const t = convexTest(schema, modules); + registerGithubOauth(t); + + // convex-test mounts components without an httpPrefix, so an accepted + // redirect stops later, when the callback URL is built. + await expect( + t.mutation(api.auth.startSignInWithGithub, { redirectTo }), + ).rejects.toThrow(/httpPrefix/); + }); + + it.each([ + "https://evil.example/repositories", + "https://gitdog.dev.evil.example/", + "http://127.0.0.1:41726/callback", + "http://localhost:41721/callback", + "/repositories", + ])("refuses to return to %s", async (redirectTo) => { + const t = convexTest(schema, modules); + + await expect( + t.mutation(api.auth.startSignInWithGithub, { redirectTo }), + ).rejects.toThrow(/redirectTo/); + }); +}); diff --git a/test/helpers/auth.ts b/test/helpers/auth.ts index d4c5f2e..5de6ee9 100644 --- a/test/helpers/auth.ts +++ b/test/helpers/auth.ts @@ -17,8 +17,6 @@ export async function asUser( t: T, userId: Id<"users">, ): Promise> { - // Convex Auth checks token issuers against the deployment's cloud URL. - process.env.CONVEX_CLOUD_URL ??= "https://gitdog-test.convex.cloud"; if (!withCore.has(t)) { registerCore(t); withCore.add(t); diff --git a/test/pages/legalConsentPage.test.ts b/test/pages/legalConsentPage.test.ts index 205cb30..7c5d831 100644 --- a/test/pages/legalConsentPage.test.ts +++ b/test/pages/legalConsentPage.test.ts @@ -7,6 +7,7 @@ const convexMocks = { currentUser: null as unknown, attestLegalEligibility: vi.fn(), authState: { isAuthenticated: false, isLoading: false }, + flowError: null as { error: string } | null, }; const legalConsentMocks = { @@ -25,6 +26,7 @@ vi.mock("@convex-dev/auth/react", () => ({ vi.mock("@convex-dev/auth/methods/github/react", () => ({ useSignInWithGithub: () => ({ signIn: vi.fn() }), + useOauth: () => ({ flowError: convexMocks.flowError }), })); vi.mock("react-i18next", () => ({ @@ -59,6 +61,7 @@ describe("legal consent page", () => { beforeEach(() => { convexMocks.currentUser = null; convexMocks.authState = { isAuthenticated: false, isLoading: false }; + convexMocks.flowError = null; legalConsentMocks.hasPendingLegalConsent = false; }); @@ -88,6 +91,16 @@ describe("legal consent page", () => { expect(html).toContain("auth.legalConsent.continueWithGitHub"); }); + it("explains why the last GitHub sign-in failed", () => { + expect(renderConsentPage()).not.toContain('role="alert"'); + + convexMocks.flowError = { error: "ACCESS_DENIED" }; + expect(renderConsentPage()).toContain("auth.legalConsent.signInCancelled"); + + convexMocks.flowError = { error: "OTHER_ERROR" }; + expect(renderConsentPage()).toContain("auth.legalConsent.signInFailed"); + }); + it("keeps the confirmation form for a current backend requiring consent", () => { convexMocks.currentUser = { name: "current-user", diff --git a/test/pages/repositoryConnectFlow.test.ts b/test/pages/repositoryConnectFlow.test.ts index 73d25d1..caa258b 100644 --- a/test/pages/repositoryConnectFlow.test.ts +++ b/test/pages/repositoryConnectFlow.test.ts @@ -16,6 +16,7 @@ import { groupRepositoriesByInstallation, type InstallationBindingRefreshResult, needsGitHubAppInstallation, + resolveConnectScreen, OAUTH_INSTALLATION_RECOVERY_MAX_INSTALLATIONS, type OAuthInstallationRecoveryOutcome, PENDING_RECONNECT_STORAGE_KEY, @@ -952,3 +953,62 @@ describe("repository connection flow", () => { ).toBe(false); }); }); + +describe("resolveConnectScreen", () => { + const installed = [{ installationId: 1 }]; + const base = { + loading: false, + installations: [] as { installationId: number }[], + recovery: { status: "none", recoveredCount: 0 }, + verificationPending: false, + hasError: false, + }; + + it.each([ + ["loading", { loading: true }], + ["loading", { installations: undefined }], + ["loading", { recovery: { status: "pending", recoveredCount: 0 } }], + ["loading", { recovery: { status: "complete", recoveredCount: 1 } }], + [ + "verification", + { + recovery: { status: "pending", recoveredCount: 0 }, + verificationPending: true, + }, + ], + [ + "verification", + { + recovery: { status: "configure_required", recoveredCount: 0 }, + verificationPending: true, + }, + ], + [ + "error", + { + recovery: { status: "unavailable", recoveredCount: 0 }, + hasError: true, + }, + ], + // A new user without a fresh attestation must still be offered Install. + ["install", { recovery: { status: "reauth_required", recoveredCount: 0 } }], + ["install", {}], + [ + "repositories", + { + installations: installed, + recovery: { status: "reauth_required", recoveredCount: 0 }, + }, + ], + [ + "repositories", + { + installations: installed, + recovery: { status: "configure_required", recoveredCount: 0 }, + }, + ], + ["repositories", { recovery: { status: "complete", recoveredCount: 0 } }], + ] as const)("shows %s for %j", (screen, overrides) => { + expect(resolveConnectScreen({ ...base, ...overrides })).toBe(screen); + }); +});