diff --git a/CHANGELOG.md b/CHANGELOG.md index 9eea2b15..703596ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ All notable changes to AngKorGit are documented here. The format follows ## [Unreleased] +### Added +- **Clone from saved accounts** (#47). Browse and search repositories from your + GitHub, GitLab or Bitbucket Cloud accounts in the clone dialog. AngKorGit + remembers the selected account for that repository. + ## [0.28.0] — 2026-11-15 The hooks release. AngKorGit now runs the hooks Git runs after a checkout, a pull or diff --git a/CLAUDE.md b/CLAUDE.md index ba7b61b5..a7c56949 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -166,6 +166,10 @@ angkorgit/ │ │ refs/merge-requests/N/head, bitbucket → null), │ │ types.ts (PullRequestInfo, CreatePullRequestInput, │ │ ForgeUser, PullRequestCheckoutSpec, ForgeError), +│ │ repositories.ts maps one saved-account repository +│ │ page at a time, including Bitbucket workspace +│ │ continuation, using the shared transport and +│ │ provider message parsers; │ │ shared.ts also owns createForgeJsonRequest — the ONE │ │ transport helper (status check, ForgeError shaping, │ │ JSON guard) all three adapters use; a new adapter is a @@ -341,7 +345,13 @@ forge.rs ← forge API proxy: forge_request(repoPath, host, request bitbucket Basic email:token) and forwards via http.rs; the URL host must equal the remote host or its api. subdomain (dot-anchored, so evilgithub.com never matches) — tokens never reach the webview; - 6 module tests + 7 module tests +forge_repositories.rs ← account_forge_request uses the exact saved account, reuses forge + auth headers and http.rs, and permits GET only on that provider's + HTTPS API origin and path prefix. No redirects, 10-second timeout. + The same path checks the account identity endpoint after an + authenticated clone fails. Pagination and JSON handling live in core + TypeScript. 3 module tests. proc.rs ← EVERY child process starts here: proc::hidden(program) adds CREATE_NO_WINDOW on Windows (see G31). A module test scans src/ and fails on any bare Command::new outside proc.rs @@ -875,7 +885,7 @@ core/ - Operations that can pause on conflicts return `OpOutcome { status: "ok"|"conflicts"|"up_to_date"|"fast_forward", message }` — never an error for conflicts. - Command args are **camelCase** matching the TS payloads (`#![allow(non_snake_case)]`). - Every new engine function gets an integration test in `tests/git_engine.rs` - (81 tests; TempRepo fixture creates real repos in temp dirs; uses `angkorgit_lib::test_api`). + (212 macOS tests; TempRepo fixture creates real repos in temp dirs; uses `angkorgit_lib::test_api`). - Destructive ops verify outcomes (e.g. discard returns leftover paths → UI explains submodules). ## 6. Frontend — `apps/desktop/src/` @@ -1463,7 +1473,14 @@ features/ │ │ so fast switches never flash it; auto fetch tries every │ │ remote on each tick, marks fetched when any succeeds, │ │ records failed remote names, and retries at the configured -│ │ interval), CloneDialog, RepoDialogs +│ │ interval), CloneDialog (Browse saved accounts lists +│ │ GitHub, GitLab and Bitbucket Cloud repositories for +│ │ the exact host + username through account_forge_request. +│ │ Load more fetches one repository page, with partial +│ │ results retained on error. The dialog caches pages per +│ │ account for five minutes and offers Refresh. Selecting +│ │ a result fills the URL and editing clears the selection), +│ │ RepoDialogs │ │ (create branch/tag/stash — the stash dialog takes an │ │ optional StashPreset {paths} context (working-copy row menu │ │ "Stash this file…" / "Stash n files…"), lists the files name-first and passes @@ -3591,6 +3608,18 @@ update CLAUDE.md or docs/ — never the code. odd statuses never mark an account broken (offline must not rot accounts); Bitbucket re-checks need the stored Atlassian `email` (G17) and are skipped without it. + Cloning from the saved account picker uses the selected keychain entry and + writes that host binding before post-checkout. Initial profile setup keeps + bindings written directly to the repo and never copies inherited or included + config. A profile without account mappings leaves that config alone during + initial setup, while applying a profile explicitly replaces the local binding. + The picker lists and clones over HTTPS, including for self-managed GitLab. + GitLab page numbers and GitLab/GitHub repository paths are applied to the saved + origin, since the server can advertise a different public address behind a proxy. + A clone authentication error triggers an independent HTTPS check of the + account's identity endpoint. Only a 401 from that endpoint marks the + current credential unverified. Verification is diagnostic and the Git + credential order still follows the repo binding and host default. - **G31 — on Windows every `Command` needs `CREATE_NO_WINDOW`**: AngKorGit is a GUI-subsystem process with no console, so spawning a console-subsystem child @@ -4635,10 +4664,10 @@ update CLAUDE.md or docs/ — never the code. | Suite | Location | Coverage | | --- | --- | --- | -| Rust integration (210 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | -| Rust module (112 macOS; platform cases in CI) | `src/commands.rs` (2), `src/core/submodule.rs` (2 atomic baseline-write tests), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (20), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (7), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | -| Unit (341) | `tests/unit/*.test.ts` | actionError (busy responses use info without a failure prefix, other errors keep default or custom formatting), themeContrast (every palette keeps body ≥ 7:1, muted ≥ 5.5:1, faint ≥ 4.5:1 against background and surface, in that order, and defines its own code comment colour), settingsFilter (AND terms, section labels, catalog coverage of every JSX card title), GraphLayout (incl. pagination stability, lane reuse), wordDiff (round-trip), conflict parse/serialize (diff3 labels, CRLF, bare markers, 8+-char content lines, close-without-separator — all lossless), cliAgents (per-agent argv/stdin shape incl. Cursor print mode with the prompt last, ANSI/OSC cleaning, output-file preference, error surfacing), aiProviders (empty/whitespace/missing content rejected for openai-compatible + ollama, HTTP status+body surfaced, real content passes; OpenAI itself gets max_completion_tokens while other compatible hosts and LM Studio keep max_tokens, a rejected temperature is dropped and remembered, a rejected max_tokens or max_completion_tokens swaps once and never loops, an unrelated 400 is not retried, a reasoning model that spent its budget thinking gets one retry at REASONING_MIN_TOKENS that sticks, a budget that ran out without reasoning explains itself), aiCapabilities (review conventions: absent by default, general-only, general+project order with precedence note, whitespace = absent, clipping), aiTextSegments (token parse: adjacent tokens, unclosed/inner-asterisk/multi-line markers stay literal, ** inside backticks is code), reviewSignature (staged-only, order-insensitive, unstaged-edit + set changes alter it, newline filenames don't collide, hashText determinism), commitStyle (prefix rule matching/tokens/ticket-fallthrough, `$`-sequence literalness, preset instructions, post-generation prefix enforcement), pullRequestUrl (https/scp/ssh remotes, non-standard ports kept, http preserved, ssh port dropped, Bitbucket Server /scm/ shape, .git-behind-slash strip, unknown forge → null), aiModels (per-provider list endpoints/headers incl. Groq-style base URLs, generateContent filtering for Gemini, dedupe/sort, invalid-JSON + HTTP-status errors, cli → empty without a request), forge (parseForgeRemote for all three forges + rejects, provider creation gating, github/gitlab/bitbucket adapters: request URLs, field mapping incl. fork + draft detection, create payloads, error-message surfacing incl. github field-level validation entries without a message, checkoutSpec shapes incl. bitbucket fork → null, pickForgeRemote upstream-first ordering, github 403 create refusals explained (fine-grained token into another owner's repo, missing pull request permission, rate limit left verbatim), gitlab self-hosted https→http transport fallback — GET-only (a retried POST could file a duplicate MR), never for gitlab.com or api-level errors, working scheme remembered per host and safe under concurrent fallbacks, reviewer candidates per forge + reviewer ids embedded/requested on create incl. github follow-up failure tolerance, authorAvatar per forge: github commit author, gitlab avatar-by-email URL encoding, bitbucket commit author user), worktree (folder-name slug from repo + branch, sibling-path suggestion incl. Windows separators, parentDirectory), highlight (block-comment continuation: JSDoc carried and closed, line comments and glob strings not treated as open, mid-line close resumes code, xml opener, no-block-comment languages ignore the flag; embedded languages: astro on the xml grammar, svelte/toml mappings, whole-file frontmatter + script/style blocks incl. lang="ts"/"scss" and a single-line script tag, hunk walk from line 1 and mid-file back to the first fence or closer, template-only hunk marks nothing, non-markup → null; shebangs: direct and env forms incl. -S and VAR=val, version suffixes, unknown interpreter and non-shebang → null, name and extension win over the shebang, diffFirstLine prefers the new side and falls back to a deleted file's old side), commitMessage (split/join round-trip, CRLF, second line without blank line is body, newline never enters the summary), fileFilter (empty/whitespace query passes all, case-insensitive substring, every term required), webUrl (https/scp/ssh:// remotes → repository page, ssh port dropped, http + web port kept, Bitbucket Server browse page, Bitbucket Cloud untouched, trailing slash, local path → null), blameable (hasCommittedHistory true for every tracked change kind, false for untracked and staged-new), imageMime (one media type per engine image extension, null otherwise), renderCap (lines at or under 5,000 chars stay whole, longer ones clip and count the hidden tail, custom cap), fork → upstream pull requests (github head `owner:branch`, gitlab GET target id then POST on the source project with target_project_id, bitbucket source.repository, forgeTargets dedupes same-host remotes and defaultForgeTarget prefers `upstream`), allFiles (tree paths marked with their change, deleted files kept, no duplicate paths, foldersWithChanges lists every ancestor of a changed file and nothing otherwise), fetchRemotes (continues after a failure and reports failures), patchText (headers + hunk headers + prefixed lines, rename old path, multi-file join, hasReviewableText rejects null/binary/image/empty), single-file review + explain prompts (file/where/sibling context lines, sibling cap at 30, section labels, conventions order, patch at the end, 4096-token budget), aiReport (labelled sections, bullet severities, continuation lines, verdict tones, unstructured fallback, bold inside a sentence is not a label), locateDiffLine (exact match prefers additions, deletion/context fallback, whitespace-insensitive whole-line hit, tiny/absent snippets null), commit review + explain prompts (commit line, file list capped at 30, conventions, patch at the end), terminalKeys (Alt+Up/Down map to ESC[1;3A/B on keydown only, every other modifier/key/phase left to xterm), chord (key from event.code so ⌥A stays A, unsupported keys null, id round-trip, exact modifier match, per-platform labels, no-modifier/reserved problems per platform, repoForChord lookup), repoGroups (empty/duplicate names ignoring case and the renamed group, least-used colour with wrap, recents bucketed in order with the rest ungrouped, a deleted group's paths fall back to ungrouped while empty groups stay listed, worktree inherits its main's group unless mapped itself, tabClusters/orderRepoTabs cluster open tabs by group with ungrouped last and leave a group-less strip alone, moveRepoGroup places a group before or after another and ignores self or unknown targets), tabLabels (unique names get no hint, nearest distinguishing parent folder, walks further up when parents collide, case-insensitive names and Windows separators), linePairs + pairHunk (the issue #62 hunk, single replacement always one row, comment block before a rewritten line, dissimilar deletion unpaired, pure runs unchanged, positional fallback past the cap, identical lines anchor, the demo load hunk; lineSimilarity ignores punctuation and repeats and compares symbol-only lines by text), remotes (pickRemote upstream → origin → first, pushSetsUpstream only for no upstream or the same remote), diffLocation (new line number for additions and context, old number and old path for a deletion, the clicked split pane wins, column only when given, none without a number on that side; columnAt counts characters from one, an emoji as one, nothing past the text or inside the clipped tail of a line over 5,000 characters) | -| E2E (153) | `tests/e2e/smoke.spec.ts` | the AI button in the commit message editor keeps the summary focused after the click and Escape closes the editor while the stubbed Ollama /api/chat answer is held (the late answer is discarded), then fills summary + description from the commit's own diff and saves, folder rows in the working-copy tree stage and unstage everything inside them (one engine call each, chevron still folds, indeterminate in All files), stepping with n / the header chevron / p marks the active change rows and counts "k of n changes" in inline, split and wrapped views, View options stays open across two toggles, Settings filter (autofocus, SSH-only, first catalog hit across sections, locate flash, section-label match, no results, Escape clears then closes, close resets, AI section preset), splash→welcome, the AI chip names Ollama on the demo defaults, reads Set up AI when the CLI provider has no agent, Claude Code once picked, turns ok after Test connection, stale when the provider changes back to Ollama, and survives a reload, Blame is disabled in the file menu and the diff header for the untracked demo file while a tracked file keeps it enabled, the remote row menu's Open in browser opens the demo remote's GitHub page in a popup and the palette lists Open repository in browser, the sidebar and graph branch menus carry a fast-forward entry next to merge that is disabled while the current branch is ahead, settings installs the command line tool, settings lists the demo editors and picking Zed relabels the toolbar button and its menu, the Pull options menu offers merge and rebase, the status bar reports Fetched just now after the auto fetch, retries every remote after a partial auto fetch failure, keeps the timestamp and faint failed remote hint through partial and offline fetches, updates the timestamp on Pull, and explains the disabled Fetch button when no remotes exist, the diff header's Blame button opens file history in the blame pane with the Working copy row selected, per-hunk author buttons and an uncommitted hunk that disappears when a commit row is picked, a Blame at this commit menu, the Diff view toggle brings the diff controls back and Escape returns to the graph, the palette's Blame… picks a file and opens its blame pane, open repo, graph, inspector, palette, search, conflict resolver line picks, single-conflict nav + per-conflict take-all, per-block conflict hand edit, interactive rebase dialog + multi-select squash, cherry-pick dialog with the source-reference checkbox on by default, multi-select cherry-pick listing both commits and confirming, diff auto-jump lands at the first change with no scroll animation (frame-traced scrollTop), long path stays inside the discard confirm dialog, commit action buttons stay inside a narrow working copy panel (the row wraps), sidebar branch names align with and without the HEAD tick (measured left offsets), hovering a working-copy file reveals its full path, opening a diff folds the sidebar away and the toggle brings back the graph, avatars stay visible after a diff open/close round-trip (stubbed Gravatar), diff text selection survives the right-click copy menu and Esc closes only the menu, sidebar lists the demo pull requests and the create dialog opens, reconnecting an account opens the prefilled token form with focus in the token field, a file history row's Open commit button closes the panel and selects that commit in the graph, the author box finds commits with the graph lanes intact and combines with the text search, commit search finds matches in the full graph (n of m pill, Enter/Previous step, query survives selecting another commit, Escape clears), a search result that lands after a click keeps the clicked commit selected while clicking a match moves the pill to 2 of n and Enter steps to 3, searching a commit hash jumps to it in the full graph, a short hash prefix jumps too while an unknown hex word says No matches, a missing hash keeps the graph with No matches, mod+f focuses the commit search, sidebar lists the demo worktrees (incl. a missing-folder row) and the new-worktree dialog re-suggests the folder as the branch name is typed, the inner line of a JSDoc block in the demo CommitGraph.tsx diff renders as one hljs-comment span (guards the DiffViewer → prepareCommentStates wiring, which the unit tests cannot see), collapse-all folds every section and branch folder and a reopened section comes back with its folders closed, the inspector keeps its width (±1px) when a diff folds the sidebar away and both widths return on Escape (measured via data-panel-id after dragging the sidebar handle), the commit box renders the summary larger and bolder than the description with Enter/Backspace moving between them and commit disabled on an empty summary, dragging the commit box's top edge grows the description and double-click resets it, the Changes header's fold button collapses that list's folders (nested file hidden) and flips to expand-all, and no fold button exists in flat mode, the top graph row shows a whole `main` chip with no HEAD chip and no clipped chip text plus a 7-char hash copy button, the graph display menu hides the hash column and brings it back, the sidebar accordion pins collapsed headers at the bottom under an open Branches section and moves the Tags header up when Tags opens, the welcome page flags the demo's missing folder and opens a repository via ↓ + ⏎ from the autofocused search, the conflict resolver renders positive integer line numbers in A, B and Result with each starting at 1, the checked-out branch chip is opaque while another local branch's chip stays translucent, double-clicking the separated `origin/main` chip opens the reset prompt naming the 2 commits that would be lost and Cancel dismisses it (the demo repo puts origin/main 2 commits behind main so the split is real), the diff header's History button opens that same file's history panel and closes the diff, a working-copy row's "Stash this file…" opens the dialog naming that file and the toolbar pop button restores the latest demo stash, shift-click selects three working-copy rows and the bulk menu offers Stage 3 / Stash 3 files, the working-copy filter hides non-matching rows with "1 of 2" counts and the clear button restores them, the commit file filter narrows five demo files to one and Escape resets it, selecting the demo stash shows the stash hint and the hover restore button on a file toasts the restore, right-clicking a plain commit's file offers File history / Show in Finder / Copy path and no stash Apply entry, staged rows offer discard from the row, the menu and the header trash icon, the sidebar is visible again after a reload that happened with a diff open, the demo stash renders as a graph row with an Archive node and a dashed chip whose menu pops it, ↓ then → opens the second commit's first file with the file list focused, ↓/↑ walk files, twelve → presses stay on the same file and one ← returns to the graph on the same commit, the Graph display menu's "Lane color band" removes and restores the tail rects, the inspector stops at its minimum width when dragged and folds/returns for file history, dragging the sidebar shut and back open in one gesture shows its content again, conflict picks land in file order with a mixed-state side checkbox, the resolver picks with A/B/↑/↓ and ⌘⏎ opens the next conflicted file, leaving with picks asks first while Escape closes a clean resolver, right-clicking the main tip row offers Push main ↑2 while an inner commit's menu has no push, hovering the feature/diff-viewer chip stacks both its refs in a panel whose first chip sits on the row chip (≤2px) with the folded `release/0.4` under it, and right-clicking that one opens its Checkout menu (no reset entry for a plain local), the top row shows `main` as its visible chip although `hotfix/lane-colors` comes first in the refs and only `main` carries the check inside the stacked panel, right-clicking the separated `origin/main` chip offers "Reset main to this…" and opens the same reset dialog, clicking a working-copy file then ↓/↓/↑ moves the diff through ipc.ts → palette-seed.sql → Architecture.md and back — the Remotes header's Add remote button opens the add dialog with the button disabled until name and URL are filled, right-clicking the terminal shows Copy (disabled without a selection)/Paste/Select all/Clear terminal, Settings → Git → Clone destination remembers a chosen folder and the clone dialog's destination starts there, a four-row drag selection in the palette-seed diff stays a Range and still copies all four lines via ⌘C after its rows scroll out of the virtualizer in either direction, and reads the same text once scrolled back, the pushed demo commit opens the editor and Save asks "Rewrite a pushed commit?" (Cancel keeps the draft) while the top commit opens the inline editor on double-click (Esc cancels, Save rewrites the heading, body and graph row), the GitHub account form keeps the classic token link and adds the fine-grained page inline while the Token label still focuses the input, the Fonts card's Interface picker lists proportional fonts first and Code lists monospace first, picking Helvetica Neue/Fira Code changes --font-sans/--font-mono and the terminal follows Code until Menlo + 16 px is picked for it, all of it survives a reload and Reset fonts clears it, sidebar section headers and bodies carry no fill and no top border while each header shows a filled gold icon tile and a filled count badge, the commit Files header's A token narrows five files to one with All pressed off and back, the All files view lists Roadmap.md at the commit with 5 changed, keeps a change-free folder collapsed until clicked, opens the unchanged file with an unchanged badge and no @@ header while Folder tree hides it again, the working copy's All files view shows README.md beside the stage/unstage checkboxes of the changed files and opens it without a Stage file button, dragging a selection below the diff grows it past six lines from the start row and ⌘C copies the same text before and after scrolling away, the diff header's AI actions menu reviews the open file (busy strip → demo response under the header, Copy, fold to one line and back, full-view dialog, button disabled meanwhile, closing and reopening the diff dismisses the result) then explains it and Dismiss removes the panel, the inspector's Review with AI reviews the selected commit (Stop reviewing while busy, AI review card → demo response, Dismiss), file history's diff pane shows no change arrows on a commit that did not touch palette-seed.sql and, on the Working copy row, `n` jumps the scroller to the one change, `p` from the top wraps to it and the header's Next change button lands on the same offset, a second repo opened from the palette becomes a tab that ⌘1 / ⌘⇧] switch between (wrapping), the tab menu's Keyboard shortcut… capture box flags a bare `t` as no_modifier and ⌘K as reserved without opening the palette, saving ⌃⇧T shows the chip on the tab and the chord switches to it, and Settings → Shortcuts lists and removes it, Force push from the Push menu opens a "Force push?" confirm naming origin/main that Cancel dismisses without pushing, and repositories can be grouped on the welcome page: Add to group → New group… creates Frontend with a picked colour (Create disabled on an empty name, a duplicate name shows the taken hint), dragging a row onto the header moves it (counts 2 and 2), Enter in the name field creates Backend, the header menu's Move up puts Backend first (Move down disabled at the bottom) and Move down restores it, the header button collapses and re-expands it, searching flattens the list to the two matching rows, Open all in tabs opens both Frontend repos as tabs whose titles end in · Frontend, the tab menu's Move to group re-homes one to Backend and the strip splits into two clusters with chips, clicking the Backend chip hides its tab and shows Backend1, collapsing Frontend keeps the active tab visible, ⌘2 switches to the hidden temple-ui and reveals it, both chips expand again, the Backend chip's menu counts 1 under Close its tabs and Collapse other groups folds Frontend to Frontend1 while ⌘1 still reaches its hidden tab, Expand all groups brings both back, dragging the Backend chip onto the first cluster's left edge puts Backend first so ⌘1 reaches temple-ui and dragging it back restores Frontend, narrowing the window to 300px shows the overflow list whose temple-ui entry switches tabs and widening hides it again, no separators or overflow button exist with two tabs, the switcher lists repos under data-switcher-group labels, the palette's Close all in Backend closes its one open tab while Open all in Backend says 2 repositories, and Ungroup… confirms and leaves the repos in the list, the long-line diff scrollbar stays at the viewport bottom, pans both split panes together, accepts arrow keys and Shift+wheel, and disappears when wrapping is enabled, the code diff opened from a selected commit also scrolls horizontally in inline and split views, and a trackpad pan of one wheel event per frame moves the long-line diff by the whole gesture with no backward step, dragging the drawn thumb moves the layers by exactly the engine's scrollLeft and a click on the track pages back to 0, and a text selection dragged past the pane's right edge pans the long lines, grows the selection and stops panning when the pointer comes back, scanning ~/projects from the welcome page lists four repos with two marked In recents and disabled, unticking one adds the other to the recents list, a seeded tab whose folder is missing closes with a toast while two same-named angkorgit tabs show forks / projects hints and a unique one shows none, ⌘P on the welcome page filters four recents to temple-ui and Enter opens it as the only tab, ⌘P marks it Current and opens angkorgit as a second tab, a third ⌘P marks temple-ui Open tab and switches back without a new tab, ⌘K still opens the command palette, and ⌘T opens a picked folder as a third tab, the all files layout stacks the five demo commit files with GraphRow.tsx scrolled to the top and "2 of 5", clicking Architecture.md in the inspector scrolls it to the top ("4 of 5"), side by side applies inside the cards, a user wheel at the top moves the inspector highlight to CommitGraph.tsx, one file and then all files collapse and expand, Show one file returns to DiffPanel and the choice survives a reload, clicking a file in the inspector still jumps to it after scrolling reached it once and ← inside the page returns to the graph, a stash file never offers the all files layout even with 'all' remembered while a plain commit still gets it, a click into a file diff followed by ← closes it and returns to the graph, ⌘⏎ with nothing staged toasts "Stage some changes first" and commits nothing, and a file filter that hides every staged file leaves Commit enabled with the full count, and eleven tabs shrink to fit an 820px window with the inactive close buttons gone and no overflow button, scroll past their 48px floor at 480px and come back to their natural widths at 1440px, and What's new opens from the welcome footer and the status bar bell with its unread dot cleared once seen and after a reload, and a drifted demo submodule row has no Discard button, its menu offers Update submodule to efec64c without Discard changes…, and its hover Update button toasts the checkout and clears the row, and the Pull button carries a conflict warning whose tooltip names the files, opens "This pull will conflict" (Cancel closes, Pull and resolve pulls), switches to "Your changes are in the way" whose Stash 2 files… opens the stash dialog with those files, and shows no warning without a predicted problem, and a failing demo pre-commit hook opens the hook dialog with ANSI-free lint output (Close keeps the message and commits nothing, Commit without hooks commits) while a ticked Skip hooks commits directly and clears itself, and a repo without hooks shows no Skip hooks box, and a hook that fails after switching to another tab only toasts "Nothing was committed in angkorgit" there (no dialog, no commit, the other tab never shows Running hooks…) while the first tab keeps its draft and shows the waiting failure when the user returns, a commit hook keeps Commit busy as Running hooks… across selecting a graph commit and coming back and its failure dialog appears while the graph commit is shown, and Commit without hooks never reads Running hooks… while text typed during the run survives the commit, and a failing demo pre-push hook makes the toolbar Push open "A hook stopped the push" with ANSI-free test output while the Push menu offers Push without hooks (absent in a repo without hooks) and the dialog's Push without hooks pushes main, and after a Push without hooks that the remote rejects as non-fast-forward the dialog's Force push keeps skipping the hook and pushes main forced, and when develop was checked out while the hook ran the rejected dialog still names origin/main with Pull with rebase disabled ("Check out main first…") and Cancel focused, nothing pulls, and once main is checked out again the same dialog enables and focuses Pull with rebase, which pulls, and a graph chip takes its lane colour while every lane line is a rail (no cubic curves) and the WIP banner is opaque, a 14-lane demo history scrolls the graph sideways by exactly each wheel step, by the drawn thumb and back to 0 on a track click while vertical scrolling stays put, and dragging the Graph header edge narrows the column and its scrollbar, survives a reload and double-click resets it, and a running demo post-checkout shows a loading toast and responds to a second checkout with an info toast naming post-checkout and the repository, with no red failure toast, and a failing demo post-checkout hook shows a warning toast after "Checkout develop done" whose Show output opens the warning dialog with ANSI-free output and only Copy output and Close, the Pull menu's Pull without hooks pulls without the post-merge warning a plain Pull then shows (and is absent without hooks), and Pull all puts a post-merge warning with a collapsed Hook output on every updated row ("2 hook warnings") while Pull all without hooks from the group menu shows none, and a hook folder inside the worktree offers Pull without hooks and Pull all without hooks before any hook exists (but no Push without hooks), and the Pull menu shows Pull without hooks after the hook setup changed between two opens, Pull without hooks with a predicted conflict opens "This pull will conflict" first and Pull and resolve then pulls without the post-merge warning, and discarding three selected files shows one post-checkout warning, while a bulk discard that fails for one file names it with the reason and shows no success toast, and so does the Staged header's Discard all staged changes, and the Only matches toggle narrows a "merge" search to the matching commits with "n matching commits", steps them with Enter and brings the full graph back on the same commit, also when the search box is cleared — all on demo mode, and a squeezed same-name tab hint stays at least 18px wide in a 480px window, and graph nodes whose lanes leave the column stay inside it, pinned to an edge, at rest and after scrolling right, and right-clicking the 7th character of a diff line offers Copy path and line with `path:line:7` (copied, toast) while a right-click past the end of the text drops the column, and two cmd-selected commits offer Compare these commits, which puts a From/To header over the newer commit's file list (no message editor or AI buttons), opens a file diff and the all files layout labelled `older..newer`, swaps the direction from the header and leaves compare mode on a plain click, while three selected commits get no Compare entry, and switching to light and back recolours every element on the repo page in the same frame while hover fades keep their duration | +| Rust integration (212 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | saved-account clone through the exact mock keychain entry, HTTPS host validation and local binding; config reads ignore inherited and included account bindings; stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | +| Rust module (120 macOS; platform cases in CI) | `src/commands.rs` (2), `src/core/submodule.rs` (2 atomic baseline-write tests), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (22), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (10), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/forge_repositories.rs` (3), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | +| Unit (345) | `tests/unit/*.test.ts` | saved-account pages (GitHub Enterprise aliases, GitLab paging behind a proxy, Bitbucket workspace continuation, unsafe links and rate limits), actionError (busy responses use info without a failure prefix, other errors keep default or custom formatting), themeContrast (every palette keeps body ≥ 7:1, muted ≥ 5.5:1, faint ≥ 4.5:1 against background and surface, in that order, and defines its own code comment colour), settingsFilter (AND terms, section labels, catalog coverage of every JSX card title), GraphLayout (incl. pagination stability, lane reuse), wordDiff (round-trip), conflict parse/serialize (diff3 labels, CRLF, bare markers, 8+-char content lines, close-without-separator — all lossless), cliAgents (per-agent argv/stdin shape incl. Cursor print mode with the prompt last, ANSI/OSC cleaning, output-file preference, error surfacing), aiProviders (empty/whitespace/missing content rejected for openai-compatible + ollama, HTTP status+body surfaced, real content passes; OpenAI itself gets max_completion_tokens while other compatible hosts and LM Studio keep max_tokens, a rejected temperature is dropped and remembered, a rejected max_tokens or max_completion_tokens swaps once and never loops, an unrelated 400 is not retried, a reasoning model that spent its budget thinking gets one retry at REASONING_MIN_TOKENS that sticks, a budget that ran out without reasoning explains itself), aiCapabilities (review conventions: absent by default, general-only, general+project order with precedence note, whitespace = absent, clipping), aiTextSegments (token parse: adjacent tokens, unclosed/inner-asterisk/multi-line markers stay literal, ** inside backticks is code), reviewSignature (staged-only, order-insensitive, unstaged-edit + set changes alter it, newline filenames don't collide, hashText determinism), commitStyle (prefix rule matching/tokens/ticket-fallthrough, `$`-sequence literalness, preset instructions, post-generation prefix enforcement), pullRequestUrl (https/scp/ssh remotes, non-standard ports kept, http preserved, ssh port dropped, Bitbucket Server /scm/ shape, .git-behind-slash strip, unknown forge → null), aiModels (per-provider list endpoints/headers incl. Groq-style base URLs, generateContent filtering for Gemini, dedupe/sort, invalid-JSON + HTTP-status errors, cli → empty without a request), forge (parseForgeRemote for all three forges + rejects, provider creation gating, github/gitlab/bitbucket adapters: request URLs, field mapping incl. fork + draft detection, create payloads, error-message surfacing incl. github field-level validation entries without a message, checkoutSpec shapes incl. bitbucket fork → null, pickForgeRemote upstream-first ordering, github 403 create refusals explained (fine-grained token into another owner's repo, missing pull request permission, rate limit left verbatim), gitlab self-hosted https→http transport fallback — GET-only (a retried POST could file a duplicate MR), never for gitlab.com or api-level errors, working scheme remembered per host and safe under concurrent fallbacks, reviewer candidates per forge + reviewer ids embedded/requested on create incl. github follow-up failure tolerance, authorAvatar per forge: github commit author, gitlab avatar-by-email URL encoding, bitbucket commit author user), worktree (folder-name slug from repo + branch, sibling-path suggestion incl. Windows separators, parentDirectory), highlight (block-comment continuation: JSDoc carried and closed, line comments and glob strings not treated as open, mid-line close resumes code, xml opener, no-block-comment languages ignore the flag; embedded languages: astro on the xml grammar, svelte/toml mappings, whole-file frontmatter + script/style blocks incl. lang="ts"/"scss" and a single-line script tag, hunk walk from line 1 and mid-file back to the first fence or closer, template-only hunk marks nothing, non-markup → null; shebangs: direct and env forms incl. -S and VAR=val, version suffixes, unknown interpreter and non-shebang → null, name and extension win over the shebang, diffFirstLine prefers the new side and falls back to a deleted file's old side), commitMessage (split/join round-trip, CRLF, second line without blank line is body, newline never enters the summary), fileFilter (empty/whitespace query passes all, case-insensitive substring, every term required), webUrl (https/scp/ssh:// remotes → repository page, ssh port dropped, http + web port kept, Bitbucket Server browse page, Bitbucket Cloud untouched, trailing slash, local path → null), blameable (hasCommittedHistory true for every tracked change kind, false for untracked and staged-new), imageMime (one media type per engine image extension, null otherwise), renderCap (lines at or under 5,000 chars stay whole, longer ones clip and count the hidden tail, custom cap), fork → upstream pull requests (github head `owner:branch`, gitlab GET target id then POST on the source project with target_project_id, bitbucket source.repository, forgeTargets dedupes same-host remotes and defaultForgeTarget prefers `upstream`), allFiles (tree paths marked with their change, deleted files kept, no duplicate paths, foldersWithChanges lists every ancestor of a changed file and nothing otherwise), fetchRemotes (continues after a failure and reports failures), patchText (headers + hunk headers + prefixed lines, rename old path, multi-file join, hasReviewableText rejects null/binary/image/empty), single-file review + explain prompts (file/where/sibling context lines, sibling cap at 30, section labels, conventions order, patch at the end, 4096-token budget), aiReport (labelled sections, bullet severities, continuation lines, verdict tones, unstructured fallback, bold inside a sentence is not a label), locateDiffLine (exact match prefers additions, deletion/context fallback, whitespace-insensitive whole-line hit, tiny/absent snippets null), commit review + explain prompts (commit line, file list capped at 30, conventions, patch at the end), terminalKeys (Alt+Up/Down map to ESC[1;3A/B on keydown only, every other modifier/key/phase left to xterm), chord (key from event.code so ⌥A stays A, unsupported keys null, id round-trip, exact modifier match, per-platform labels, no-modifier/reserved problems per platform, repoForChord lookup), repoGroups (empty/duplicate names ignoring case and the renamed group, least-used colour with wrap, recents bucketed in order with the rest ungrouped, a deleted group's paths fall back to ungrouped while empty groups stay listed, worktree inherits its main's group unless mapped itself, tabClusters/orderRepoTabs cluster open tabs by group with ungrouped last and leave a group-less strip alone, moveRepoGroup places a group before or after another and ignores self or unknown targets), tabLabels (unique names get no hint, nearest distinguishing parent folder, walks further up when parents collide, case-insensitive names and Windows separators), linePairs + pairHunk (the issue #62 hunk, single replacement always one row, comment block before a rewritten line, dissimilar deletion unpaired, pure runs unchanged, positional fallback past the cap, identical lines anchor, the demo load hunk; lineSimilarity ignores punctuation and repeats and compares symbol-only lines by text), remotes (pickRemote upstream → origin → first, pushSetsUpstream only for no upstream or the same remote), diffLocation (new line number for additions and context, old number and old path for a deletion, the clicked split pane wins, column only when given, none without a number on that side; columnAt counts characters from one, an emoji as one, nothing past the text or inside the clipped tail of a line over 5,000 characters) | +| E2E (156) | `tests/e2e/smoke.spec.ts` | saved-account cloning (account switches while loading, keyboard selection, retry, manual URL edits, cached pages across opens, and partial results after a page error), the AI button in the commit message editor keeps the summary focused after the click and Escape closes the editor while the stubbed Ollama /api/chat answer is held (the late answer is discarded), then fills summary + description from the commit's own diff and saves, folder rows in the working-copy tree stage and unstage everything inside them (one engine call each, chevron still folds, indeterminate in All files), stepping with n / the header chevron / p marks the active change rows and counts "k of n changes" in inline, split and wrapped views, View options stays open across two toggles, Settings filter (autofocus, SSH-only, first catalog hit across sections, locate flash, section-label match, no results, Escape clears then closes, close resets, AI section preset), splash→welcome, the AI chip names Ollama on the demo defaults, reads Set up AI when the CLI provider has no agent, Claude Code once picked, turns ok after Test connection, stale when the provider changes back to Ollama, and survives a reload, Blame is disabled in the file menu and the diff header for the untracked demo file while a tracked file keeps it enabled, the remote row menu's Open in browser opens the demo remote's GitHub page in a popup and the palette lists Open repository in browser, the sidebar and graph branch menus carry a fast-forward entry next to merge that is disabled while the current branch is ahead, settings installs the command line tool, settings lists the demo editors and picking Zed relabels the toolbar button and its menu, the Pull options menu offers merge and rebase, the status bar reports Fetched just now after the auto fetch, retries every remote after a partial auto fetch failure, keeps the timestamp and faint failed remote hint through partial and offline fetches, updates the timestamp on Pull, and explains the disabled Fetch button when no remotes exist, the diff header's Blame button opens file history in the blame pane with the Working copy row selected, per-hunk author buttons and an uncommitted hunk that disappears when a commit row is picked, a Blame at this commit menu, the Diff view toggle brings the diff controls back and Escape returns to the graph, the palette's Blame… picks a file and opens its blame pane, open repo, graph, inspector, palette, search, conflict resolver line picks, single-conflict nav + per-conflict take-all, per-block conflict hand edit, interactive rebase dialog + multi-select squash, cherry-pick dialog with the source-reference checkbox on by default, multi-select cherry-pick listing both commits and confirming, diff auto-jump lands at the first change with no scroll animation (frame-traced scrollTop), long path stays inside the discard confirm dialog, commit action buttons stay inside a narrow working copy panel (the row wraps), sidebar branch names align with and without the HEAD tick (measured left offsets), hovering a working-copy file reveals its full path, opening a diff folds the sidebar away and the toggle brings back the graph, avatars stay visible after a diff open/close round-trip (stubbed Gravatar), diff text selection survives the right-click copy menu and Esc closes only the menu, sidebar lists the demo pull requests and the create dialog opens, reconnecting an account opens the prefilled token form with focus in the token field, a file history row's Open commit button closes the panel and selects that commit in the graph, the author box finds commits with the graph lanes intact and combines with the text search, commit search finds matches in the full graph (n of m pill, Enter/Previous step, query survives selecting another commit, Escape clears), a search result that lands after a click keeps the clicked commit selected while clicking a match moves the pill to 2 of n and Enter steps to 3, searching a commit hash jumps to it in the full graph, a short hash prefix jumps too while an unknown hex word says No matches, a missing hash keeps the graph with No matches, mod+f focuses the commit search, sidebar lists the demo worktrees (incl. a missing-folder row) and the new-worktree dialog re-suggests the folder as the branch name is typed, the inner line of a JSDoc block in the demo CommitGraph.tsx diff renders as one hljs-comment span (guards the DiffViewer → prepareCommentStates wiring, which the unit tests cannot see), collapse-all folds every section and branch folder and a reopened section comes back with its folders closed, the inspector keeps its width (±1px) when a diff folds the sidebar away and both widths return on Escape (measured via data-panel-id after dragging the sidebar handle), the commit box renders the summary larger and bolder than the description with Enter/Backspace moving between them and commit disabled on an empty summary, dragging the commit box's top edge grows the description and double-click resets it, the Changes header's fold button collapses that list's folders (nested file hidden) and flips to expand-all, and no fold button exists in flat mode, the top graph row shows a whole `main` chip with no HEAD chip and no clipped chip text plus a 7-char hash copy button, the graph display menu hides the hash column and brings it back, the sidebar accordion pins collapsed headers at the bottom under an open Branches section and moves the Tags header up when Tags opens, the welcome page flags the demo's missing folder and opens a repository via ↓ + ⏎ from the autofocused search, the conflict resolver renders positive integer line numbers in A, B and Result with each starting at 1, the checked-out branch chip is opaque while another local branch's chip stays translucent, double-clicking the separated `origin/main` chip opens the reset prompt naming the 2 commits that would be lost and Cancel dismisses it (the demo repo puts origin/main 2 commits behind main so the split is real), the diff header's History button opens that same file's history panel and closes the diff, a working-copy row's "Stash this file…" opens the dialog naming that file and the toolbar pop button restores the latest demo stash, shift-click selects three working-copy rows and the bulk menu offers Stage 3 / Stash 3 files, the working-copy filter hides non-matching rows with "1 of 2" counts and the clear button restores them, the commit file filter narrows five demo files to one and Escape resets it, selecting the demo stash shows the stash hint and the hover restore button on a file toasts the restore, right-clicking a plain commit's file offers File history / Show in Finder / Copy path and no stash Apply entry, staged rows offer discard from the row, the menu and the header trash icon, the sidebar is visible again after a reload that happened with a diff open, the demo stash renders as a graph row with an Archive node and a dashed chip whose menu pops it, ↓ then → opens the second commit's first file with the file list focused, ↓/↑ walk files, twelve → presses stay on the same file and one ← returns to the graph on the same commit, the Graph display menu's "Lane color band" removes and restores the tail rects, the inspector stops at its minimum width when dragged and folds/returns for file history, dragging the sidebar shut and back open in one gesture shows its content again, conflict picks land in file order with a mixed-state side checkbox, the resolver picks with A/B/↑/↓ and ⌘⏎ opens the next conflicted file, leaving with picks asks first while Escape closes a clean resolver, right-clicking the main tip row offers Push main ↑2 while an inner commit's menu has no push, hovering the feature/diff-viewer chip stacks both its refs in a panel whose first chip sits on the row chip (≤2px) with the folded `release/0.4` under it, and right-clicking that one opens its Checkout menu (no reset entry for a plain local), the top row shows `main` as its visible chip although `hotfix/lane-colors` comes first in the refs and only `main` carries the check inside the stacked panel, right-clicking the separated `origin/main` chip offers "Reset main to this…" and opens the same reset dialog, clicking a working-copy file then ↓/↓/↑ moves the diff through ipc.ts → palette-seed.sql → Architecture.md and back — the Remotes header's Add remote button opens the add dialog with the button disabled until name and URL are filled, right-clicking the terminal shows Copy (disabled without a selection)/Paste/Select all/Clear terminal, Settings → Git → Clone destination remembers a chosen folder and the clone dialog's destination starts there, a four-row drag selection in the palette-seed diff stays a Range and still copies all four lines via ⌘C after its rows scroll out of the virtualizer in either direction, and reads the same text once scrolled back, the pushed demo commit opens the editor and Save asks "Rewrite a pushed commit?" (Cancel keeps the draft) while the top commit opens the inline editor on double-click (Esc cancels, Save rewrites the heading, body and graph row), the GitHub account form keeps the classic token link and adds the fine-grained page inline while the Token label still focuses the input, the Fonts card's Interface picker lists proportional fonts first and Code lists monospace first, picking Helvetica Neue/Fira Code changes --font-sans/--font-mono and the terminal follows Code until Menlo + 16 px is picked for it, all of it survives a reload and Reset fonts clears it, sidebar section headers and bodies carry no fill and no top border while each header shows a filled gold icon tile and a filled count badge, the commit Files header's A token narrows five files to one with All pressed off and back, the All files view lists Roadmap.md at the commit with 5 changed, keeps a change-free folder collapsed until clicked, opens the unchanged file with an unchanged badge and no @@ header while Folder tree hides it again, the working copy's All files view shows README.md beside the stage/unstage checkboxes of the changed files and opens it without a Stage file button, dragging a selection below the diff grows it past six lines from the start row and ⌘C copies the same text before and after scrolling away, the diff header's AI actions menu reviews the open file (busy strip → demo response under the header, Copy, fold to one line and back, full-view dialog, button disabled meanwhile, closing and reopening the diff dismisses the result) then explains it and Dismiss removes the panel, the inspector's Review with AI reviews the selected commit (Stop reviewing while busy, AI review card → demo response, Dismiss), file history's diff pane shows no change arrows on a commit that did not touch palette-seed.sql and, on the Working copy row, `n` jumps the scroller to the one change, `p` from the top wraps to it and the header's Next change button lands on the same offset, a second repo opened from the palette becomes a tab that ⌘1 / ⌘⇧] switch between (wrapping), the tab menu's Keyboard shortcut… capture box flags a bare `t` as no_modifier and ⌘K as reserved without opening the palette, saving ⌃⇧T shows the chip on the tab and the chord switches to it, and Settings → Shortcuts lists and removes it, Force push from the Push menu opens a "Force push?" confirm naming origin/main that Cancel dismisses without pushing, and repositories can be grouped on the welcome page: Add to group → New group… creates Frontend with a picked colour (Create disabled on an empty name, a duplicate name shows the taken hint), dragging a row onto the header moves it (counts 2 and 2), Enter in the name field creates Backend, the header menu's Move up puts Backend first (Move down disabled at the bottom) and Move down restores it, the header button collapses and re-expands it, searching flattens the list to the two matching rows, Open all in tabs opens both Frontend repos as tabs whose titles end in · Frontend, the tab menu's Move to group re-homes one to Backend and the strip splits into two clusters with chips, clicking the Backend chip hides its tab and shows Backend1, collapsing Frontend keeps the active tab visible, ⌘2 switches to the hidden temple-ui and reveals it, both chips expand again, the Backend chip's menu counts 1 under Close its tabs and Collapse other groups folds Frontend to Frontend1 while ⌘1 still reaches its hidden tab, Expand all groups brings both back, dragging the Backend chip onto the first cluster's left edge puts Backend first so ⌘1 reaches temple-ui and dragging it back restores Frontend, narrowing the window to 300px shows the overflow list whose temple-ui entry switches tabs and widening hides it again, no separators or overflow button exist with two tabs, the switcher lists repos under data-switcher-group labels, the palette's Close all in Backend closes its one open tab while Open all in Backend says 2 repositories, and Ungroup… confirms and leaves the repos in the list, the long-line diff scrollbar stays at the viewport bottom, pans both split panes together, accepts arrow keys and Shift+wheel, and disappears when wrapping is enabled, the code diff opened from a selected commit also scrolls horizontally in inline and split views, and a trackpad pan of one wheel event per frame moves the long-line diff by the whole gesture with no backward step, dragging the drawn thumb moves the layers by exactly the engine's scrollLeft and a click on the track pages back to 0, and a text selection dragged past the pane's right edge pans the long lines, grows the selection and stops panning when the pointer comes back, scanning ~/projects from the welcome page lists four repos with two marked In recents and disabled, unticking one adds the other to the recents list, a seeded tab whose folder is missing closes with a toast while two same-named angkorgit tabs show forks / projects hints and a unique one shows none, ⌘P on the welcome page filters four recents to temple-ui and Enter opens it as the only tab, ⌘P marks it Current and opens angkorgit as a second tab, a third ⌘P marks temple-ui Open tab and switches back without a new tab, ⌘K still opens the command palette, and ⌘T opens a picked folder as a third tab, the all files layout stacks the five demo commit files with GraphRow.tsx scrolled to the top and "2 of 5", clicking Architecture.md in the inspector scrolls it to the top ("4 of 5"), side by side applies inside the cards, a user wheel at the top moves the inspector highlight to CommitGraph.tsx, one file and then all files collapse and expand, Show one file returns to DiffPanel and the choice survives a reload, clicking a file in the inspector still jumps to it after scrolling reached it once and ← inside the page returns to the graph, a stash file never offers the all files layout even with 'all' remembered while a plain commit still gets it, a click into a file diff followed by ← closes it and returns to the graph, ⌘⏎ with nothing staged toasts "Stage some changes first" and commits nothing, and a file filter that hides every staged file leaves Commit enabled with the full count, and eleven tabs shrink to fit an 820px window with the inactive close buttons gone and no overflow button, scroll past their 48px floor at 480px and come back to their natural widths at 1440px, and What's new opens from the welcome footer and the status bar bell with its unread dot cleared once seen and after a reload, and a drifted demo submodule row has no Discard button, its menu offers Update submodule to efec64c without Discard changes…, and its hover Update button toasts the checkout and clears the row, and the Pull button carries a conflict warning whose tooltip names the files, opens "This pull will conflict" (Cancel closes, Pull and resolve pulls), switches to "Your changes are in the way" whose Stash 2 files… opens the stash dialog with those files, and shows no warning without a predicted problem, and a failing demo pre-commit hook opens the hook dialog with ANSI-free lint output (Close keeps the message and commits nothing, Commit without hooks commits) while a ticked Skip hooks commits directly and clears itself, and a repo without hooks shows no Skip hooks box, and a hook that fails after switching to another tab only toasts "Nothing was committed in angkorgit" there (no dialog, no commit, the other tab never shows Running hooks…) while the first tab keeps its draft and shows the waiting failure when the user returns, a commit hook keeps Commit busy as Running hooks… across selecting a graph commit and coming back and its failure dialog appears while the graph commit is shown, and Commit without hooks never reads Running hooks… while text typed during the run survives the commit, and a failing demo pre-push hook makes the toolbar Push open "A hook stopped the push" with ANSI-free test output while the Push menu offers Push without hooks (absent in a repo without hooks) and the dialog's Push without hooks pushes main, and after a Push without hooks that the remote rejects as non-fast-forward the dialog's Force push keeps skipping the hook and pushes main forced, and when develop was checked out while the hook ran the rejected dialog still names origin/main with Pull with rebase disabled ("Check out main first…") and Cancel focused, nothing pulls, and once main is checked out again the same dialog enables and focuses Pull with rebase, which pulls, and a graph chip takes its lane colour while every lane line is a rail (no cubic curves) and the WIP banner is opaque, a 14-lane demo history scrolls the graph sideways by exactly each wheel step, by the drawn thumb and back to 0 on a track click while vertical scrolling stays put, and dragging the Graph header edge narrows the column and its scrollbar, survives a reload and double-click resets it, and a running demo post-checkout shows a loading toast and responds to a second checkout with an info toast naming post-checkout and the repository, with no red failure toast, and a failing demo post-checkout hook shows a warning toast after "Checkout develop done" whose Show output opens the warning dialog with ANSI-free output and only Copy output and Close, the Pull menu's Pull without hooks pulls without the post-merge warning a plain Pull then shows (and is absent without hooks), and Pull all puts a post-merge warning with a collapsed Hook output on every updated row ("2 hook warnings") while Pull all without hooks from the group menu shows none, and a hook folder inside the worktree offers Pull without hooks and Pull all without hooks before any hook exists (but no Push without hooks), and the Pull menu shows Pull without hooks after the hook setup changed between two opens, Pull without hooks with a predicted conflict opens "This pull will conflict" first and Pull and resolve then pulls without the post-merge warning, and discarding three selected files shows one post-checkout warning, while a bulk discard that fails for one file names it with the reason and shows no success toast, and so does the Staged header's Discard all staged changes, and the Only matches toggle narrows a "merge" search to the matching commits with "n matching commits", steps them with Enter and brings the full graph back on the same commit, also when the search box is cleared — all on demo mode, and a squeezed same-name tab hint stays at least 18px wide in a 480px window, and graph nodes whose lanes leave the column stay inside it, pinned to an edge, at rest and after scrolling right, and right-clicking the 7th character of a diff line offers Copy path and line with `path:line:7` (copied, toast) while a right-click past the end of the text drops the column, and two cmd-selected commits offer Compare these commits, which puts a From/To header over the newer commit's file list (no message editor or AI buttons), opens a file diff and the all files layout labelled `older..newer`, swaps the direction from the header and leaves compare mode on a plain click, while three selected commits get no Compare entry, and switching to light and back recolours every element on the repo page in the same frame while hover fades keep their duration | ## 9.5 Open-source & community files diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 89dc5883..48372b9f 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -4,6 +4,7 @@ use std::sync::{Mutex, OnceLock}; use tauri::{AppHandle, Emitter, State}; +use crate::core::accounts::AccountRef; use crate::core::post_hooks::{self, Hooked}; use crate::core::types::*; use crate::core::{ @@ -198,26 +199,45 @@ pub async fn repo_clone( url: String, into: String, branch: Option, + account: Option, ) -> AppResult { let emitter = app.clone(); + let rejected_account = account.clone(); let cloned = blocking_post_hooks(&app, into, move |into| { post_hooks::clone( &url, into, branch.as_deref(), + account.as_ref(), move |pct| { let _ = emitter.emit("clone-progress", pct); }, false, ) }) - .await?; + .await; + if matches!(&cloned, Err(AppError::Git(error)) if error.code() == git2::ErrorCode::Auth) { + if let Some(account) = rejected_account { + confirm_clone_account_rejection(account).await; + } + } + let cloned = cloned?; let root = cloned.value.clone(); report(&app, &root, cloned); crate::state::recent_add(&app, &root)?; Ok(root) } +async fn confirm_clone_account_rejection(account: AccountRef) { + let selected = account.clone(); + let Ok((info, token)) = blocking(move || selected.with_token()).await else { + return; + }; + if crate::forge_repositories::account_token_rejected(&info, &token).await { + let _ = blocking(move || account.mark_rejected(&token)).await; + } +} + #[tauri::command] pub fn recent_repositories(app: AppHandle) -> AppResult> { crate::state::recent_list(&app) @@ -239,8 +259,18 @@ pub fn recent_remove(app: AppHandle, path: String) -> AppResult, key: String) -> AppResult> { - blocking(move || repo::get_config(path.as_deref(), &key)).await +pub async fn config_get( + path: Option, + key: String, + local: Option, +) -> AppResult> { + blocking(move || { + if let (true, Some(path)) = (local.unwrap_or(false), path.as_deref()) { + return repo::get_local_config(path, &key); + } + repo::get_config(path.as_deref(), &key) + }) + .await } #[tauri::command] @@ -1125,6 +1155,16 @@ pub fn account_list() -> Vec { crate::core::accounts::list() } +#[tauri::command] +pub async fn account_forge_request( + host: String, + username: String, + url: String, +) -> AppResult { + let (account, token) = blocking(move || AccountRef { host, username }.with_token()).await?; + crate::forge_repositories::request(&account, &token, url).await +} + #[tauri::command] pub async fn account_add( host: String, diff --git a/apps/desktop/src-tauri/src/core/accounts.rs b/apps/desktop/src-tauri/src/core/accounts.rs index 8113a86d..1f018c3d 100644 --- a/apps/desktop/src-tauri/src/core/accounts.rs +++ b/apps/desktop/src-tauri/src/core/accounts.rs @@ -36,6 +36,84 @@ pub struct AccountInfo { pub is_default: bool, } +#[derive(Clone, Deserialize)] +pub struct AccountRef { + pub host: String, + pub username: String, +} + +impl AccountRef { + pub fn with_token(&self) -> AppResult<(AccountInfo, String)> { + self.resolve(&list(), token_of) + } + + pub fn mark_rejected(&self, token: &str) -> AppResult<()> { + let host = normalize_host(&self.host); + let Ok(cache) = token_cache().lock() else { + return Ok(()); + }; + if cache + .get(&entry_name(&host, &self.username)) + .and_then(Option::as_deref) + != Some(token) + { + return Ok(()); + } + mark_matching_unverified(|account| { + account.host == host + && account.username == self.username + && (account.verified || account.verified_at.is_none()) + }) + } + + fn resolve( + &self, + accounts: &[AccountInfo], + token: impl FnOnce(&str, &str) -> Option, + ) -> AppResult<(AccountInfo, String)> { + let host = normalize_host(&self.host); + let account = find_in(accounts, &host, &self.username).ok_or_else(|| { + AppError::other(format!( + "The saved account {} on {host} no longer exists.", + self.username + )) + })?; + let token = token(&account.host, &account.username).ok_or_else(|| { + AppError::other(format!( + "The token for {} on {} is missing from the system keychain. Reconnect the account in Settings → Authentication.", + account.username, account.host + )) + })?; + Ok((account.clone(), token)) + } +} + +pub fn https_account_origin(host: &str) -> Option { + let url = reqwest::Url::parse(&format!("https://{host}/")).ok()?; + (url.host().is_some() + && url.username().is_empty() + && url.password().is_none() + && url.path() == "/" + && url.query().is_none() + && url.fragment().is_none()) + .then_some(url) +} + +pub fn clone_url(account: &AccountInfo, raw: &str) -> Option { + let url = reqwest::Url::parse(raw).ok()?; + let origin = https_account_origin(&account.host)?; + (matches!( + account.provider.as_str(), + "github" | "gitlab" | "gitlab-self" | "bitbucket" + ) && url.origin() == origin.origin() + && url.username().is_empty() + && url.password().is_none() + && url.query().is_none() + && url.fragment().is_none() + && url.path() != "/") + .then_some(url) +} + fn meta_path() -> Option { CONFIG_DIR.get().map(|dir| dir.join("accounts.json")) } @@ -140,8 +218,12 @@ fn save_list(accounts: &[AccountInfo]) -> AppResult<()> { pub fn find(host: &str, username: &str) -> Option { let host = normalize_host(host); - list() - .into_iter() + find_in(&list(), &host, username).cloned() +} + +fn find_in<'a>(accounts: &'a [AccountInfo], host: &str, username: &str) -> Option<&'a AccountInfo> { + accounts + .iter() .find(|a| a.host == host && a.username == username) } @@ -296,10 +378,16 @@ pub fn candidates(host: &str, preferred: Option<&str>) -> Vec<(String, String)> pub fn mark_unverified(host: &str, username: &str) -> AppResult<()> { let host = normalize_host(host); + mark_matching_unverified(|account| { + account.verified && hosts_match(&account.host, &host) && account.username == username + }) +} + +fn mark_matching_unverified(matches: impl Fn(&AccountInfo) -> bool) -> AppResult<()> { let mut accounts = list(); let mut changed = false; for account in accounts.iter_mut() { - if hosts_match(&account.host, &host) && account.username == username && account.verified { + if matches(account) { account.verified = false; account.verified_at = Some(now_epoch()); changed = true; @@ -408,6 +496,107 @@ mod tests { assert!(accounts[0].is_default); } + #[test] + fn selecting_a_saved_account_never_uses_the_host_default() { + let accounts = [ + account("github.com", "work", true), + account("github.com", "personal", false), + ]; + let selected = AccountRef { + host: "github.com".into(), + username: "personal".into(), + }; + let (account, token) = selected + .resolve(&accounts, |host, username| { + assert_eq!((host, username), ("github.com", "personal")); + Some("personal-token".into()) + }) + .unwrap(); + assert_eq!(account.username, "personal"); + assert_eq!(token, "personal-token"); + + let missing = selected.resolve(&accounts, |_, username| { + assert_eq!(username, "personal"); + None + }); + assert!( + matches!(missing, Err(error) if error.to_string().contains("missing from the system keychain")) + ); + let removed = selected.resolve(&accounts[..1], |_, _| { + panic!("must not look up another account's token") + }); + assert!(matches!(removed, Err(error) if error.to_string().contains("no longer exists"))); + } + + #[test] + fn account_clone_urls_are_credential_free_and_match_the_saved_origin() { + let work = account("github.com", "work", true); + assert!(clone_url(&work, "https://github.com:443/org/repo.git").is_some()); + for url in [ + "https://github.com.example.org/org/repo.git", + "https://github.com:8443/org/repo.git", + "https://api.github.com/org/repo.git", + "https://user:secret@github.com/org/repo.git", + "https://github.com/org/repo.git?token=secret", + "http://github.com/org/repo.git", + "git@github.com:org/repo.git", + ] { + assert!(clone_url(&work, url).is_none(), "{url}"); + } + let self_hosted = AccountInfo { + provider: "gitlab-self".into(), + ..account("git.local:8080", "work", true) + }; + assert!(clone_url(&self_hosted, "https://git.local:8080/org/subgroup/repo.git").is_some()); + assert!(clone_url(&self_hosted, "http://git.local:8080/org/subgroup/repo.git").is_none()); + } + + #[test] + fn a_recorded_rejection_preserves_the_preferred_git_credential() { + let dir = tempfile::tempdir().unwrap(); + CONFIG_DIR.set(dir.path().to_path_buf()).unwrap(); + let host = "git.example.test"; + let selected = AccountRef { + host: host.into(), + username: "work".into(), + }; + let unchecked = AccountInfo { + verified: false, + ..account(host, "personal", false) + }; + save_list(&[ + account(host, "work", true), + account("git.example.test:8443", "work", true), + unchecked, + ]) + .unwrap(); + token_cache().lock().unwrap().extend([ + (entry_name(host, "work"), Some("current-token".into())), + ( + entry_name("git.example.test:8443", "work"), + Some("other-port-token".into()), + ), + (entry_name(host, "personal"), Some("unchecked-token".into())), + ]); + + selected.mark_rejected("previous-token").unwrap(); + assert!(find(host, "work").unwrap().verified); + selected.mark_rejected("current-token").unwrap(); + let rejected = find(host, "work").unwrap(); + assert!(!rejected.verified); + assert!(rejected.verified_at.is_some()); + assert!(find("git.example.test:8443", "work").unwrap().verified); + let usable = candidates(host, Some("work")); + assert_eq!( + usable, + [ + ("work".into(), "current-token".into()), + ("work".into(), "other-port-token".into()), + ("personal".into(), "unchecked-token".into()), + ] + ); + } + #[test] fn ordered_for_host_puts_preferred_before_default() { let accounts = vec![ diff --git a/apps/desktop/src-tauri/src/core/post_hooks.rs b/apps/desktop/src-tauri/src/core/post_hooks.rs index 893f26de..dc3cccb3 100644 --- a/apps/desktop/src-tauri/src/core/post_hooks.rs +++ b/apps/desktop/src-tauri/src/core/post_hooks.rs @@ -2,6 +2,7 @@ use std::path::Path; use git2::Oid; +use super::accounts::AccountRef; use super::hooks::{run_post, PostHook, PostHooks}; use super::types::{ CommitOutcome, DiscardBatch, DiscardFailure, HookWarning, OpOutcome, RebaseTodoEntry, @@ -331,10 +332,11 @@ pub fn clone( url: &str, into: &str, branch: Option<&str>, + account: Option<&AccountRef>, on_progress: impl Fn(u32) + Send, no_verify: bool, ) -> AppResult> { - let root = remote::clone(url, into, branch, on_progress)?; + let root = remote::clone(url, into, branch, account, on_progress)?; let path = root.clone(); Ok(checked_out(&path, root, no_verify)) } diff --git a/apps/desktop/src-tauri/src/core/remote.rs b/apps/desktop/src-tauri/src/core/remote.rs index 155cfebc..e8844ede 100644 --- a/apps/desktop/src-tauri/src/core/remote.rs +++ b/apps/desktop/src-tauri/src/core/remote.rs @@ -6,11 +6,12 @@ use std::sync::{Arc, Mutex, OnceLock, RwLock}; use git2::{ build::CheckoutBuilder, AutotagOption, Cred, CredentialType, FetchOptions, PushOptions, - RemoteCallbacks, Repository, + RemoteCallbacks, RemoteRedirect, Repository, }; use crate::error::{AppError, AppResult}; +use super::accounts::{self, AccountInfo, AccountRef}; use super::group_update::{FetchProgress, GroupUpdateControl}; use super::hooks::{pre_push_input, PostHook, PostHooks, PrePush, PushedRef}; use super::types::{GeneratedKey, GroupUpdateResult, OpOutcome, RefMovement, RemoteInfo}; @@ -288,8 +289,12 @@ fn refused_account_hint(offered: &Mutex>) -> String { return String::new(); }; let _ = super::accounts::mark_unverified(&host, &username); + format!(" {}", refused_account_message(&host, &username)) +} + +fn refused_account_message(host: &str, username: &str) -> String { format!( - " The connected {host} account '{username}' was refused — its token may have expired \ + "The connected {host} account '{username}' was refused — its token may have expired \ or been revoked. Reconnect it in Settings → Authentication." ) } @@ -1514,10 +1519,101 @@ pub fn clone( url: &str, into: &str, branch: Option<&str>, + account: Option<&AccountRef>, on_progress: impl Fn(u32) + Send, ) -> AppResult { prime_account_bindings(None); - let mut callbacks = make_callbacks(); + let saved = account + .map(|account| { + let (account, token) = account.with_token()?; + SavedClone::new(&account, token, url) + }) + .transpose()?; + let repo = clone_repository(url, Path::new(into), branch, saved, on_progress)?; + let root = repo + .workdir() + .unwrap_or_else(|| repo.path()) + .to_string_lossy() + .trim_end_matches('/') + .to_string(); + Ok(root) +} + +struct SavedClone { + url: reqwest::Url, + account: AccountRef, + token: String, +} + +impl SavedClone { + fn new(account: &AccountInfo, token: String, url: &str) -> AppResult { + let url = accounts::clone_url(account, url).ok_or_else(|| { + AppError::other("The clone URL does not match the selected saved account.") + })?; + Ok(Self { + url, + account: AccountRef { + host: account.host.clone(), + username: account.username.clone(), + }, + token, + }) + } + + fn callbacks(self) -> RemoteCallbacks<'static> { + let mut callbacks = RemoteCallbacks::new(); + let mut offered = false; + callbacks.credentials(move |url, _, allowed| { + if reqwest::Url::parse(url).is_ok_and(|url| url.origin() == self.url.origin()) + && allowed.contains(CredentialType::USER_PASS_PLAINTEXT) + { + if offered { + return Err(git2::Error::new( + git2::ErrorCode::Auth, + git2::ErrorClass::Http, + format!( + "This repository refused the saved account {} on {}. Check repository access or reconnect the account in Settings → Authentication.", + self.account.username, self.account.host + ), + )); + } + let credential = Cred::userpass_plaintext(&self.account.username, &self.token)?; + offered = true; + return Ok(credential); + } + Err(git2::Error::from_str(&format!( + "Could not authenticate with {} on {}. Check repository access or reconnect the account in Settings → Authentication.", + self.account.username, self.account.host + ))) + }); + callbacks + } +} + +fn clone_repository( + url: &str, + into: &Path, + branch: Option<&str>, + saved: Option, + on_progress: impl Fn(u32) + Send, +) -> AppResult { + let mut builder = git2::build::RepoBuilder::new(); + let mut opts = FetchOptions::new(); + let saved_url = saved.as_ref().map(|saved| saved.url.to_string()); + let mut callbacks = if let Some(saved) = saved { + let host = accounts::host_of_url(saved.url.as_str()).expect("saved clone URL has a host"); + let binding = format!("{host}={}", saved.account.username); + builder.remote_create(move |repo, name, url| { + repo.config()? + .open_level(git2::ConfigLevel::Local)? + .set_str("angkorgit.accounts", &binding)?; + repo.remote(name, url) + }); + opts.follow_redirects(RemoteRedirect::None); + saved.callbacks() + } else { + make_callbacks() + }; let mut last_pct: Option = None; callbacks.transfer_progress(move |stats| { let total = stats.total_objects().max(1); @@ -1528,22 +1624,13 @@ pub fn clone( } true }); - let mut opts = FetchOptions::new(); opts.remote_callbacks(callbacks); - let mut builder = git2::build::RepoBuilder::new(); builder.fetch_options(opts); if let Some(branch) = branch { builder.branch(branch); } - let repo = builder.clone(url, std::path::Path::new(into))?; - let root = repo - .workdir() - .unwrap_or_else(|| repo.path()) - .to_string_lossy() - .trim_end_matches('/') - .to_string(); - Ok(root) + Ok(builder.clone(saved_url.as_deref().unwrap_or(url), into)?) } #[allow(dead_code)] @@ -1744,6 +1831,113 @@ mod tests { assert_eq!(ssh_key_candidates(Some(" "), Some(&home()), &[]).len(), 2); } + fn git_auth_server(accepts_token: bool) -> (SavedClone, std::thread::JoinHandle<()>) { + use std::io::{BufRead, BufReader, Write}; + use std::net::TcpListener; + use std::time::Duration; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let host = listener.local_addr().unwrap().to_string(); + let url = format!("http://{host}/origin.git"); + let server = std::thread::spawn(move || { + for authorized in [false, true] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let headers: Vec<_> = BufReader::new(&stream) + .lines() + .map(Result::unwrap) + .take_while(|line| !line.is_empty()) + .collect(); + let authorization = headers.iter().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("authorization") + .then(|| value.trim()) + }); + if authorized { + assert_eq!( + authorization, + Some("Basic cGVyc29uYWw6c2VsZWN0ZWQtdG9rZW4=") + ); + } else { + assert!(authorization.is_none()); + } + if authorized && accepts_token { + let service = "# service=git-upload-pack\n"; + let ref_line = format!( + "{} capabilities^{{}}\0symref=HEAD:refs/heads/main\n", + "0".repeat(40) + ); + let body = format!( + "{:04x}{service}0000{:04x}{ref_line}0000", + service.len() + 4, + ref_line.len() + 4 + ); + write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/x-git-upload-pack-advertisement\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}", body.len()).unwrap(); + } else { + write!(stream, "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"test\"\r\nConnection: close\r\nContent-Length: 0\r\n\r\n").unwrap(); + } + } + }); + let saved = SavedClone { + url: reqwest::Url::parse(&url).unwrap(), + account: AccountRef { + host, + username: "personal".into(), + }, + token: "selected-token".into(), + }; + (saved, server) + } + + #[test] + fn saved_account_clone_authenticates_and_records_the_local_binding() { + let target = tempfile::tempdir().unwrap(); + let (saved, server) = git_auth_server(true); + let host = saved.account.host.clone(); + let url = saved.url.to_string(); + let repo = clone_repository( + &url, + &target.path().join("cloned"), + None, + Some(saved), + |_| {}, + ) + .unwrap(); + server.join().unwrap(); + assert_eq!( + read_account_bindings(&repo).get(&host).map(String::as_str), + Some("personal") + ); + assert_eq!( + repo.find_remote("origin").unwrap().url(), + Some(url.as_str()) + ); + } + + #[test] + fn saved_account_clone_reports_a_refusal_as_a_repository_auth_error() { + let target = tempfile::tempdir().unwrap(); + let (saved, server) = git_auth_server(false); + let url = saved.url.to_string(); + let result = clone_repository( + &url, + &target.path().join("cloned"), + None, + Some(saved), + |_| {}, + ); + let Err(AppError::Git(error)) = result else { + panic!("expected clone authentication to fail") + }; + server.join().unwrap(); + assert_eq!(error.code(), git2::ErrorCode::Auth); + assert!(error + .message() + .contains("This repository refused the saved account")); + } + #[test] fn plain_push_refspecs_have_no_force_prefix() { assert_eq!( diff --git a/apps/desktop/src-tauri/src/core/repo.rs b/apps/desktop/src-tauri/src/core/repo.rs index f161b4a6..cdbc5070 100644 --- a/apps/desktop/src-tauri/src/core/repo.rs +++ b/apps/desktop/src-tauri/src/core/repo.rs @@ -246,7 +246,29 @@ pub fn get_config(repo_path: Option<&str>, key: &str) -> AppResult AppResult> { + let config = open(repo_path)? + .config()? + .open_level(git2::ConfigLevel::Local)?; + let mut entries = config.entries(None)?; + let mut value = None; + while let Some(entry) = entries.next() { + let entry = entry?; + if entry.include_depth() == 0 && entry.name() == Some(key) { + value = entry.value().map(str::to_owned); + } + } + Ok(value) +} + pub fn set_config(repo_path: Option<&str>, key: &str, value: &str, global: bool) -> AppResult<()> { + if let (false, Some(path), "angkorgit.accounts") = (global, repo_path, key) { + open(path)? + .config()? + .open_level(git2::ConfigLevel::Local)? + .set_multivar(key, ".*", value)?; + return Ok(()); + } let mut config = match (global, repo_path) { (false, Some(path)) => open(path)?.config()?, _ => git2::Config::open_default()? diff --git a/apps/desktop/src-tauri/src/forge.rs b/apps/desktop/src-tauri/src/forge.rs index 79bf5196..4498fae8 100644 --- a/apps/desktop/src-tauri/src/forge.rs +++ b/apps/desktop/src-tauri/src/forge.rs @@ -14,7 +14,7 @@ fn url_host_allowed(host: &str, url_host: &str) -> bool { url_host == host || url_host == format!("api.{host}") } -fn auth_headers( +pub(crate) fn auth_headers( provider: &str, token: &str, email: Option<&str>, diff --git a/apps/desktop/src-tauri/src/forge_repositories.rs b/apps/desktop/src-tauri/src/forge_repositories.rs new file mode 100644 index 00000000..7c9c9e9d --- /dev/null +++ b/apps/desktop/src-tauri/src/forge_repositories.rs @@ -0,0 +1,144 @@ +use std::sync::OnceLock; +use std::time::Duration; + +use reqwest::{Client, StatusCode, Url}; + +use crate::core::accounts::{https_account_origin, AccountInfo}; +use crate::error::{AppError, AppResult}; +use crate::http::{self, HttpRequest, HttpResponse}; + +fn api_base(account: &AccountInfo) -> AppResult { + let origin = https_account_origin(&account.host) + .ok_or_else(|| AppError::other("The saved account has an invalid host."))?; + let base = match account.provider.as_str() { + "github" if origin.as_str() == "https://github.com/" => { + Url::parse("https://api.github.com/") + } + "github" => origin.join("api/v3/"), + "gitlab" | "gitlab-self" => origin.join("api/v4/"), + "bitbucket" if origin.as_str() == "https://bitbucket.org/" => { + Url::parse("https://api.bitbucket.org/2.0/") + } + _ => { + return Err(AppError::other( + "Repository browsing is unavailable for this account.", + )) + } + }; + Ok(base.expect("forge API paths are fixed")) +} + +fn request_url(base: &Url, url: &str) -> AppResult { + Url::parse(url) + .ok() + .filter(|url| { + url.origin() == base.origin() + && url.username().is_empty() + && url.password().is_none() + && url.fragment().is_none() + && url.path().starts_with(base.path()) + }) + .ok_or_else(|| AppError::other("The request does not match the saved account's HTTPS API.")) +} + +fn client() -> AppResult<&'static Client> { + static CLIENT: OnceLock = OnceLock::new(); + if let Some(client) = CLIENT.get() { + return Ok(client); + } + let built = Client::builder() + .timeout(Duration::from_secs(10)) + .https_only(true) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|_| AppError::other("Could not start the repository browser."))?; + Ok(CLIENT.get_or_init(|| built)) +} + +pub async fn request(account: &AccountInfo, token: &str, url: String) -> AppResult { + let url = request_url(&api_base(account)?, &url)?; + let headers = crate::forge::auth_headers(&account.provider, token, account.email.as_deref())?; + http::request_with_client( + client()?, + HttpRequest { + url: url.into(), + method: "GET".into(), + headers: headers.into_iter().collect(), + body: None, + }, + ) + .await +} + +pub async fn account_token_rejected(account: &AccountInfo, token: &str) -> bool { + let Ok(base) = api_base(account) else { + return false; + }; + let url = base + .join("user") + .expect("account identity endpoint is fixed"); + request(account, token, url.into()) + .await + .is_ok_and(|response| response.status == StatusCode::UNAUTHORIZED.as_u16()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn account(provider: &str, host: &str) -> AccountInfo { + AccountInfo { + host: host.into(), + username: "work".into(), + provider: provider.into(), + verified: true, + email: None, + verified_at: None, + expires_at: None, + is_default: true, + } + } + + #[test] + fn saved_account_requests_are_pinned_to_the_https_api_origin_and_prefix() { + let base = api_base(&account("gitlab-self", "git.example.test:8443")).unwrap(); + assert!(request_url(&base, "https://git.example.test:8443/api/v4/projects").is_ok()); + for url in [ + "http://git.example.test:8443/api/v4/projects", + "https://git.example.test/api/v4/projects", + "https://wrong.example.test:8443/api/v4/projects", + "https://git.example.test:8443/api/v4x/projects", + "https://user@git.example.test:8443/api/v4/projects", + ] { + assert!(request_url(&base, url).is_err(), "{url}"); + } + } + + #[test] + fn public_forge_requests_use_the_official_api_origins() { + for (provider, host, expected) in [ + ("github", "github.com", "https://api.github.com/user"), + ( + "github", + "github.corp.test", + "https://github.corp.test/api/v3/user", + ), + ( + "bitbucket", + "bitbucket.org", + "https://api.bitbucket.org/2.0/user", + ), + ] { + let base = api_base(&account(provider, host)).unwrap(); + assert_eq!(base.join("user").unwrap().as_str(), expected); + } + } + + #[test] + fn authenticated_repository_client_rejects_plain_http() { + let result = tauri::async_runtime::block_on( + client().unwrap().get("http://127.0.0.1:1/projects").send(), + ); + assert!(matches!(result, Err(error) if error.is_builder())); + } +} diff --git a/apps/desktop/src-tauri/src/http.rs b/apps/desktop/src-tauri/src/http.rs index cc2d1d56..7dad158c 100644 --- a/apps/desktop/src-tauri/src/http.rs +++ b/apps/desktop/src-tauri/src/http.rs @@ -17,6 +17,10 @@ pub struct HttpRequest { pub struct HttpResponse { pub status: u16, pub body: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub link: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_page: Option, } pub(crate) fn shared_client() -> AppResult<&'static reqwest::Client> { @@ -35,15 +39,26 @@ pub async fn request(req: HttpRequest) -> AppResult { if !req.url.starts_with("http://") && !req.url.starts_with("https://") { return Err(AppError::other("only http(s) URLs are allowed")); } - let client = shared_client()?; + request_with_client(shared_client()?, req).await +} +pub(crate) async fn request_with_client( + client: &reqwest::Client, + req: HttpRequest, +) -> AppResult { let mut builder = match req.method.as_str() { "GET" => client.get(&req.url), "POST" => client.post(&req.url), other => return Err(AppError::other(format!("unsupported method {other}"))), }; for (k, v) in &req.headers { - builder = builder.header(k, v); + let mut value = reqwest::header::HeaderValue::from_str(v) + .map_err(|_| AppError::other("Invalid HTTP header value."))?; + value.set_sensitive(matches!( + k.as_str(), + "authorization" | "private-token" | "api-key" | "x-api-key" + )); + builder = builder.header(k, value); } if let Some(body) = req.body { builder = builder.body(body); @@ -54,9 +69,23 @@ pub async fn request(req: HttpRequest) -> AppResult { .await .map_err(|e| AppError::other(format!("request failed: {e}")))?; let status = response.status().as_u16(); + let header = |name| { + response + .headers() + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned) + }; + let link = header("link"); + let next_page = header("x-next-page"); let body = response .text() .await .map_err(|e| AppError::other(format!("failed to read response: {e}")))?; - Ok(HttpResponse { status, body }) + Ok(HttpResponse { + status, + body, + link, + next_page, + }) } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 39f310b9..87d279d9 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -9,6 +9,7 @@ mod editors; mod error; mod fonts; mod forge; +mod forge_repositories; mod http; mod proc; mod state; @@ -18,6 +19,7 @@ mod watcher; pub mod test_api { #[cfg(unix)] pub use crate::ai_cli::background_process_signals_available; + pub use crate::core::accounts::{self, AccountRef}; pub use crate::core::blame::blame_file; pub use crate::core::branch::{ can_fast_forward, checkout_branch, checkout_detached, cherry_pick, cherry_pick_many, @@ -52,6 +54,7 @@ pub mod test_api { add as remote_add, checkout_remote_ref, fetch, group_update, group_update_controlled, list as remote_list, pull, push, push_specs, push_tag, }; + pub use crate::core::repo::get_local_config; pub use crate::core::repo::{ cleanup_state, discover, info as repo_info, init, ref_fingerprint, set_config, status, }; @@ -248,6 +251,7 @@ pub fn run() { commands::ssh_public_key, commands::ssh_key_generate, commands::account_list, + commands::account_forge_request, commands::account_add, commands::account_remove, commands::account_set_default, diff --git a/apps/desktop/src-tauri/tests/clone_hooks.rs b/apps/desktop/src-tauri/tests/clone_hooks.rs index ad7fe315..383898c8 100644 --- a/apps/desktop/src-tauri/tests/clone_hooks.rs +++ b/apps/desktop/src-tauri/tests/clone_hooks.rs @@ -77,6 +77,7 @@ fn post_checkout_runs_after_clone_with_a_zero_previous_head() { source.to_str().unwrap(), into.to_str().unwrap(), None, + None, |_| {}, false, ) @@ -93,6 +94,7 @@ fn post_checkout_runs_after_clone_with_a_zero_previous_head() { source.to_str().unwrap(), root.join("clone-without-hooks").to_str().unwrap(), None, + None, |_| {}, true, ) @@ -105,6 +107,7 @@ fn post_checkout_runs_after_clone_with_a_zero_previous_head() { empty.to_str().unwrap(), root.join("clone-of-empty").to_str().unwrap(), None, + None, |_| {}, false, ) diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index 55cae05d..4670ecfb 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -56,6 +56,155 @@ impl Drop for TempRepo { } } +#[test] +fn local_account_binding_reads_ignore_included_config() { + let repo = TempRepo::new(); + let included = repo.dir.join("accounts.gitconfig"); + let mut config = git2::Config::open(&included).unwrap(); + config + .set_str("angkorgit.accounts", "github.com=included") + .unwrap(); + core::set_config( + Some(repo.path()), + "include.path", + included.to_str().unwrap(), + false, + ) + .unwrap(); + assert_eq!( + core::get_local_config(repo.path(), "angkorgit.accounts").unwrap(), + None + ); + core::set_config( + Some(repo.path()), + "angkorgit.accounts", + "github.com=direct", + false, + ) + .unwrap(); + assert_eq!( + core::get_local_config(repo.path(), "angkorgit.accounts") + .unwrap() + .as_deref(), + Some("github.com=direct") + ); + assert_eq!( + git2::Config::open(&included) + .unwrap() + .get_string("angkorgit.accounts") + .unwrap(), + "github.com=included" + ); +} + +#[test] +fn saved_account_clone_looks_up_the_exact_keychain_entry_and_writes_a_local_binding() { + const CHILD: &str = "ANGKORGIT_TEST_SAVED_ACCOUNT_CLONE"; + if std::env::var_os(CHILD).is_none() { + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "saved_account_clone_looks_up_the_exact_keychain_entry_and_writes_a_local_binding", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + struct CloneKeychain; + impl keyring::credential::CredentialBuilderApi for CloneKeychain { + fn build( + &self, + _: Option<&str>, + service: &str, + user: &str, + ) -> keyring::Result> { + use keyring::credential::CredentialApi; + assert_eq!(service, "AngKorGit"); + assert_eq!(user, "acct:git.example.test:personal"); + let entry = keyring::mock::MockCredential::default(); + entry.set_password("test-token")?; + Ok(Box::new(entry)) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + } + keyring::set_default_credential_builder(Box::new(CloneKeychain)); + let settings = tempfile::tempdir().unwrap(); + core::accounts::CONFIG_DIR + .set(settings.path().to_path_buf()) + .unwrap(); + std::fs::write(settings.path().join("accounts.json"), serde_json::to_vec(&serde_json::json!([ + { "host": "git.example.test", "username": "work", "provider": "gitlab-self", "isDefault": true }, + { "host": "git.example.test", "username": "personal", "provider": "gitlab-self" } + ])).unwrap()).unwrap(); + + unsafe { + git2::opts::set_search_path(git2::ConfigLevel::Global, settings.path()).unwrap(); + } + let source = TempRepo::new(); + source.write("tracked.txt", "saved clone"); + commit_all(&source, "source commit"); + let source_url = reqwest::Url::from_file_path(&source.dir).unwrap(); + let url = "https://git.example.test/group/project.git"; + let mut global = git2::Config::open(&settings.path().join(".gitconfig")).unwrap(); + global + .set_str(&format!("url.{source_url}.insteadOf"), url) + .unwrap(); + global + .set_str("angkorgit.accounts", "unrelated.example.test=global") + .unwrap(); + assert_eq!( + core::get_local_config(source.path(), "angkorgit.accounts").unwrap(), + None + ); + + let selected = core::AccountRef { + host: "git.example.test".into(), + username: "personal".into(), + }; + let target = settings.path().join("clone"); + let into = target.to_str().unwrap(); + let invalid = core::post_hooks::clone( + "https://elsewhere.test/group/project.git", + into, + None, + Some(&selected), + |_| {}, + true, + ); + assert!(matches!(invalid, Err(error) if error.to_string().contains("does not match"))); + assert!(!target.exists()); + + core::post_hooks::clone(url, into, None, Some(&selected), |_| {}, true).unwrap(); + assert_eq!( + std::fs::read_to_string(target.join("tracked.txt")).unwrap(), + "saved clone" + ); + assert_eq!( + core::get_local_config(into, "remote.origin.url") + .unwrap() + .as_deref(), + Some(url) + ); + assert_eq!( + core::get_local_config(into, "angkorgit.accounts") + .unwrap() + .as_deref(), + Some("git.example.test=personal") + ); +} + fn commit_all(repo: &TempRepo, message: &str) -> String { core::stage_all(repo.path()).unwrap(); core::commit(repo.path(), message, false).unwrap().oid diff --git a/apps/desktop/src/core/demo.ts b/apps/desktop/src/core/demo.ts index 4f312bc7..110ba9b7 100644 --- a/apps/desktop/src/core/demo.ts +++ b/apps/desktop/src/core/demo.ts @@ -1,4 +1,5 @@ import type { EditorInfo } from './ipc'; +import type { AccountRepository } from '@angkorgit/core'; import type { BlameHunk, FileBlame } from '@angkorgit/core'; import type { BranchInfo, @@ -715,6 +716,9 @@ const demoPull = ( base: { ref: 'main' }, }); +export const demoAccountRepositories: AccountRepository[] = ['demo/angkorgit', 'demo/temple-ui'] + .map((fullName) => ({ fullName, cloneUrl: `https://github.com/${fullName}.git` })); + export function demoForgeResponse(request: HttpRequest): HttpResponse { const url = request.url; if (request.method === 'POST' && url.includes('/pulls')) { diff --git a/apps/desktop/src/core/ipc.ts b/apps/desktop/src/core/ipc.ts index e3869b3c..b5f93236 100644 --- a/apps/desktop/src/core/ipc.ts +++ b/apps/desktop/src/core/ipc.ts @@ -16,6 +16,8 @@ import type { HistoryQuery, HttpRequest, HttpResponse, + AccountRepositoryPage, + RepositoryCursor, RebaseTodoEntry, RecentRepository, RepositoryScan, @@ -32,6 +34,7 @@ import type { RepoHooks, DiscardBatch, } from '@angkorgit/core'; +import { listAccountRepositories } from '@angkorgit/core'; import type { FileBlame } from '@angkorgit/core'; let demo = null as unknown as typeof import('./demo'); @@ -62,9 +65,12 @@ export interface GeneratedKey { publicKey: string; } -export interface HostingAccount { +export interface HostingAccountRef { host: string; username: string; +} + +export interface HostingAccount extends HostingAccountRef { provider: string; verified: boolean; email?: string | null; @@ -400,12 +406,17 @@ export const ipc = { if (!isTauri()) return demo.demoRepo; return invoke('repo_init', { path }); }, - async cloneRepository(url: string, into: string, branch?: string | null): Promise { + async cloneRepository( + url: string, + into: string, + branch?: string | null, + account?: HostingAccountRef | null, + ): Promise { if (!isTauri()) { await delay(600); return demo.demoRepo.path; } - return invoke('repo_clone', { url, into, branch: branch ?? null }); + return invoke('repo_clone', { url, into, branch: branch ?? null, account: account ?? null }); }, async status(path: string): Promise { if (!isTauri()) return demoStatusNow(); @@ -432,9 +443,9 @@ export const ipc = { return invoke('recent_remove', { path }); }, - async configGet(path: string | null, key: string): Promise { + async configGet(path: string | null, key: string, local = false): Promise { if (!isTauri()) return key === 'user.name' ? 'Demo User' : key === 'user.email' ? 'demo@angkorgit.dev' : null; - return invoke('config_get', { path, key }); + return invoke('config_get', { path, key, local }); }, async configSet(path: string | null, key: string, value: string, global: boolean): Promise { if (!isTauri()) return; @@ -1035,6 +1046,11 @@ export const ipc = { ]; return invoke('account_list'); }, + async accountRepositories(account: HostingAccount, cursor?: RepositoryCursor | null): Promise { + if (!isTauri()) return { repositories: demo.demoAccountRepositories, next: null, skipped: 0 }; + const { host, username } = account; + return listAccountRepositories(account, ({ url }) => invoke('account_forge_request', { host, username, url }), cursor); + }, async accountAdd( host: string, username: string, diff --git a/apps/desktop/src/features/repository/AccountRepositoryPicker.tsx b/apps/desktop/src/features/repository/AccountRepositoryPicker.tsx new file mode 100644 index 00000000..89d38aa9 --- /dev/null +++ b/apps/desktop/src/features/repository/AccountRepositoryPicker.tsx @@ -0,0 +1,188 @@ +import { useCallback, useEffect, useReducer, useRef, useState } from 'react'; +import { Command } from 'cmdk'; +import { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Spinner } from '@angkorgit/design-system'; +import type { AccountRepositoryPage } from '@angkorgit/core'; +import { ipc, type HostingAccount } from '@/core/ipc'; + +type LoadMode = 'open' | 'refresh' | 'more'; + +interface RepositoryList extends AccountRepositoryPage { + pending: boolean; + loaded: boolean; + attemptedAt: number; + error?: { message: string; retry: LoadMode }; +} + +const emptyPage: AccountRepositoryPage = { repositories: [], next: null, skipped: 0 }; +const cacheDuration = 5 * 60_000; + +function accountKey(account: HostingAccount): string { + return JSON.stringify([account.provider, account.host, account.username, account.verifiedAt]); +} + +export function useAccountRepositoryPages() { + const lists = useRef(new Map()); + const [, update] = useReducer((version: number) => version + 1, 0); + const load = useCallback(async (account: HostingAccount, mode: LoadMode) => { + const key = accountKey(account); + const previous = lists.current.get(key); + const now = Date.now(); + if (previous?.pending || (mode === 'open' && previous && now - previous.attemptedAt < cacheDuration)) return; + if (mode === 'more' && !previous?.next) return; + + const pending: RepositoryList = { + ...(previous ?? emptyPage), + loaded: previous?.loaded ?? false, + pending: true, + attemptedAt: now, + error: undefined, + }; + lists.current.set(key, pending); + update(); + try { + const page = await ipc.accountRepositories(account, mode === 'more' ? previous?.next : null); + const repositories = new Map( + (mode === 'more' ? pending.repositories : []).map((repository) => [repository.cloneUrl, repository]), + ); + for (const repository of page.repositories) repositories.set(repository.cloneUrl, repository); + lists.current.set(key, { + ...page, + repositories: [...repositories.values()], + skipped: page.skipped + (mode === 'more' ? pending.skipped : 0), + loaded: true, + pending: false, + attemptedAt: now, + }); + } catch (error) { + const message = (error as { message?: string } | null)?.message ?? String(error); + lists.current.set(key, { + ...pending, + pending: false, + error: { message, retry: mode === 'open' ? 'refresh' : mode }, + }); + } + update(); + }, []); + return { lists: lists.current, load }; +} + +type RepositoryPages = ReturnType; + +function AccountRepositories({ + account, + active, + pages, + onSelect, +}: { + account: HostingAccount; + active: boolean; + pages: RepositoryPages; + onSelect: (url: string, account: HostingAccount) => void; +}) { + const { load, lists } = pages; + const list = lists.get(accountKey(account)); + const retry = list?.error?.retry; + useEffect(() => { + if (active) void load(account, 'open'); + }, [account, active, load]); + + return ( + <> + {!!list?.repositories.length && ( + + + + + {list.next ? 'No matches in the loaded repositories.' : 'No matching repositories.'} + + {list.repositories.map((repository) => ( + onSelect(repository.cloneUrl, account)} + className="cursor-pointer truncate rounded-sm px-2 py-1 text-sm text-foreground data-[selected=true]:bg-surface-raised" + title={repository.fullName} + > + {repository.fullName} + + ))} + + + )} + {(!list || list.pending) && ( +
+ Loading repositories… +
+ )} + {!!list?.skipped && ( +

+ {list.skipped === 1 + ? 'One repository had an invalid clone address.' + : `${list.skipped} repositories had invalid clone addresses.`} +

+ )} + {list?.loaded && !list.repositories.length && !list.skipped && !list.pending && !list.error && ( +

+ {list.next ? 'No repositories on this page.' : 'No repositories available to this account.'} +

+ )} + {list?.error && ( +

{list.error.message}

+ )} + {list && (list.loaded || list.error) && ( +
+ {retry ? ( + + ) : list.next && ( + + )} + {list.loaded && ( + + )} +
+ )} + + ); +} + +export function AccountRepositoryPicker({ + accounts, + active, + pages, + onSelect, +}: { + accounts: HostingAccount[]; + active: boolean; + pages: RepositoryPages; + onSelect: (url: string, account: HostingAccount) => void; +}) { + const [selected, setSelected] = useState(accounts.length === 1 ? '0' : ''); + const account = selected === '' ? undefined : accounts[Number(selected)]; + return ( +
+ + {account && } +
+ ); +} diff --git a/apps/desktop/src/features/repository/CloneDialog.tsx b/apps/desktop/src/features/repository/CloneDialog.tsx index 17558d1b..3b59f23a 100644 --- a/apps/desktop/src/features/repository/CloneDialog.tsx +++ b/apps/desktop/src/features/repository/CloneDialog.tsx @@ -1,7 +1,7 @@ import { toastActionError } from '../../components/actionError'; -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { toast } from 'sonner'; -import { FolderOpen } from 'lucide-react'; +import { ChevronDown, FolderOpen } from 'lucide-react'; import { Button, Dialog, @@ -13,9 +13,12 @@ import { Input, Spinner, } from '@angkorgit/design-system'; -import { ipc, listen, pickDirectory } from '@/core/ipc'; +import { ipc, listen, pickDirectory, type HostingAccount, type HostingAccountRef } from '@/core/ipc'; import { useUi, type ClonePreset, type DialogContext } from '@/features/ui/store'; import { useSettings } from '@/features/settings/store'; +import { AccountRepositoryPicker, useAccountRepositoryPages } from './AccountRepositoryPicker'; + +const browsableProviders = new Set(['github', 'gitlab', 'gitlab-self', 'bitbucket']); function clonePreset(ctx: DialogContext): ClonePreset | null { if (!ctx || typeof ctx === 'string' || !('url' in ctx) || !('into' in ctx)) return null; @@ -31,6 +34,30 @@ export function CloneDialog({ onCloned }: { onCloned: (path: string) => void }) const [into, setInto] = useState(''); const [branch, setBranch] = useState(''); const [progress, setProgress] = useState(null); + const [accounts, setAccounts] = useState([]); + const [pickedAccount, setPickedAccount] = useState(null); + const [browsing, setBrowsing] = useState(false); + const [hasBrowsed, setHasBrowsed] = useState(false); + const repositoryPages = useAccountRepositoryPages(); + const urlInput = useRef(null); + const browseButton = useRef(null); + + useEffect(() => { + if (!open) { + setAccounts([]); + return; + } + let current = true; + void ipc.accountList().then( + (accounts) => { + if (current) setAccounts(accounts.filter((account) => browsableProviders.has(account.provider))); + }, + () => { + if (current) setAccounts([]); + }, + ); + return () => { current = false; }; + }, [open]); useEffect(() => { if (!open) { @@ -38,11 +65,17 @@ export function CloneDialog({ onCloned }: { onCloned: (path: string) => void }) setInto(''); setBranch(''); setProgress(null); + setPickedAccount(null); + setBrowsing(false); + setHasBrowsed(false); return; } const preset = clonePreset(dialogContext); if (preset) { setUrl(preset.url); + setPickedAccount(null); + setBrowsing(false); + setHasBrowsed(false); setInto(preset.into || cloneRoot || ''); setBranch(preset.branch ?? ''); } else if (cloneRoot) { @@ -62,11 +95,12 @@ export function CloneDialog({ onCloned }: { onCloned: (path: string) => void }) const clone = async () => { if (progress !== null || !url.trim() || !into.trim()) return; + setBrowsing(false); setProgress(0); try { const name = url.trim().replace(/\.git$/, '').split('/').pop() ?? 'repository'; const target = `${into.replace(/\/$/, '')}/${name}`; - const path = await ipc.cloneRepository(url.trim(), target, branch.trim() || null); + const path = await ipc.cloneRepository(url.trim(), target, branch.trim() || null, pickedAccount); setCloneRoot(into.trim().replace(/\/$/, '')); toast.success('Repository cloned'); closeDialog(); @@ -79,7 +113,16 @@ export function CloneDialog({ onCloned }: { onCloned: (path: string) => void }) return ( !o && closeDialog()}> - + { + if (browsing) { + event.preventDefault(); + setBrowsing(false); + browseButton.current?.focus(); + } + }} + > Clone repository @@ -90,13 +133,58 @@ export function CloneDialog({ onCloned }: { onCloned: (path: string) => void })
setUrl(e.target.value)} + onChange={(e) => { + setUrl(e.target.value); + setPickedAccount(null); + }} onKeyDown={(e) => { if (e.key === 'Enter') void clone(); }} /> + {accounts.length > 0 && ( +
+
+ + {pickedAccount && ( + + {pickedAccount.username} on {pickedAccount.host} + + )} +
+ {hasBrowsed && ( + + )} +
+ )} = { defaultHost: 'gitlab.com', hostEditable: false, tokenPage: () => 'https://gitlab.com/-/user_settings/personal_access_tokens', - tokenHint: 'Personal access token with "read_repository" + "write_repository" scopes', + tokenHint: 'Personal access token with read_repository and write_repository. Add read_api to browse repositories.', usernameHint: 'username (detected from the token)', }, 'gitlab-self': { @@ -86,7 +86,7 @@ const PROVIDERS: Record = { defaultHost: '', hostEditable: true, tokenPage: (host) => (host ? `http://${host}/-/user_settings/personal_access_tokens` : null), - tokenHint: 'Personal access token with "read_repository" + "write_repository" scopes', + tokenHint: 'Personal access token with read_repository and write_repository. Repository browsing uses HTTPS and requires read_api.', usernameHint: 'username (detected from the token)', }, bitbucket: { @@ -94,7 +94,7 @@ const PROVIDERS: Record = { defaultHost: 'bitbucket.org', hostEditable: false, tokenPage: () => 'https://id.atlassian.com/manage-profile/security/api-tokens', - tokenHint: 'API token with read:repository:bitbucket + write:repository:bitbucket scopes', + tokenHint: 'API token with read:repository:bitbucket and write:repository:bitbucket. Add read:workspace:bitbucket to browse repositories.', usernameHint: 'Atlassian account email (your Bitbucket username is detected)', }, other: { diff --git a/apps/desktop/src/features/settings/profiles.ts b/apps/desktop/src/features/settings/profiles.ts index 92f1da7b..b5b8ec57 100644 --- a/apps/desktop/src/features/settings/profiles.ts +++ b/apps/desktop/src/features/settings/profiles.ts @@ -12,19 +12,25 @@ export function serializeAccountBindings(accounts: Record | unde export async function applyProfileToRepo( repoPath: string, profile: IdentityProfile, - opts?: { preserveIdentity?: boolean }, + opts?: { preserveIdentity?: boolean; preserveAccounts?: boolean }, ): Promise { if (!opts?.preserveIdentity) { await ipc.configSet(repoPath, 'user.name', profile.name, false); await ipc.configSet(repoPath, 'user.email', profile.email, false); } + const profileBindings = serializeAccountBindings(profile.accounts); + if (profileBindings || !opts?.preserveAccounts) { + const existingBindings = opts?.preserveAccounts + ? await ipc.configGet(repoPath, 'angkorgit.accounts', true) + : null; + await ipc.configSet( + repoPath, + 'angkorgit.accounts', + [profileBindings, existingBindings].filter(Boolean).join(','), + false, + ); + } await ipc.configSet(repoPath, 'angkorgit.profile', profile.id, false); - await ipc.configSet( - repoPath, - 'angkorgit.accounts', - serializeAccountBindings(profile.accounts), - false, - ); const repoState = useRepo.getState(); if (repoState.repo?.path === repoPath) repoState.setProfileId(profile.id); } @@ -48,11 +54,11 @@ export async function ensureRepoProfile(repoPath: string): Promise Promise; diff --git a/packages/core/src/forge/providers/bitbucket.ts b/packages/core/src/forge/providers/bitbucket.ts index b87b2ba1..68325e1d 100644 --- a/packages/core/src/forge/providers/bitbucket.ts +++ b/packages/core/src/forge/providers/bitbucket.ts @@ -29,7 +29,7 @@ interface BitbucketPull { links?: { html?: { href?: string } }; } -function bitbucketMessage(body: string): string | null { +export function bitbucketMessage(body: string): string | null { try { const parsed = JSON.parse(body) as { error?: { message?: string; detail?: string } }; const message = parsed.error?.message ?? null; diff --git a/packages/core/src/forge/providers/github.ts b/packages/core/src/forge/providers/github.ts index 9ec1cf90..65ac299e 100644 --- a/packages/core/src/forge/providers/github.ts +++ b/packages/core/src/forge/providers/github.ts @@ -69,7 +69,7 @@ export function explainGithubCreateRefusal(error: unknown, targetRepo: string | return new ForgeError(said ? `${hint} GitHub said: ${said}.` : hint, error.forge, error.status); } -function githubMessage(body: string): string | null { +export function githubMessage(body: string): string | null { try { const parsed = JSON.parse(body) as { message?: string; diff --git a/packages/core/src/forge/providers/gitlab.ts b/packages/core/src/forge/providers/gitlab.ts index cce1348e..9c5a5a97 100644 --- a/packages/core/src/forge/providers/gitlab.ts +++ b/packages/core/src/forge/providers/gitlab.ts @@ -27,7 +27,7 @@ interface GitlabMergeRequest { target_project_id?: number; } -function gitlabMessage(body: string): string | null { +export function gitlabMessage(body: string): string | null { try { const parsed = JSON.parse(body) as { message?: string | string[]; error?: string }; if (Array.isArray(parsed.message)) return parsed.message.join('; '); diff --git a/packages/core/src/forge/repositories.ts b/packages/core/src/forge/repositories.ts new file mode 100644 index 00000000..71ef6905 --- /dev/null +++ b/packages/core/src/forge/repositories.ts @@ -0,0 +1,159 @@ +import type { HttpClient, HttpResponse } from '../ai/types'; +import { bitbucketMessage } from './providers/bitbucket'; +import { githubApiBase, githubMessage } from './providers/github'; +import { gitlabMessage } from './providers/gitlab'; +import { createForgeJsonRequest } from './shared'; +import { ForgeError } from './types'; + +export interface AccountRepository { + fullName: string; + cloneUrl: string; +} + +type BitbucketCursor = { + kind: 'bitbucket'; + workspacePage: string | null; + workspaces: string[]; + repositoryPage: string | null; +}; + +export type RepositoryCursor = { kind: 'github' | 'gitlab'; url: string } | BitbucketCursor; + +export interface AccountRepositoryPage { + repositories: AccountRepository[]; + next: RepositoryCursor | null; + skipped: number; +} + +const bitbucketApi = 'https://api.bitbucket.org/2.0'; +const workspaceList = `${bitbucketApi}/user/workspaces?pagelen=50`; +const forgeDetails = { + github: { label: 'GitHub', parseMessage: githubMessage, scopes: 'Metadata and Contents read access' }, + gitlab: { label: 'GitLab', parseMessage: gitlabMessage, scopes: 'read_api (or api) and repository read access' }, + bitbucket: { label: 'Bitbucket', parseMessage: bitbucketMessage, scopes: 'read:workspace:bitbucket and read:repository:bitbucket' }, +}; + +function linkNext(link: string | undefined): string | undefined { + return link?.match(/<([^>]+)>\s*;\s*rel="next"/)?.[1]; +} + +function resolvePage(current: string, next: string | null | undefined): string | null { + if (!next) return null; + const original = new URL(current); + const target = new URL(next, original); + if (target.origin !== original.origin || target.pathname !== original.pathname || + target.username || target.password || target.hash || target.href === original.href) { + throw new Error('The provider returned an invalid repository pagination link.'); + } + return target.href; +} + +function gitlabNext(current: string, response: HttpResponse): string | null { + const link = linkNext(response.link); + if (!response.nextPage && !link) return null; + const next = response.nextPage || new URL(link!, current).searchParams.get('page'); + const url = new URL(current); + if (!next || !/^\d+$/.test(next) || !Number.isSafeInteger(Number(next)) || + Number(next) <= Number(url.searchParams.get('page'))) { + throw new Error('GitLab returned an invalid repository page number.'); + } + url.searchParams.set('page', next); + return url.href; +} + +function repositoryPage( + names: unknown[], + origin: string, + next: RepositoryCursor | null, +): AccountRepositoryPage { + const repositories: AccountRepository[] = []; + for (const fullName of names) { + if (typeof fullName !== 'string') continue; + const segments = fullName.split('/'); + if (segments.length < 2 || segments.some((segment) => !segment || segment === '.' || segment === '..')) continue; + repositories.push({ fullName, cloneUrl: `${origin}/${segments.map(encodeURIComponent).join('/')}.git` }); + } + return { repositories, next, skipped: names.length - repositories.length }; +} + +type RepositoryRequest = (url: string) => Promise<{ data: unknown; response: HttpResponse }>; + +async function bitbucketRepositories( + get: RepositoryRequest, + origin: string, + cursor: BitbucketCursor, +): Promise { + let { workspacePage, workspaces, repositoryPage: page } = cursor; + if (workspaces.length === 0 && workspacePage) { + const { data } = await get(workspacePage); + const result = data as { values?: { workspace?: { slug?: string } }[]; next?: string }; + if (!Array.isArray(result?.values)) throw new Error('Bitbucket returned an invalid workspace list.'); + workspaces = result.values.flatMap((entry) => { + const slug = entry?.workspace?.slug; + return typeof slug === 'string' && slug ? [slug] : []; + }); + workspacePage = resolvePage(workspacePage, result.next); + } + + const workspace = workspaces[0]; + if (!workspace) { + return { + repositories: [], + next: workspacePage ? { kind: 'bitbucket', workspaces, workspacePage, repositoryPage: null } : null, + skipped: 0, + }; + } + page ??= `${bitbucketApi}/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?pagelen=50`; + const { data } = await get(page); + const result = data as { values?: { repository?: { full_name?: string } }[]; next?: string }; + if (!Array.isArray(result?.values)) throw new Error('Bitbucket returned an invalid repository list.'); + page = resolvePage(page, result.next); + if (!page) workspaces = workspaces.slice(1); + return repositoryPage( + result.values.map((entry) => entry?.repository?.full_name), + origin, + page || workspaces.length || workspacePage ? { kind: 'bitbucket', workspaces, workspacePage, repositoryPage: page } : null, + ); +} + +export async function listAccountRepositories( + account: { host: string; provider: string }, + http: HttpClient, + cursor?: RepositoryCursor | null, +): Promise { + const kind = account.provider === 'gitlab-self' ? 'gitlab' : account.provider; + if (kind !== 'github' && kind !== 'gitlab' && kind !== 'bitbucket') { + throw new Error('Repository browsing is unavailable for this provider.'); + } + const { label, parseMessage, scopes } = forgeDetails[kind]; + const origin = new URL(`https://${account.host}`).origin; + const get: RepositoryRequest = async (url) => { + let response!: HttpResponse; + try { + const request = createForgeJsonRequest(http, kind, label, parseMessage, (res) => { response = res; }); + return { data: await request(url, 'GET'), response }; + } catch (error) { + if (error instanceof ForgeError && (error.status === 401 || error.status === 403)) { + throw new Error(`${error.message}. Check that the saved token has ${scopes}.`); + } + throw error; + } + }; + if (kind === 'bitbucket') { + return bitbucketRepositories(get, origin, cursor?.kind === kind + ? cursor + : { kind, workspacePage: workspaceList, workspaces: [], repositoryPage: null }); + } + const first = kind === 'github' + ? `${githubApiBase(new URL(origin).host)}/user/repos?per_page=50` + : `${origin}/api/v4/projects?membership=true&simple=true&per_page=50&order_by=id&sort=asc&page=1`; + const url = cursor?.kind === kind ? cursor.url : first; + const { data, response } = await get(url); + if (!Array.isArray(data)) throw new Error(`${label} returned an invalid repository list.`); + const next = kind === 'gitlab' ? gitlabNext(url, response) : resolvePage(url, linkNext(response.link)); + return repositoryPage( + data.map((entry) => kind === 'github' ? entry?.full_name : entry?.path_with_namespace), + origin, + next ? { kind, url: next } : null, + ); +} diff --git a/packages/core/src/forge/shared.ts b/packages/core/src/forge/shared.ts index e0315624..badccaf5 100644 --- a/packages/core/src/forge/shared.ts +++ b/packages/core/src/forge/shared.ts @@ -1,4 +1,4 @@ -import type { HttpClient } from '../ai/types'; +import type { HttpClient, HttpResponse } from '../ai/types'; import type { ForgeKind } from './remote'; import { ForgeError, type PullRequestCheckoutSpec, type PullRequestInfo } from './types'; @@ -13,6 +13,7 @@ export function createForgeJsonRequest( forge: string, label: string, parseMessage: (body: string) => string | null, + onResponse?: (response: HttpResponse) => void, ): ForgeJsonRequest { return async (url, method, payload) => { const res = await http({ @@ -21,6 +22,7 @@ export function createForgeJsonRequest( headers: payload === undefined ? {} : { 'content-type': 'application/json' }, body: payload === undefined ? undefined : JSON.stringify(payload), }); + onResponse?.(res); if (res.status < 200 || res.status >= 300) { const detail = parseMessage(res.body); throw new ForgeError( diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index ba0d6cd1..65a36bf5 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -33,6 +33,7 @@ export * from './forge/remote'; export * from './forge/shared'; export * from './forge/types'; export * from './forge/provider'; +export * from './forge/repositories'; export * from './forge/providers/github'; export * from './forge/providers/gitlab'; export * from './forge/providers/bitbucket'; diff --git a/tests/e2e/smoke.spec.ts b/tests/e2e/smoke.spec.ts index 721332ca..50bf8e33 100644 --- a/tests/e2e/smoke.spec.ts +++ b/tests/e2e/smoke.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from '@playwright/test'; +import { expect, test, type Page } from '@playwright/test'; import { filterFiles } from '../../packages/core/src/git/fileFilter'; import { demoStatus } from '../../apps/desktop/src/core/demo'; @@ -2652,6 +2652,180 @@ test('settings remembers a clone destination and the clone dialog starts there', await expect(page.getByPlaceholder('Destination folder')).toHaveValue('/tmp/repos'); }); +async function openCloneWithTwoAccounts(page: Page) { + await page.goto('/'); + await page.evaluate(async () => { + const { ipc } = await import('/src/core/ipc.ts'); + const accounts = await ipc.accountList(); + ipc.accountList = async () => [...accounts, { + host: 'github.com', username: 'demo-work', provider: 'github', verified: true, + }]; + const accountRepositories = ipc.accountRepositories; + ipc.accountRepositories = async (account, cursor) => account.username === 'demo-work' + ? { + repositories: ['temple-labs/billing-service', 'temple-labs/angkorgit'] + .map((fullName) => ({ fullName, cloneUrl: `https://github.com/${fullName}.git` })), + next: null, + skipped: 0, + } + : accountRepositories(account, cursor); + }); + await page.getByText('Clone repository', { exact: true }).first().click(); + return page.getByRole('dialog', { name: 'Clone repository' }); +} + +test('clone from saved accounts keeps the selected account when another list finishes late', async ({ page }) => { + const dialog = await openCloneWithTwoAccounts(page); + await page.evaluate(async () => { + const { ipc } = await import('/src/core/ipc.ts'); + const accountRepositories = ipc.accountRepositories; + const cloneRepository = ipc.cloneRepository; + const state = window as unknown as { finishPersonalList: () => void; cloneArgs?: unknown[] }; + const personalListGate = new Promise((resolve) => { state.finishPersonalList = resolve; }); + ipc.accountRepositories = async (account) => { + if (account.username === 'demo-user') { + await personalListGate; + } + return accountRepositories(account); + }; + ipc.cloneRepository = async (...args) => { + state.cloneArgs = args; + return cloneRepository(...args); + }; + }); + await dialog.getByRole('button', { name: 'Browse saved accounts' }).click(); + const account = dialog.getByRole('combobox', { name: 'Saved account' }); + await account.click(); + await page.getByRole('option', { name: 'demo-user on github.com' }).click(); + await expect(dialog.getByRole('status')).toHaveText('Loading repositories…'); + await account.click(); + await page.getByRole('option', { name: 'demo-work on github.com' }).click(); + const search = dialog.getByPlaceholder('Search repositories…'); + await search.fill('temple-labs/billing'); + await expect(dialog.getByRole('option', { name: 'temple-labs/billing-service' })).toBeVisible(); + await page.evaluate(() => (window as unknown as { finishPersonalList: () => void }).finishPersonalList()); + await expect(dialog.getByRole('listbox', { name: 'Repositories' })) + .toHaveText('temple-labs/billing-service'); + await expect(dialog.getByRole('option', { name: 'demo/temple-ui' })).not.toBeVisible(); + await search.press('Enter'); + await expect(dialog.getByRole('textbox', { name: 'Repository URL' })) + .toHaveValue('https://github.com/temple-labs/billing-service.git'); + await expect(dialog.getByText('demo-work on github.com', { exact: true }).filter({ visible: true })).toBeVisible(); + await dialog.getByPlaceholder('Destination folder').fill('/tmp/repos'); + await dialog.getByPlaceholder('Branch (optional)').fill('develop'); + await dialog.getByRole('button', { name: 'Clone', exact: true }).click(); + await expect(page.getByText('Repository cloned')).toBeVisible(); + await expect(page.getByPlaceholder('Search commits…')).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { cloneArgs: unknown[] }).cloneArgs)).toEqual([ + 'https://github.com/temple-labs/billing-service.git', + '/tmp/repos/billing-service', + 'develop', + { host: 'github.com', username: 'demo-work' }, + ]); +}); + +test('clone from saved accounts can retry and editing the URL clears the picked account', async ({ page }) => { + const dialog = await openCloneWithTwoAccounts(page); + await page.evaluate(async () => { + const { ipc } = await import('/src/core/ipc.ts'); + const accountRepositories = ipc.accountRepositories; + const cloneRepository = ipc.cloneRepository; + const state = window as unknown as { cloneListOffline: boolean; cloneArgs?: unknown[] }; + state.cloneListOffline = true; + ipc.accountRepositories = async (account) => { + if (state.cloneListOffline) { + throw new Error('Could not reach GitHub. Check your connection and try again.'); + } + return accountRepositories(account); + }; + ipc.cloneRepository = async (...args) => { + state.cloneArgs = args; + return cloneRepository(...args); + }; + }); + const url = dialog.getByRole('textbox', { name: 'Repository URL' }); + await url.fill('git@github.com:demo/manual.git'); + await dialog.getByRole('button', { name: 'Browse saved accounts' }).click(); + await dialog.getByRole('combobox', { name: 'Saved account' }).click(); + await page.getByRole('option', { name: 'demo-work on github.com' }).click(); + await expect(dialog.getByRole('alert')).toContainText('Could not reach GitHub'); + await expect(url).toHaveValue('git@github.com:demo/manual.git'); + await page.evaluate(() => { + (window as unknown as { cloneListOffline: boolean }).cloneListOffline = false; + }); + await dialog.getByRole('button', { name: 'Retry' }).click(); + const search = dialog.getByPlaceholder('Search repositories…'); + await search.fill('no such repository'); + await expect(dialog.getByText('No matching repositories.')).toBeVisible(); + await search.fill('angkorgit'); + await dialog.getByRole('option', { name: 'temple-labs/angkorgit' }).click(); + await expect(dialog.getByText('demo-work on github.com', { exact: true }).filter({ visible: true })).toBeVisible(); + await url.fill('git@github.com:demo/manual.git'); + await expect(dialog.getByText('demo-work on github.com', { exact: true }).filter({ visible: true })).toBeHidden(); + await dialog.getByPlaceholder('Destination folder').fill('/tmp/repos'); + await url.press('Enter'); + await expect(page.getByText('Repository cloned')).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { cloneArgs: unknown[] }).cloneArgs)).toEqual([ + 'git@github.com:demo/manual.git', '/tmp/repos/manual', null, null, + ]); +}); + +test('clone from saved accounts caches pages and keeps results when a later page fails', async ({ page }) => { + const dialog = await openCloneWithTwoAccounts(page); + await page.evaluate(async () => { + const { ipc } = await import('/src/core/ipc.ts'); + const original = ipc.accountRepositories; + const state = window as unknown as { repositoryRequests: string[]; rateLimited: boolean }; + state.repositoryRequests = []; + state.rateLimited = true; + ipc.accountRepositories = async (account, cursor) => { + state.repositoryRequests.push(`${account.username}:${cursor ? 'next' : 'first'}`); + if (account.username !== 'demo-work') return original(account, cursor); + if (cursor && state.rateLimited) throw new Error('GitHub rate limit (429).'); + const repo = cursor ? 'temple-labs/second-page' : 'temple-labs/first-page'; + return { + repositories: [{ fullName: repo, cloneUrl: `https://github.com/${repo}.git` }], + next: cursor ? null : { kind: 'github', url: 'https://api.github.com/user/repos?page=2' }, + skipped: cursor ? 1 : 0, + }; + }; + }); + + const browse = dialog.getByRole('button', { name: 'Browse saved accounts' }); + const account = dialog.getByRole('combobox', { name: 'Saved account' }); + const first = dialog.getByRole('option', { name: 'temple-labs/first-page' }); + const requests = () => page.evaluate(() => (window as unknown as { repositoryRequests: string[] }).repositoryRequests); + await browse.click(); + await account.click(); + await page.getByRole('option', { name: 'demo-work on github.com' }).click(); + await expect(first).toBeVisible(); + expect(await requests()).toEqual(['demo-work:first']); + await dialog.getByRole('button', { name: 'Load more' }).click(); + await expect(dialog.getByRole('alert')).toContainText('429'); + await expect(first).toBeVisible(); + await page.evaluate(() => { (window as unknown as { rateLimited: boolean }).rateLimited = false; }); + await dialog.getByRole('button', { name: 'Retry' }).click(); + await expect(dialog.getByRole('option', { name: 'temple-labs/second-page' })).toBeVisible(); + await expect(dialog.getByText('One repository had an invalid clone address.')).toBeVisible(); + + await account.click(); + await page.getByRole('option', { name: 'demo-user on github.com' }).click(); + await expect(dialog.getByRole('option', { name: 'demo/temple-ui' })).toBeVisible(); + await account.click(); + await page.getByRole('option', { name: 'demo-work on github.com' }).click(); + await expect(first).toBeVisible(); + await browse.click(); + await browse.click(); + await expect(first).toBeVisible(); + await dialog.getByRole('button', { name: 'Cancel', exact: true }).click(); + await page.getByText('Clone repository', { exact: true }).first().click(); + await browse.click(); + await account.click(); + await page.getByRole('option', { name: 'demo-work on github.com' }).click(); + await expect(first).toBeVisible(); + expect(await requests()).toEqual(['demo-work:first', 'demo-work:next', 'demo-work:next', 'demo-user:first']); +}); + test('a diff selection keeps its lines after scrolling away and back', async ({ page }) => { await page.goto('/'); await page.getByText('angkorgit', { exact: true }).first().click(); diff --git a/tests/unit/forgeRepositories.test.ts b/tests/unit/forgeRepositories.test.ts new file mode 100644 index 00000000..e015780a --- /dev/null +++ b/tests/unit/forgeRepositories.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { HttpClient, HttpResponse } from '@angkorgit/core'; +import { listAccountRepositories } from '@angkorgit/core'; + +function response(body: unknown, headers: Partial = {}): HttpResponse { + return { status: 200, body: JSON.stringify(body), ...headers }; +} + +describe('saved account repository pages', () => { + it('builds GitHub Enterprise URLs from repository names and reports invalid entries', async () => { + const http = vi.fn().mockResolvedValue( + response([ + { full_name: 'team/repo', clone_url: 'https://public.example.test/team/repo.git' }, + { full_name: 'team/../invalid' }, + { clone_url: 'https://other.example.test/repo.git' }, + ], { link: '; rel="next"' }), + ); + const result = await listAccountRepositories({ host: 'git.internal.test:8443', provider: 'github' }, http); + expect(result).toEqual({ + repositories: [{ fullName: 'team/repo', cloneUrl: 'https://git.internal.test:8443/team/repo.git' }], + next: { kind: 'github', url: 'https://git.internal.test:8443/api/v3/user/repos?page=2' }, + skipped: 2, + }); + expect(http).toHaveBeenCalledTimes(1); + }); + + it('keeps the saved GitLab host and filters when a proxy advertises a different origin', async () => { + const http = vi.fn() + .mockResolvedValueOnce(response([{ path_with_namespace: 'group/subgroup/project' }], { + link: '; rel="next"', + })) + .mockResolvedValueOnce(response([{ path_with_namespace: 'group/new-project' }])); + const account = { host: 'git.internal.test:8443', provider: 'gitlab-self' }; + const result = await listAccountRepositories(account, http); + expect(result.repositories[0]?.cloneUrl).toBe('https://git.internal.test:8443/group/subgroup/project.git'); + expect(http).toHaveBeenCalledTimes(1); + await listAccountRepositories(account, http, result.next); + expect(http.mock.calls[1]?.[0].url).toBe( + 'https://git.internal.test:8443/api/v4/projects?membership=true&simple=true&per_page=50&order_by=id&sort=asc&page=2', + ); + }); + + it('loads one Bitbucket repository page at a time and retains pending workspaces', async () => { + const http = vi.fn() + .mockResolvedValueOnce(response({ values: [{ workspace: { slug: 'alpha' } }, { workspace: { slug: 'beta' } }] })) + .mockResolvedValueOnce(response({ + values: [{ repository: { full_name: 'alpha/first' } }], + next: '?pagelen=50&page=2', + })) + .mockResolvedValueOnce(response({ values: [{ repository: { full_name: 'alpha/second' } }] })) + .mockResolvedValueOnce(response({ values: [{ repository: { full_name: 'beta/third' } }] })); + const account = { host: 'bitbucket.org', provider: 'bitbucket' }; + const first = await listAccountRepositories(account, http); + expect(first.repositories[0]?.fullName).toBe('alpha/first'); + expect(http).toHaveBeenCalledTimes(2); + const second = await listAccountRepositories(account, http, first.next); + expect(second.repositories[0]?.fullName).toBe('alpha/second'); + expect(http).toHaveBeenCalledTimes(3); + const third = await listAccountRepositories(account, http, second.next); + expect(third.repositories[0]?.fullName).toBe('beta/third'); + expect(third.next).toBeNull(); + }); + + it('refuses foreign pagination links and reports API errors through the shared forge transport', async () => { + const account = { host: 'github.com', provider: 'github' }; + const http = vi.fn() + .mockResolvedValueOnce(response([], { link: '; rel="next"' })) + .mockResolvedValueOnce(response({ message: 'Rate limited' }, { status: 429 })); + await expect(listAccountRepositories(account, http)).rejects.toThrow('invalid repository pagination link'); + await expect(listAccountRepositories(account, http)).rejects.toThrow('GitHub request failed (429): Rate limited'); + expect(http).toHaveBeenCalledTimes(2); + }); +});