a510b46e4e
* feat(task): add task_environment_repos schema and model for multi-repo support
Phase 0 of multi-repository task support: introduces the per-repository
child table and model alongside legacy single-repo fields (dual-write,
no behavior change). Lays the foundation for the orchestrator/lifecycle
refactor in subsequent phases.
- New task_environment_repos table with FK CASCADE on task_environments.
- New task_dir_name column on task_environments (idempotent ALTER).
- TaskEnvironmentRepo model + Repos slice + RepoFor helper on TaskEnvironment.
- CRUD methods + interface extension; env getters preload Repos.
- Idempotent backfill from legacy single-repo task_environments rows.
- Tests cover round-trip, CRUD, preload ordering, embedded create, cascade
delete, and backfill from a legacy-shaped row.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(lifecycle): add Repositories list to LaunchRequest and EnvPrepareRequest
Phase 1.1 of multi-repository task support: extends the lifecycle types
with explicit per-repo lists, while keeping the legacy single-repo
top-level fields as the synthesized fallback. No caller behavior changes
yet — preparers still see length-1 specs for single-repo launches.
- LaunchRequest.Repositories []RepoLaunchSpec + RepoSpecs() helper.
- EnvPrepareRequest.Repositories []RepoPrepareSpec + RepoSpecs() helper.
- EnvPrepareResult.Worktrees []RepoWorktreeResult for per-repo outcomes.
- runEnvironmentPreparer forwards req.Repositories into the prepare
request, inheriting the request-level RepoSetupScript when each
per-repo entry has none.
- Tests cover explicit-list precedence, synthesized fallback, and
repo-less requests.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(worktree,lifecycle): support multiple worktrees per session
Phases 1.2 and 1.3 of multi-repository task support. The pieces are
intertwined so they ship together — the preparer's per-repo loop
depends on the manager being able to hold one worktree per
(session, repository) pair instead of one per session.
Worktree manager:
- In-memory cache key changes from sessionID to (sessionID|repositoryID).
- New MultiRepoStore optional capability + SQLite implementation:
GetWorktreesBySessionID and GetWorktreeBySessionAndRepository.
- New Manager methods: GetAllBySessionID, GetBySessionAndRepo. Existing
GetBySessionID returns the first match (single-repo callers unchanged).
- Manager.Create's "already exists" check is now repo-scoped so the
second repo's create no longer returns the first repo's worktree.
- All cache write/delete sites updated to the composite key.
WorktreePreparer:
- New prepareMultiRepo path activated when EnvPrepareRequest.Repositories
has >=2 entries; single-repo and repo-less behavior is byte-identical.
- prepareOneRepo runs validate -> sync -> create -> fetch-PR -> per-repo
setup-script for each spec; rolls back already-created worktrees on
any failure.
- Workspace path becomes the task root (parent of any repo subdir);
legacy WorktreeID/WorktreeBranch/MainRepoGitDir mirror Worktrees[0]
for downstream code that hasn't been migrated yet.
- Per-repo setup script runs verbatim (no script-engine resolution
yet — the per-repo placeholder namespace lands in a follow-up).
Tests:
- Manager: GetAllBySessionID, GetBySessionAndRepo (hit + miss),
GetBySessionID single-repo compat, cache key separation.
- Preparer: multi-repo creates one worktree per repo; rollback removes
active worktrees on partial failure; per-repo setup script runs in
each worktree directory and emits its own step.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(orchestrator): resolve all task repos and persist per-repo rows on launch
Phase 1.4 of multi-repository task support: the orchestrator now reads
every repository linked to a task, forwards the full list through the
adapter into the lifecycle layer, and persists one TaskEnvironmentRepo
plus one TaskSessionWorktree row per repo when the launch is multi-repo.
Single-repo and repo-less tasks keep their previous code path verbatim
(dual-write — legacy single-repo fields stay populated from the primary).
- New resolveAllRepoInfo / resolveTaskRepoInfo on the executor; primary
is the first by Position.
- buildLaunchAgentRequest takes both the primary repoInfo and the full
list, populating req.Repositories []RepoSpec only when length > 1.
- New RepoSpec / RepoWorktreeResult on the orchestrator's executor
package mirror the lifecycle types so the adapter can translate
between them without leaking lifecycle types into the orchestrator
public API.
- Adapter (cmd/kandev/adapters.go) forwards req.Repositories into
lifecycle.LaunchRequest and surfaces per-repo prepare results back
on LaunchAgentResponse.Worktrees.
- persistTaskEnvironment writes env.Repos in the same create
transaction; persistTaskEnvironmentRepos handles the existing-env
reuse path. TaskEnvironment.TaskDirName is now persisted.
- persistWorktreeAssociation loops over resp.Worktrees in multi-repo,
inserting one row per repo with its own RepositoryID.
- ResumeSession now also populates req.Repositories from task repos
and stamps the existing TaskDirName so the preparer reuses the same
task root.
- repoStore / executorStore interfaces extended with the new repo and
env-repo CRUD methods; mocks updated accordingly.
Tests:
- LaunchPreparedSession with two task repositories populates
req.Repositories in order and keeps legacy single-repo top-level
fields filled from the primary.
- The same launch persists one TaskEnvironment + 2 TaskEnvironmentRepo
+ 2 TaskSessionWorktree rows.
- Single-repo launch still produces zero entries in req.Repositories
and exercises only the legacy fields.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(agentctl): git endpoints accept optional repo subpath for multi-repo
Phase 2 of multi-repository task support: every per-call git endpoint
gains an optional `repo` field (form param for GET, JSON for POST) that
selects a sub-directory of the workspace. Empty `repo` = workspace root,
preserving single-repo behavior verbatim.
- Manager.GitOperatorFor(subpath) returns a per-subpath GitOperator
(cached). Validates the subpath against path traversal, absolute
paths, and missing directories.
- New api server helper gitOpForRepo() emits a 400 with a per-operation
GitOperationResult on invalid subpaths.
- Repo field added to: pull, push, rebase, merge, abort, commit,
rename-branch, stage, unstage, discard, create-pr, revert-commit,
show-commit, reset, log, cumulative-diff. (git/status still reads
from the workspace tracker — that endpoint will gain multi-repo
support when the tracker itself is split per repo.)
- Tests cover empty subpath, valid subpath caching, traversal
rejection, and missing-directory rejection.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/comments): scope diff comments by repository for multi-repo tasks
Phase 3 of multi-repository task support: comments now carry an
optional repositoryId so two repos with the same file path render
their own comment threads instead of bleeding together.
- CommentBase.repositoryId (optional, backwards compatible).
- getCommentsForFile gains an optional repositoryId arg; legacy
comments without a repositoryId match any repo filter so persisted
data keeps showing.
- Diff store interface in lib/diff/types.ts mirrors the new arg.
- Tests cover per-repo filter, omitted-arg fallback, and legacy data.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(github): per-repo PR association on task PRs and watches
Phase 4 of multi-repository task support: github_task_prs and
github_pr_watches gain a repository_id column so multi-repo tasks can
have one PR per repo without colliding on (task_id) uniqueness.
- Idempotent ALTER TABLE adds repository_id to both tables.
- TaskPR.RepositoryID and PRWatch.RepositoryID model fields.
- New GetTaskPRByRepository and ListTaskPRsByTask lookups; existing
GetTaskPR keeps single-PR semantics for callers not yet migrated.
- ReplaceTaskPR's delete is scoped by repository_id when set so a
multi-repo task replacing one repo's PR no longer wipes the other.
- Tests cover per-repo storage and scoped replace.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web): foundations for multi-repo task UI
Phase 5 of multi-repository task support: primitives the upcoming UI
work needs without changing any visible behavior yet.
- TaskRepository.checkout_branch surfaces the optional PR head branch
field that the backend already exposes.
- primaryTaskRepository(repos) picks by lowest Position so consumers
match the backend's "primary" semantics instead of `[0]`.
- New useTaskRepositories(taskId) / useTaskPrimaryRepository(taskId)
hooks read the live kanban task and return its repos sorted by
position. Future kanban/diff/UI consumers should use these instead
of poking task.repositories directly.
- Tests cover lowest-position selection and empty/single-repo edge cases.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web): kanban card shows multi-repo "+N" chip and hydrates full repo list
Phase 6 (subset) of multi-repository task support. The kanban now
exposes the per-task repository list to the UI and renders a compact
"+N" badge on cards whose tasks span more than one repository.
- KanbanState.tasks[].repositories slim shape (id, repository_id,
base_branch, checkout_branch, position).
- SSR mapper hydrates the full list and uses primaryTaskRepository()
to pick the position-aware primary instead of [0].
- useKanbanData passes repositories through to the card props.
- KanbanCard renders the primary repo name with a small "+N" chip
when len(repositories) > 1; tooltip names the count.
- useTaskRepositories / useTaskPrimaryRepository hooks return the
slim KanbanTaskRepository shape so multi-repo consumers share one
read path.
Larger UI surfaces (task-create dialog, diff view, file browser,
mobile sheets) still target the primary repo only — they will be
ported as the multi-repo task creation flow lands. No visible change
for single-repo tasks.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(task): reject duplicate repositories on multi-repo task create
Phase 8 of multi-repository task support: surface duplicate-repository
input as a clean validation error instead of letting the unique
(task_id, repository_id) constraint surface mid-loop with some rows
already inserted.
- createTaskRepositories tracks seen repository IDs and returns
"repository <id> listed more than once for the task" before any
CreateTaskRepository call.
- Tests cover the rejection path and confirm two distinct repos still
succeed with both rows persisted in Position order.
Repository discovery and per-repo cloning were already covered by
Phase 1.4 (resolveAllRepoInfo loops ensureRepoCloned) and the
existing repository_discovery service is repo-list aware by design.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/task-create): repeatable repository rows for multi-repo task creation
Users can now actually create a multi-repo task: a "+ Add repository"
button below the primary repo + branch selectors expands the form with
additional (repository, base-branch) rows. Each extra row picks from a
filtered repository list that excludes the primary and any other already-
chosen extras, so duplicates are impossible to enter.
- ExtraRepositoryRow type + form-state hook (extraRepositories, add /
remove / update / reset). Lives in its own file so the main state hook
stays under the file-length lint cap.
- ExtraRepositoryRows component renders the rows and the "+ Add" button;
per-row branches are loaded on demand via the existing
useRepositoryBranches hook.
- buildRepositoriesPayload accepts the extras and appends them after the
primary, dropping rows with empty repository_id silently so an
unfinished row does not block submit. The backend's duplicate-repo
validation (Phase 8) catches anything that slips through.
- DialogFormBody is split: CreateModeSelectors (selectors + extra rows)
and useDialogHandlers move to dedicated files, keeping touched files
under the lint thresholds.
- Tests cover the multi-repo payload (ordering, drop-empty, no-primary
recovery, single-repo unchanged) and the existing
store-multi-repo.test.ts gets named constants to satisfy the
no-duplicate-string rule.
Verified: pnpm exec tsc --noEmit clean, vitest 608/608 green,
eslint --max-warnings 0 clean.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(agentctl): per-repo workspace tracker for multi-repo git/status
The git/status endpoint now accepts an optional ?repo=<subpath> query
param that selects a sub-directory of the workspace, completing the
per-repo plumbing started in the multi-repo phase. Single-repo callers
keep the workspace-root behavior unchanged.
- Manager.GetWorkspaceTrackerFor(subpath) returns a per-subpath
WorkspaceTracker (lazy + cached). Validation reuses a new
resolveSubpath helper shared with GitOperatorFor, so both code paths
reject path traversal / absolute paths / missing dirs the same way.
- Per-subpath trackers are NOT started (no polling goroutines); the
multi-repo path uses them only for synchronous GetCurrentGitStatus
queries which fall through to getGitStatus when no cache is present.
This keeps per-repo cost cheap.
- handleGitStatus reads c.Query("repo") and routes through the new
resolver, returning a 400 with an error payload on invalid input.
- Tests cover empty subpath (root), valid subpath caching, traversal
rejection.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/review): group file tree by repository for multi-repo task changes
The review file tree now renders per-repo top-level nodes when a task's
changes span multiple repositories, so the same file path in two repos
no longer collapses into a single ambiguous entry.
- ReviewFile.repository_id and ReviewFile.repository_name (optional)
identify which repo each file belongs to. Single-repo callers leave
them unset and the tree falls back to the existing flat grouping.
- buildFileTree splits into buildMultiRepoTree (when 2+ distinct
repository_names are present) and buildFlatTree (the original logic).
Repo roots have isRepoRoot=true and a repositoryId for downstream
filters; their children are full path subtrees per repo.
- collapse() skips repo roots so a repo with a single changed file
still shows its repo header.
- ReviewFileTree renders repo roots with a stronger label, a top
border, and an "N files" count badge; data-testid="repo-root-node"
for E2E coverage. File-level rendering is unchanged.
- Tests cover the flat-tree fallback (no repo info, single repo),
multi-repo grouping, repo-root pinning, and same-filename-different-
repos isolation.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/task-top-bar): "+N" repo chip on multi-repo task header
The task page top-bar breadcrumb now shows a small "+N" chip next to the
primary repository name when the task spans more than one repository,
matching the kanban-card treatment introduced earlier. Hover surfaces the
exact count via tooltip ("frontend (+2 more repos)").
- resolveTaskProps populates repositoryCount from task.repositories.length.
- TaskTopBar threads repositoryCount through to the new
RepositoryBreadcrumb subcomponent.
- The chip carries data-testid="topbar-extra-repo-count" for E2E
selectors.
- TopBarLeft was nearing the function-length / complexity caps; the
breadcrumb extraction restores headroom for future additions.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(web/task-create): disable "Add repository" when no other repos available
When the user only has the primary repository in their workspace,
clicking "+ Add repository" used to insert a row whose dropdown was
empty — looking like a bug ("no other repos show up"). The button now
disables itself when there are no remaining workspace repositories to
choose from, with a tooltip explaining why ("All workspace repositories
are already added"). The previous "primary not selected" guard is also
surfaced via tooltip.
- ExtraRepositoryRows computes remainingCount = repos − used (primary
+ already-added extras) and gates the Add button on it.
- New computeAddButtonHint helper returns a per-state title string for
the disabled cases.
- Tests cover: dropdown shows the unused workspace repos when opened
(the click path the user reported wasn't actually broken — the gate
was just missing); Add button disabled when only the primary exists.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(agentctl): workspace tracker falls back to first repo subdir for multi-repo task roots
The "Changes" panel was empty for multi-repo tasks because the
agent's workspace path is the task root — a plain holder directory
that holds one git worktree per repository as siblings. The workspace
tracker tried to run git commands against that bare root and silently
failed, so no git status updates ever reached the UI.
The tracker now detects this at construction: when the configured
workDir isn't itself a git repo, it falls back to the first immediate
child directory that is. The user gets the primary repo's changes in
the panel; cross-repo aggregation is a follow-up.
- preferGitRepoChildIfRootIsBare scans os.ReadDir entries (skipping
hidden / non-directory entries) and returns the first that has a
valid git index. Logs an info line when the rewrite happens so it's
visible in the agentctl log.
- Repo-less tasks (e.g. quick chat) and single-repo tasks keep their
previous behavior verbatim — the fallback only fires when the root
itself fails resolveGitIndexPath.
- Tests cover: fallback when the workdir is a multi-repo holder,
no-fallback for a real git repo, no-fallback when no git child
exists.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(multi-repo): per-repo workspace tracking — Changes panel shows all repos
The agent's workspace tracker is now split per-repository for multi-repo
task roots. Each repo gets its own tracker that polls git independently
and stamps its repository name onto every emitted event. The Changes
panel aggregates files from every repo and groups them under per-repo
headers using the file-tree machinery from Phase 6.
Backend (agentctl):
- GitStatusUpdate / FileListUpdate gain a RepositoryName field. Empty
for single-repo workspaces (legacy clients see no change).
- WorkspaceTracker carries repositoryName and stamps it onto every
emitted status/file-list. Two constructors: NewWorkspaceTracker for
the legacy single-repo path (with the bare-root fallback) and
NewWorkspaceTrackerForRepo for explicit per-repo trackers.
- Manager scans direct child directories for git repos at construction.
When 2+ repos are found, builds one tracker per repo subdir on top of
the root tracker (which stays bound to the bare task root and emits
nothing useful). Single-repo workspaces are unchanged.
- Manager.SubscribeWorkspaceStream / UnsubscribeWorkspaceStream fan out
one client subscription across the root + all per-repo trackers via
AttachWorkspaceStreamSubscriber / DetachWorkspaceStreamSubscriber on
the tracker. The WS handler switched from the single-tracker subscribe
to the manager fan-out.
- Tests cover: per-repo trackers spawn for multi-repo task roots,
single-repo doesn't, both repos emit GitStatusUpdates tagged with
RepositoryName.
Frontend:
- GitStatusEntry / GitStatusData carry repository_name (optional).
- session-runtime gitStatus.byEnvironmentRepo new map keyed by env id
then repository name; setGitStatus routes per-repo updates into it
while still updating the legacy byEnvironmentId for single-repo
consumers. clearGitStatus drops both maps.
- migrateEnvKeyedData migrates the new per-repo map alongside the
existing keys when sessionId resolves to an environmentId.
- WS git-status handler forwards repository_name from event.status.
- New useSessionGitStatusByRepo hook returns sorted [{repo, status}]
pairs for the active session.
- task-changes-panel mergeReviewFiles iterates statusByRepo when
available, stamping repository_name onto every uncommitted file so
the Changes panel groups them under per-repo headers (using the
ReviewFile.repository_name plumbing from Phase 6).
- Tests: per-repo routing, no overwrite on sibling repo update,
legacy single-repo fallback, clear-on-cleanup.
Verified: pnpm exec vitest run 623/623, eslint --max-warnings 0 clean,
tsc --noEmit clean, make test (backend) clean, make lint 0 issues.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/changes-panel): per-repo group headers above each repo's files
The Changes panel now renders a sticky "frontend / N files" header above
the diffs from each repository so the user can visually distinguish
where each change lives. Single-repo tasks render unchanged (no header
shown when there's only one unnamed group).
- ReviewDiffList groups its file list by repository_name (preserving the
caller's order within each group), then renders one RepoGroupHeader
per group followed by the existing FileDiffSection list. Header gating
rule: show when len(groups) > 1 OR the single group has a non-empty
repository name.
- Group key uses "repo:path" so a file with the same path in two repos
no longer collides on React's reconciliation.
- groupFilesByRepository + RepoGroupHeader live in a sibling
review-diff-list-groups.tsx file to keep review-diff-list.tsx under
the 600-line lint cap.
- Tests cover: no header for plain (no repo_name) files, one header per
repo for 2+ groups, header shown even for a single named repo, file
paths land under the right group's section.
Verified: vitest 627/627, eslint clean, tsc clean.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(lifecycle): propagate RepositoryName through PublishGitStatus
The agentctl WorkspaceTracker stamps every per-repo GitStatusUpdate
with RepositoryName, but the lifecycle PublishGitStatus translation
into GitEventPayload was dropping that field. The orchestrator then
forwarded a status with empty repository_name, the frontend store
routed everything into the empty-key bucket, and the Changes panel's
multi-repo grouping never triggered — no header, no per-repo split.
- GitStatusData gains RepositoryName (omitempty so single-repo
payloads stay byte-identical on the wire).
- PublishGitStatus copies update.RepositoryName onto the payload.
- Test asserts the field survives the publish → subscribe round trip
via the in-memory event bus on the GitEvent.<sessionID> subject.
Restart the agentctl process for any running multi-repo task to pick
up the new field; new launches get it automatically.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(web/changes-panel): per-repo group headers in the dockview Changes tab
The Changes tab in the dockview panel (the Files / Changes (N) tab the
user actually interacts with — not the standalone Review dialog) was
still rendering a flat file list, so multi-repo task changes either
collided onto the legacy single-status (showing only one repo's files)
or rendered without grouping.
- FileInfo gains repository_name (optional, single-repo unchanged).
- useSessionGit aggregates files from useSessionGitStatusByRepo when
multi-repo data is present, stamping each FileInfo with its
repository_name. Falls back to the legacy single status for
single-repo workspaces. Aggregation extracted into
aggregateFilesAcrossRepos to keep useSessionGit under the 100-line
function lint cap.
- ChangedFile (changes-panel.tsx + changes-panel-timeline.tsx) carries
repositoryName through to the renderer.
- FileListSection delegates to a new FileListBody that groups rows by
repositoryName; renders a small per-repo subheader when 2+ repos OR
any single named repo is present, otherwise falls back to the
pre-multi-repo flat list (same DOM shape).
- Tests cover: no header for plain (no repo_name) files, headers
per repo for 2+ groups, single named repo still gets a label.
Restart the backend so the per-repo trackers spawn for in-flight
multi-repo tasks; new launches are unaffected.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(multi-repo): per-repo git ops, unified branch endpoint, chip-style task create
Bundles a string of multi-repo fixes and refactors that came up while
testing the feature end-to-end:
- workspace_path stored on multi-repo TaskEnvironment was one level too
high, so agentctl booted with the wrong WorkDir on cold start; fixed
in resolveTaskEnvWorkspacePath + GetWorkspaceInfoForSession.
- Stage/Unstage/Discard/Commit/Revert/Reset/Amend now thread `repo`
through agentctl client → WS handler → frontend hook → SessionGit
fan-out, so the right git repo is targeted (was running at the task
root, which isn't a git repo for multi-repo tasks).
- agentctl GitLog is multi-repo aware: when no `repo` is specified and
per-repo trackers exist, fans out one log per repo and merges sorted
newest-first with RepositoryName stamped on each commit.
- Per-repo grouping for files (Changes panel) and commits, with
collapsible group headers; commits section defaults to collapsed.
Algorithm extracted into one generic groupByRepositoryName helper
(was copy-pasted three times).
- Task creation dialog rewritten around a unified `fs.repositories[]`
list — no more "primary vs extras" split. Chip-style row with one
pill per repo + branch, "+" to add, x to remove, GitHub URL toggle
inline. Discovered (on-machine) repos appear in any chip's dropdown.
Removes ~6 fields and 3 helpers from the dialog state.
- Branch listing endpoints collapsed to one:
GET /workspaces/:id/branches?repository_id=X | path=Y
Frontend collapses to a single useBranches hook with a tagged-union
source. Drops two HTTP routes, two service methods, two API client
funcs, and one whole hook file.
Tests added across the chain: workspace_path resolver, sort-commits-
by-date, manager poll-mode propagation, RepoSubpaths, chip grouping
+ collapse + per-repo isLatest, group-by-repo helper, dialog payload
builder + chip wiring + discovered-repo flow.
* feat(multi-repo): unified per-repo git controls for all VCS operations
Changes panel and top-bar VCS button render per-repo Stage all, Commit,
Unstage all, Push, Pull, Rebase, Merge, and Create PR uniformly across
single-repo and multi-repo workspaces. Operations route to the correct
git repo subpath; fan-outs collect per-repo results and surface partial
success in the toast layer.
Backend:
- Stamp RepositoryName on Reset/BranchSwitch/FileChange notifications
and forward through orchestrator handlers
- Surface per-repo errors from handleGitLogMultiRepo via PerRepoErrors
Frontend:
- pull/push/rebase/merge/abort/commit fan out via PerRepoOperationResult
- Per-repo group headers always render with action buttons
- Top-bar dropdown lists per-repo Pull/Rebase/Merge entries
- pendingStageFiles keyed per-repo to prevent cross-repo clears
- useRepoDisplayName distinguishes loading from multi-repo
- Commit dialog file summary respects stageAll
- New helpers: changes-panel-helpers.ts, changes-panel-repo-groups.tsx,
use-repo-display-name.ts
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(multi-repo): plumb repo through file/commit/diff endpoints; per-repo PRs and review UI
- backend: thread `repo` subpath through pull/push/rebase/merge/abort, file
content/update, cumulative-diff, and commit-show endpoints; per-repo
fan-out for log + cumulative-diff with each repo's own merge-base; emit
full `repositories` array on task.updated WS payload
- github: store/list TaskPRs as []*TaskPR (per-repo); orchestrator/web store
rekey to `Record<taskId, TaskPR[]>`
- web: aggregate PR icon (count badge + worst-of color, multi-PR tooltip);
branch hover card renders one row per repo with each repo's task base
branch; review dialog merges per-repo file maps with composite keys and
propagates repository_name through diff/expand/revert; commit-detail
panel scopes to the owning repo
- kanban card: chip row of repo names (up to 2 + "+N" overflow, tooltip
lists all)
- task-create dialog: gate non-worktree executors to multi-repo only; move
fresh-branch toggle inline next to the repo chips (icon-only, with
title/aria-label)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(multi-repo): scope PR watches/associations and review UI per repository
Schema: add repository_id to UNIQUE constraints on github_pr_watches and
github_task_prs (with idempotent copy-and-rename migration) so one task
spanning N repos can hold one watch/PR per repo without collisions.
Plumb repository_id through CreatePRWatch/EnsurePRWatch/AssociatePRWithTask
/AssociatePRByURL, fan TriggerPRSync across all per-repo watches, and
disambiguate status sync by (task, owner, repo, pr_number) instead of
"first match". Add Repo to wsCreateFile/Delete/Rename and wsCreatePR/
RenameBranch so file and git ops target the right working tree.
Frontend review dialog: switch reviewedFiles, staleFiles, fileRefs,
selectedFile and comment counts to NUL-separated `${repo}\x00${path}`
keys so same-named files in different repos no longer share state.
useTaskPR consumes the new {prs: TaskPR[]} envelope.
Also: snapshot repoTrackers slice before background refresh in
SetWorkspacePollMode to prevent races with Stop(), and key
mergeCumulativeFiles by NUL-separated (repo, path) to match.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* chore: apply prettier formatting
Unblock CI prettier check on files modified earlier on this branch
that pre-date the current prettier config.
* fix: address PR review feedback and unblock E2E
Backend:
- ListWorkspaceTaskPRs background sweep now uses TriggerPRSyncAll so
multi-repo tasks refresh every per-repo PR (was only the most recently
updated watch). Caught by claude review on #767.
Frontend (no behaviour change):
- Replace literal NUL byte (0x00) in FILE_KEY_SEP and the inline key
builder in use-review-dialog with the explicit escape so the
source is plain ASCII. The runtime separator is unchanged; this just
removes a footgun that GitHub's diff renders as a visible space.
- Show the auto-resolved branch as a small read-only pill next to the
GitHub URL input so the URL-mode dialog surfaces the branch the task
will run on (previously only the URL was visible).
E2E:
- changes-panel-focus / pr-detection / pr-switcher-changes: expand the
commits-section before asserting on commit text -- the section starts
collapsed since the chip-style refactor.
- repository-selector-scroll: open the popover via repo-chip-trigger
instead of the legacy single repository-selector testid.
* test(e2e): align task-create dialog tests with chip refactor
Updates three more tests that broke when the dialog migrated from a
single repository/branch combobox to per-row repo/branch chips and the
URL-mode toggle relabel:
- create-task.spec.ts (pre-select + remembers-selections): switch
repository-selector / branch-selector lookups to repo-chip-trigger /
branch-chip-trigger.
- create-task-github-url.spec.ts (toggle test): the inverse-state label
is now "use a workspace repository", not the legacy
"or select a repository".
No code changes — purely test alignment with the existing UI.
* fix(web): re-apply workbench-chrome topbar + restore branch-selector behaviour
Two regressions surfaced by the multi-repo merge into main:
1. task-top-bar.tsx had been resolved in our favour at the workbench-chrome
merge (#761), losing the TopbarActionOverflow wiring that the new test
asserts on. Re-applies main's topbar structure (TopbarCluster groups,
TopbarActionOverflow, IntegrationsMenu, MoreToolsMenu, SettingsButton)
on top of our multi-repo additions: repositoryCount + RepositoryBreadcrumb
"+N" chip, gitStatus + isMultiRepo plumbing, and the GitAheadBehindBadges
suppression for multi-repo. GitAheadBehindBadges moved to its own file to
stay under the file-length cap.
2. The chip-style task-create dialog dropped the legacy branch-selector
semantics. Restored:
- Local-executor branch lock: the per-row branch chip is now disabled
when isLocalExecutor and fresh-branch is off. The user's checkout
dictates the branch for local execution; fresh-branch unlocks it.
- Branch override: when locked, the chip shows currentLocalBranch
instead of the value the user picked under a different executor
(so worktree -> local doesn't display a stale "develop" pick).
- Branch refresh: useBranches now exposes a refresh() callback for
id-based sources (calls listRepositoryBranches with refresh=true),
and Pill renders BranchRefreshButton in its popover header when
onRefresh is wired.
- URL-mode branch picker: GitHubUrlSection now renders a real
branch-chip-trigger Pill backed by fs.githubBranches instead of a
read-only span, restoring the "branch selectable in URL mode"
behaviour (URL mode is always remote-clone, so the local-executor
lock does not apply).
E2E spec updated: bulk-rename legacy branch-selector / repository-selector
testids to branch-chip-trigger / repo-chip-trigger.first(). All 13
create-task-branch-selector tests pass locally.
* ci: force workflow re-run
* fix(web): unblock E2E shard 2
Three issues showed up only after the merge with main, which brought back
the E2E shard 2 tests touching git/changes-panel and improve-kandev:
1. Wire the TaskCreateDialog slot props (extraFormSlot, aboveDescriptionSlot,
bottomSlot, descriptionPlaceholder) through to DialogPromptSection. They
were declared on the public API but dropped on the floor before this
change, so Improve Kandev's contributor banner ("@octocat" /
"@kandev-maint") never rendered. Also gate the "or paste a GitHub URL"
toggle on lockedFields.repository so the locked-repo dialog hides it
(matches main's behaviour and the existing test expectation).
2. Revert "commits section starts collapsed" (introduced in 9e8079de). The
collapsed-by-default tradeoff is genuine, but it broke 14+ E2E tests
that assert on commit text in the changes panel — the win wasn't worth
the test churn. Updated the unit test to match.
3. Update the git-changes-panel E2E tests to use the stable
`[data-testid^="commit-row-"]` selector instead of `commitsList li`.
The chip-style refactor introduced a per-repo group <li> wrapper, so
counting all <li> descendants now over-counts (1 wrapper + N commits).
Same fix in the "distinguishes pushed and unpushed" test which queried
`li` with text and matched both the wrapper and the commit row.
Locally verified: full shard 2 (45 tests) passes; full unit-test suite
(943 tests) passes; lint + typecheck clean.
* fix: address claude review feedback
Three findings from claude[bot] review on PR #767:
- types.ts: add 13 unit tests for reviewFileKey / splitReviewFileKey
covering bare paths, composite keys, slashes/spaces in paths, repo
names containing slashes, and full round-trip. Asks were repeated
across five review rounds; the round-trip coverage is what catches
the FILE_KEY_SEP NUL-vs-space class of bug at the type level.
- mergeCumulativeFiles (api/git.go): shallow-copy each per-file payload
before stamping repository_name + path so the source map isn't
mutated. The previous code wrote directly into the per-repo result
map, which would have permanently rewritten the original entry if
any future caller iterated the same source twice.
- buildRepoSpecs (executor_execute.go / executor_resume.go): drop the
unused execCfg parameter (and the speculative "reserved for future
per-repo config" suppression). Per repo overrides do not exist
today and the speculative scaffolding masked an actual dead arg.
* docs(readme): mention multi-repository task support
* fix(web/topbar): drop standalone ahead/behind badges (duplicate of split button)
The Create PR / Push button already shows the inline ↑N ↓N counts, so
the separate "3 ahead" / "2 behind" badges next to the PR icon were
just visual noise. Removes the GitAheadBehindBadges component (now
unused) and the gitStatus / isMultiRepo prop chain that fed it.
* fix(github): heal legacy repository_id='' rows on github_task_prs
A task that pre-dated the multi-repo schema kept its github_task_prs row
with repository_id=''. After the schema migration, a subsequent sync
would resolve the task's primary repository_id and CreateTaskPR with the
new value -- but GetTaskPRByRepository(task, repo) returned nil because
the legacy row had an empty repository_id, so the new code inserted a
duplicate row instead of updating the legacy one. Net effect: two rows
for the same PR, surfacing as a "+2" PR badge on a single-repo task.
Adds backfillTaskPRsRepositoryID, run on schema init right after
migratePRTablesForMultiRepo:
1. Dedup pass: when a (task, owner, repo, pr_number) tuple has both a
legacy (repository_id='') and a per-repo row, drop the legacy one.
2. Backfill pass: any remaining empty-repo rows get stamped with the
task's primary repository_id from task_repositories.
The backfill is gated on task_repositories existing -- github-store unit
tests init only this package's schema, and the dedup pass alone is the
load-bearing fix for the symptom.
Tests cover the dedup path, the cross-package-skip path, and idempotency.
* test(github): cover UPDATE backfill path for orphan legacy rows
Adds TestBackfillTaskPRsRepositoryID_BackfillsOrphanRow per claude
review feedback. The two prior tests cover the DELETE dedup path and
the early-exit when task_repositories is absent, but the UPDATE path
that stamps the primary repository_id onto an orphan legacy row had
no coverage -- a wrong column name or off-by-one WHERE would have
slipped through silently.
* feat(web/changes-panel): group PR Changes by repository
Multi-repo tasks now have one TaskPR per repo, but the PR Changes
section was still rendering files flat using only the primary PR.
Adds useActiveTaskPRsWithFiles, which fans out one WS request per
TaskPR and tracks each fetch by (owner/repo/pr_number/last_synced_at)
so a server-side sync invalidates the cache.
Each PR's files are stamped with the resolved repository_name (looked
up from the workspace repos slice), and PRFilesGroupedList groups by
that name -- mirroring how Commits and Changes already render. Single-
repo tasks (one group, empty name) still render flat.
Mechanics:
- PRChangedFile gains an optional repository_name.
- mapPRFilesToChangedFiles takes a repository_name and stamps it.
- New PRFilesGroupedList + PRFilesRepoGroup live in
changes-panel-pr-files.tsx so changes-panel-timeline.tsx stays
under the 600-line cap; PRFilesSection delegates to them.
- Hook uses refs (not state) for the in-flight / fetched dedup so
setState is only called when results arrive.
- Stable EMPTY_PRS sentinel avoids the new-array-each-render trap
that would re-trigger every effect downstream.
- Workspace repo lookup memoised once via useMemo so the merged file
list isn't rebuilt on every render.
* fix(web/changes-panel): show per-repo PR header when task is multi-repo
Previous logic only stamped repository_name on PR files when prs.length > 1
(2+ PRs). For a multi-repo task with only ONE PR yet (one repo doesn't
have a branch / hasn't been pushed), no per-repo header rendered, even
though STAGED and COMMITS already grouped under their repo names. Now
gates the stamp on the task itself being multi-repo, matching how the
other sections decide.
* fix(executor): serialise concurrent LaunchPreparedSession per session
Two paths in task_operations.go call LaunchPreparedSession on the same
session_id:
1. PrepareTaskSession spawns a background goroutine with launchWorkspace=
true the moment a session is created (so file browsing works before
the user clicks Start).
2. StartTaskWithSession runs a foreground launch when the agent is
actually started (workflow auto-start, user click).
Without serialisation both reach agent_manager.LaunchAgent in parallel.
The fast-path check at the top of LaunchPreparedSession (session.Agent
ExecutionID != "") only kicks in once the first call has *persisted*
its execution id; the second call grabs a stale snapshot, runs the full
env-prep + builds runtime, then loses the executionStore.Add race and
fails with "already has an agent running (race resolved during register)".
Visible in the UI as "Environment setup failed".
Multi-repo amplifies the window because env prep runs sequentially per
repo (~2x the time for two repos), so what was a rare flake on
single-repo became consistent on multi-repo tasks.
Fix: acquire the per-session lock (the same sync.Map used by the resume
path) at the entry of LaunchPreparedSession and re-fetch the session
under the lock so the fast-path check sees the AgentExecutionID the
first holder just persisted. Second caller now takes the existing-
workspace path and starts only the agent subprocess, matching the
intended single-launch semantics.
Adds TestLaunchPreparedSession_SerialisesConcurrentLaunches that fires
two concurrent LaunchPreparedSession calls with the first one blocked
inside LaunchAgent. Without the lock, both reach LaunchAgent and the
test fails with call_count == 2; with the lock only the first does.
* fix(orchestrator): per-repo push detection so each repo's PR gets associated
Multi-repo tasks would only get one PR detected per task: the agent
pushes branches in BOTH repos, but the pushTracker keyed by sessionID
alone meant agentctl's per-repo git status events overwrote each
other's ahead counts. Whichever repo's events interleaved unfavourably
lost its >0 -> 0 transition and silently dropped its push detection.
Net effect: only the first/last repo's PR got an associated TaskPR row;
the other PR existed on GitHub but Kandev never knew about it.
Fix:
- pushTracker is now keyed by "<sessionID>|<repository_name>" so each
repo's transitions are tracked independently. Empty repository_name
preserves the legacy single-repo behaviour.
- trackPushAndAssociatePR forwards data.Status.RepositoryName to
detectPushAndAssociatePR.
- detectPushAndAssociatePR resolves owner/name/repository_id for the
specific repo via new resolvePushRepo helper (looks up the task's
task_repository whose repository.Name matches the event), then uses
GetPRWatchBySessionAndRepo to scope the existing-watch check.
- New associatePRFromPushScoped takes the per-repo repository_id
directly instead of always resolving the primary one. CheckSessionPR
(manual "check now") wired through the same scoped helper.
Existing tests pass with the explicit empty repository_name argument.
The user's existing task with the missing kandev PR row needs a manual
push retrigger or DB heal — the migration only deduped legacy empty
rows; this fix prevents the gap from recurring on future tasks.
* feat(web): one PR button per repo in topbar + per-PR detail panels
PRTopbarButton previously rendered just the primary TaskPR via
useActiveTaskPR(), so multi-repo tasks with N PRs only surfaced one.
Switch to useTaskPR(activeTaskId).prs and render one button per PR --
each opens its own dockview panel keyed by owner/repo/pr_number.
Plumbing:
- dockview-store / dockview-panel-actions: addPRPanel(prKey?: string)
builds id "pr-detail|<key>" when a key is supplied; the legacy
single-repo "pr-detail" id stays for the auto-add path.
- dockview-desktop-layout: forwards `params` to PRDetailPanelComponent
so the panel can receive its prKey.
- pr-detail-panel: new prTaskKey helper + the panel looks up the
matching TaskPR from the per-task list when params.prKey is set,
falling back to useActiveTaskPR() for legacy panels and tooltips.
- pr-topbar-button: rewritten to render a button per PR, each labelled
with #pr_number and tooltipped with owner/repo + title; click opens
the per-PR panel.
* feat(web): collapse multi-PR topbar to a dropdown + show every PR in the + menu
Two follow-ups on top of per-PR panels:
- The dockview "+" panel-add menu still listed only state.pr (the primary
TaskPR), so a 2-repo task only offered "PR #2" -- never the kandev
one. Switch to state.prs[] and render one menu item per PR; multi-repo
rows are labelled "PR #N -- repo" so the user can tell them apart.
Each item opens its own panel via addPRPanel(prTaskKey(pr)).
- The topbar grew one outline button per PR after the previous commit,
which doesn't scale (3+ PRs would crowd out other actions). Single PR
keeps the existing single-button rendering; 2+ collapses to one
outline button labelled "N PRs" with the aggregated status colour
(red if any failing, etc.) and a dropdown listing each PR with repo,
number, title, and per-PR status icon. Click an item -> open that
PR's panel.
useLeftHeaderState now reads useTaskPR(taskId).prs and forwards the
full list through AddPanelMenuState as `prs`.
* fix(web/changes-panel): PR files arrive after race-cancelled fetch
useActiveTaskPRsWithFiles dropped responses from the previous effect
instance via a `cancelled` flag, but since the dedup tracking refs
(inFlightRef / fetchedRef) carry across renders, the next effect's
early-continue still saw the key in inFlightRef and skipped a fresh
request. The ref then got populated by the cancelled response and
fetchedRef permanently locked the key out of any future fetch.
Net effect: every render after the first prs reference change left
the merged prFiles array empty -- the PR Changes section never showed
up on multi-repo tasks even though both PRs existed and the WS request
would have returned files.
Drop the cancellation flag entirely. Per-key dedup is enough to prevent
duplicate requests, and the .then handlers use functional setState so
they're safe to land after the effect re-runs.
* test: cover review-feedback gaps (mapPRFilesToChangedFiles, push multi-repo, lock test channel-sync)
Three follow-ups from claude review on PR #767:
1. apps/web/components/task/changes-panel-helpers.test.ts: 5 new tests
for mapPRFilesToChangedFiles. Covers status mapping (added / removed /
renamed / modified / fallback), forwarding of plus/minus/oldPath, and
the new repository_name stamping behaviour (multi-repo path stamps
every row; single-repo path defaults to "" so PRFilesGroupedList
skips per-repo sub-headers).
2. event_handlers_github_test.go: TestDetectPushAndAssociatePR gains
two multi-repo cases. resolvePushRepo must scope CreatePRWatch +
AssociatePRWithTask to the repository_id matching the event's
repository_name (not silently fall back to primary); unknown
repository_name must drop the event rather than mis-associate.
mockGitHubService captures lastCreateWatchRepositoryID /
lastAssociateRepositoryID so the per-repo scoping is asserted
directly.
3. executor_test.go: TestLaunchPreparedSession_SerialisesConcurrentLaunches
replaces the time.Sleep(50ms) coordination with a buffered `entered`
channel + bounded select wait per CLAUDE.md. The test now waits for
the first launch to enter LaunchAgent, then asserts no second entry
arrives within a 100ms window — without the lock the second
goroutine reaches LaunchAgent in microseconds, so the timeout serves
as the "didn't race in" oracle, not a synchronisation primitive.
* fix(orchestrator): detect push when first poll lands post-sync
trackPushAndAssociatePR only fired on a >0→0 ahead transition, which
required two distinct status events to be observed. In multi-repo tasks,
any repo whose first agentctl status poll happened to land after the
push had already completed (ahead=0 with remote branch set on the very
first observation) silently dropped the push event — the watch was
never created, the PR never associated. Reproduced on task
4fdff41b-095a-4158-a311-4a1a23abe064 where 2/3 repos pushed but only
one PR appeared.
Now also fire on first observation when the status already reflects a
post-push state (ahead=0 + RemoteBranch set). detectPushAndAssociatePR
is idempotent against an existing watch, so a spurious fire on a
worktree that started from an already-synced remote just costs one
GitHub FindPRByBranch call.
The deferred pushTracker.Delete in detectPushAndAssociatePR is removed:
keeping ahead=0 stored is what suppresses repeated firing on subsequent
status events. Cleanup now happens at session-delete time via a new
pushTrackerForget helper that walks all (session|repo) entries.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(web/topbar): restore pr-topbar-button testid for single-PR case
The multi-PR refactor renamed PRSingleButton's testid from
pr-topbar-button to pr-topbar-button-${pr_number}, breaking E2E tests
that relied on the stable selector (task-topbar-overflow.spec.ts and
the prTopbarButton page-object helper used by vcs-button-context).
Restore the canonical testid and expose pr_number via data-pr-number
for any test that needs to discriminate. PRMultiButton already uses
the same testid; with at most one PR-area control rendered at a time,
sharing the testid is unambiguous.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(orchestrator): create one PR watch per repo on multi-repo tasks
The orchestrator only ever ensured a watch for a task's PRIMARY
repository. Both call sites that create watches were primary-only:
- ensureSessionPRWatch (called when a session starts/resumes) used
resolvePrimaryTaskRepositoryID and made one EnsurePRWatch call.
- buildTaskBranchList (used by the poller's reconciler) keyed dedup
by sessionID alone, so as soon as the primary repo got a watch
the whole session was marked "watched" and the poller skipped
every other repo.
Result: in a multi-repo task, the secondary repos never got a watch
row, so the periodic GitHub poller never searched for their PRs and
never associated them. Push detection (which fires on >0→0 ahead
transitions vs origin/main) doesn't help here either because Ahead is
measured against the integration branch, not the upstream tracking
branch — pushing doesn't change Ahead.
Reproduced on task a7a59bd8: PRs existed on github for both kandev
and aistats, but only the primary (kandev) was associated.
Refactor:
- resolveSessionWatchTargets walks task_repositories × session
worktrees and returns one (repo_id, owner, repo, branch) target
per repo. Branch priority preserves the legacy precedence
(checkout_branch > primary fallback > worktree branch) so PR-
review-style synthetic worktree names don't clobber the real one.
- ensureSessionPRWatch loops over targets and ensures one watch per
repo.
- buildTaskBranchList emits one TaskBranchInfo per (session, repo)
and dedups against (session_id, repository_id) pairs from
ListActivePRWatches — replacing the old session-only dedup that
suppressed non-primary repos.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
---------
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
1390 lines
51 KiB
TypeScript
1390 lines
51 KiB
TypeScript
import { test, expect } from "../../fixtures/test-base";
|
|
import type { ApiClient } from "../../helpers/api-client";
|
|
import { KanbanPage } from "../../pages/kanban-page";
|
|
import { SessionPage } from "../../pages/session-page";
|
|
import type { Page } from "@playwright/test";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { execSync } from "node:child_process";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Git helper for E2E tests - runs git commands in the test repository
|
|
// ---------------------------------------------------------------------------
|
|
|
|
class GitHelper {
|
|
constructor(
|
|
private repoDir: string,
|
|
private env: NodeJS.ProcessEnv,
|
|
) {}
|
|
|
|
exec(cmd: string): string {
|
|
const lockPath = path.join(this.repoDir, ".git", "index.lock");
|
|
// Retry up to 3 times on index.lock conflicts. The backend's git status
|
|
// polling briefly holds the lock; waiting a short time and retrying is
|
|
// safer than deleting an actively-held lock.
|
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
if (fs.existsSync(lockPath)) fs.unlinkSync(lockPath);
|
|
try {
|
|
return execSync(cmd, { cwd: this.repoDir, env: this.env, encoding: "utf8" });
|
|
} catch (err) {
|
|
const msg = (err as Error).message ?? "";
|
|
if (msg.includes("index.lock") && attempt < 2) {
|
|
execSync("sleep 0.2");
|
|
continue;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
throw new Error(`git exec failed after 3 attempts: ${cmd}`);
|
|
}
|
|
|
|
createFile(name: string, content: string) {
|
|
const filePath = path.join(this.repoDir, name);
|
|
fs.writeFileSync(filePath, content);
|
|
}
|
|
|
|
modifyFile(name: string, content: string) {
|
|
this.createFile(name, content);
|
|
}
|
|
|
|
deleteFile(name: string) {
|
|
const filePath = path.join(this.repoDir, name);
|
|
if (fs.existsSync(filePath)) {
|
|
fs.unlinkSync(filePath);
|
|
}
|
|
}
|
|
|
|
stageFile(name: string) {
|
|
this.exec(`git add "${name}"`);
|
|
}
|
|
|
|
stageAll() {
|
|
this.exec("git add -A");
|
|
}
|
|
|
|
commit(message: string): string {
|
|
this.exec(`git commit -m "${message}"`);
|
|
return this.exec("git rev-parse HEAD").trim();
|
|
}
|
|
|
|
getCurrentSha(): string {
|
|
return this.exec("git rev-parse HEAD").trim();
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Test helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Navigate to a kanban card by title and open its session page. */
|
|
async function openTaskSession(page: Page, title: string): Promise<SessionPage> {
|
|
const kanban = new KanbanPage(page);
|
|
await kanban.goto();
|
|
|
|
const card = kanban.taskCardByTitle(title);
|
|
await expect(card).toBeVisible({ timeout: 15_000 });
|
|
await card.click();
|
|
await expect(page).toHaveURL(/\/t\//, { timeout: 15_000 });
|
|
|
|
const session = new SessionPage(page);
|
|
await session.waitForLoad();
|
|
return session;
|
|
}
|
|
|
|
/** Create a non-passthrough (standard) agent profile for the mock agent. */
|
|
async function createStandardProfile(apiClient: ApiClient, name: string) {
|
|
const { agents } = await apiClient.listAgents();
|
|
const agentId = agents[0]?.id;
|
|
if (!agentId) {
|
|
throw new Error(`E2E setup failed: no agent available for profile "${name}"`);
|
|
}
|
|
return apiClient.createAgentProfile(agentId, name, {
|
|
model: "mock-fast",
|
|
auto_approve: true,
|
|
cli_passthrough: false,
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tests
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test.describe("Git Changes Panel", () => {
|
|
/**
|
|
* Verifies that modified files appear in the unstaged section of the Changes panel.
|
|
* Creates a task, modifies a file in the repository, and verifies the Changes panel
|
|
* shows the modification in real-time via WebSocket updates.
|
|
*/
|
|
test("shows modified files in unstaged section", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Test Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Changes Test", profile.id, {
|
|
description: "Testing git changes panel",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Changes Test");
|
|
|
|
// Set up git helper for the test repository
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create and commit a file so we can modify it
|
|
git.createFile("test-file.txt", "initial content");
|
|
git.stageAll();
|
|
git.commit("Add test file");
|
|
|
|
// Now modify the file
|
|
git.modifyFile("test-file.txt", "modified content");
|
|
|
|
// Click the Changes tab to see the panel
|
|
await session.clickTab("Changes");
|
|
|
|
// Wait for the Changes panel to show the modified file
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// The file should appear in the unstaged section
|
|
// Poll for the file to appear (git status updates via WebSocket)
|
|
await expect(testPage.getByTestId("unstaged-files-section")).toBeVisible({ timeout: 15_000 });
|
|
// Scope the file search to the changes panel to avoid matching Files panel
|
|
await expect(session.changes.getByText("test-file.txt")).toBeVisible({ timeout: 15_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that new untracked files appear in the unstaged section.
|
|
*/
|
|
test("shows new untracked files in unstaged section", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git New File Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git New File Test", profile.id, {
|
|
description: "Testing new file detection",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git New File Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a new untracked file
|
|
git.createFile("new-feature.ts", "export const feature = 'new';");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// The new file should appear in unstaged (scope to changes panel to avoid
|
|
// matching the Files panel which also shows the filename)
|
|
await expect(testPage.getByTestId("unstaged-files-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("new-feature.ts")).toBeVisible({ timeout: 15_000 });
|
|
|
|
// Clean up
|
|
git.deleteFile("new-feature.ts");
|
|
});
|
|
|
|
/**
|
|
* Verifies that files with spaces in their path are shown correctly in the
|
|
* Changes panel and that their diff content is visible (not "No changes").
|
|
* Regression test for: git status --porcelain quotes paths with spaces,
|
|
* and the backend must unquote them so diff lookups succeed.
|
|
*/
|
|
test("shows modified files with spaces in path", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Spaces Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Spaces Test", profile.id, {
|
|
description: "Testing paths with spaces",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Spaces Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a file inside a directory with spaces
|
|
const dirWithSpaces = path.join(repoDir, "path with spaces");
|
|
fs.mkdirSync(dirWithSpaces, { recursive: true });
|
|
fs.writeFileSync(path.join(dirWithSpaces, "file.md"), "initial content");
|
|
git.stageAll();
|
|
git.commit("Add file with spaces in path");
|
|
|
|
// Modify the file to create an unstaged change
|
|
fs.writeFileSync(path.join(dirWithSpaces, "file.md"), "modified content");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// The file should appear in the unstaged section with its unquoted path
|
|
await expect(testPage.getByTestId("unstaged-files-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("file.md")).toBeVisible({ timeout: 15_000 });
|
|
|
|
// Click the file to open its diff and verify content is shown
|
|
await session.changes.getByText("file.md").click();
|
|
|
|
// Verify the diff viewer shows actual diff content (not empty / "No changes").
|
|
// Pierre Diffs renders in a shadow DOM — check all diffs-container elements.
|
|
await testPage.waitForFunction(
|
|
(searchText: string) => {
|
|
for (const container of document.querySelectorAll("diffs-container")) {
|
|
const shadow = container.shadowRoot;
|
|
if (shadow?.textContent?.includes(searchText)) return true;
|
|
}
|
|
return false;
|
|
},
|
|
"modified content",
|
|
{ timeout: 30_000 },
|
|
);
|
|
});
|
|
|
|
/**
|
|
* Verifies that commits appear in the commits section after committing staged files.
|
|
* This tests the full flow: create file → stage → commit → verify in UI.
|
|
*/
|
|
test("shows commits after staging and committing", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Commit Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Commit Test", profile.id, {
|
|
description: "Testing commit flow",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Commit Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create, stage, and commit a file
|
|
git.createFile("feature.ts", "export const x = 1;");
|
|
git.stageAll();
|
|
const sha = git.commit("Add feature module");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// The commit should appear in the commits section
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(testPage.getByText("Add feature module")).toBeVisible({ timeout: 15_000 });
|
|
// Verify the short SHA is displayed
|
|
await expect(testPage.getByText(sha.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that clicking a commit opens its diff view.
|
|
* This tests the integration between the commits list and the diff viewer.
|
|
*/
|
|
test("clicking commit opens diff view", async ({ testPage, apiClient, seedData, backend }) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Diff Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Diff Test", profile.id, {
|
|
description: "Testing commit diff view",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Diff Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a commit with content we can verify in the diff
|
|
git.createFile("diff-test.txt", "line 1\nline 2\nline 3");
|
|
git.stageAll();
|
|
const sha = git.commit("Add diff test file");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for the commit to appear
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
const commitRow = testPage.getByTestId(`commit-row-${sha.slice(0, 7)}`);
|
|
await expect(commitRow).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Click the commit to open its diff
|
|
await commitRow.click();
|
|
|
|
// The diff view should open showing the commit message and file changes
|
|
// Look for the commit message (which uniquely identifies this diff view)
|
|
await expect(session.changes.getByText("Add diff test file")).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Additionally verify the diff shows the actual file content (lines added).
|
|
// Pierre Diffs renders in a shadow DOM — check all diffs-container elements
|
|
// since multiple may exist (inline chat diffs + Changes panel).
|
|
await testPage.waitForFunction(
|
|
(searchText: string) => {
|
|
for (const container of document.querySelectorAll("diffs-container")) {
|
|
const shadow = container.shadowRoot;
|
|
if (shadow?.textContent?.includes(searchText)) return true;
|
|
}
|
|
return false;
|
|
},
|
|
"line 1",
|
|
{ timeout: 60_000 },
|
|
);
|
|
await expect(testPage.getByText("line 1")).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that reverting a commit undoes it (soft reset).
|
|
* Note: The "Revert commit" action does `git reset --soft HEAD~1`,
|
|
* NOT `git revert`. The commit is removed and changes become staged again.
|
|
*/
|
|
test("revert commit undoes commit and stages changes", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Revert Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Revert Test", profile.id, {
|
|
description: "Testing revert commit",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Revert Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a commit to revert
|
|
git.createFile("to-revert.txt", "content to revert");
|
|
git.stageAll();
|
|
const sha = git.commit("Add file to revert");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for the specific commit to appear by SHA
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
const commitRow = testPage.getByTestId(`commit-row-${sha.slice(0, 7)}`);
|
|
await expect(commitRow).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Verify the commit message is shown
|
|
await expect(session.changes.getByText("Add file to revert")).toBeVisible({ timeout: 5_000 });
|
|
|
|
// Click the revert button (hover action on the commit row)
|
|
await commitRow.hover();
|
|
const revertButton = commitRow.getByRole("button", { name: "Revert commit" });
|
|
await expect(revertButton).toBeVisible({ timeout: 5_000 });
|
|
await revertButton.click();
|
|
|
|
// The "Revert commit" action does `git reset --soft HEAD~1`:
|
|
// 1. The commit should disappear from the commits list
|
|
// 2. The file should now appear in the STAGED section
|
|
await expect(session.changes.getByText("Add file to revert")).not.toBeVisible({
|
|
timeout: 15_000,
|
|
});
|
|
|
|
// The file should now be staged
|
|
await expect(testPage.getByTestId("staged-files-section")).toBeVisible({ timeout: 10_000 });
|
|
await expect(session.changes.getByText("to-revert.txt")).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that resetting to a previous commit removes commits from history.
|
|
* Creates commits via git, then resets via the UI dialog.
|
|
*/
|
|
test("reset to commit removes newer commits from history", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Reset Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Reset Test", profile.id, {
|
|
description: "Testing reset to commit",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Reset Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create two commits - we'll reset to the first one
|
|
git.createFile("first.txt", "first file");
|
|
git.stageAll();
|
|
git.commit("First commit");
|
|
|
|
git.createFile("second.txt", "second file");
|
|
git.stageAll();
|
|
git.commit("Second commit");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for both commits to appear
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("First commit")).toBeVisible({ timeout: 10_000 });
|
|
await expect(session.changes.getByText("Second commit")).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Verify both commits appear
|
|
const commitsList = testPage.getByTestId("commits-list");
|
|
await expect(commitsList.locator('[data-testid^="commit-row-"]')).toHaveCount(2, {
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// Find the first commit row (it's the second in the list, older commit)
|
|
// The list shows newest first, so "Second commit" is at index 0, "First commit" at index 1
|
|
const firstCommitRow = commitsList
|
|
.locator('[data-testid^="commit-row-"]')
|
|
.filter({ hasText: "First commit" });
|
|
await expect(firstCommitRow).toBeVisible({ timeout: 5_000 });
|
|
|
|
// Get the SHA from the commit row to use in the confirmation
|
|
const firstCommitSha = await firstCommitRow.locator("code").textContent();
|
|
expect(firstCommitSha).toBeTruthy();
|
|
|
|
// Click the reset button on the first commit row
|
|
await firstCommitRow.hover();
|
|
const resetButton = firstCommitRow.getByRole("button", { name: "Reset to this commit" });
|
|
await expect(resetButton).toBeVisible({ timeout: 5_000 });
|
|
await resetButton.click();
|
|
|
|
// Confirm the reset in the dialog
|
|
const resetDialog = testPage.getByRole("dialog");
|
|
await expect(resetDialog).toBeVisible({ timeout: 5_000 });
|
|
|
|
// Select "Hard Reset" option by clicking the radio button
|
|
const hardResetRadio = resetDialog.getByLabel(/Hard Reset/i);
|
|
await hardResetRadio.click();
|
|
|
|
// Type the commit SHA to confirm hard reset
|
|
const confirmInput = resetDialog.getByPlaceholder(firstCommitSha!);
|
|
await confirmInput.fill(firstCommitSha!);
|
|
|
|
// Click the Reset button
|
|
await resetDialog.getByRole("button", { name: "Reset" }).click();
|
|
|
|
// Wait for the second commit to disappear from the list
|
|
await expect(session.changes.getByText("Second commit")).not.toBeVisible({ timeout: 15_000 });
|
|
|
|
// After a hard reset, the reset TO commit remains in history but any staged/unstaged changes
|
|
// from newer commits are lost (it's a hard reset). Since we reset to "First commit" and
|
|
// that was the original state, there may be no visible "changes" anymore - the commits
|
|
// section might not appear if there are no commits in the "since base" range.
|
|
//
|
|
// For now, verify the reset worked by confirming "Second commit" is gone.
|
|
// The "First commit" may or may not appear depending on whether base_commit_sha is set.
|
|
// The test validates the reset operation completed successfully.
|
|
});
|
|
|
|
/**
|
|
* Verifies that amending a commit updates the commit message in the history.
|
|
* Uses the UI amend button on the latest commit.
|
|
*/
|
|
test("amend commit updates commit message", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Amend Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Amend Test", profile.id, {
|
|
description: "Testing amend commit",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Amend Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a commit to amend
|
|
git.createFile("amend-test.txt", "content");
|
|
git.stageAll();
|
|
const sha = git.commit("Original message");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for the commit to appear
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
const commitRow = testPage.getByTestId(`commit-row-${sha.slice(0, 7)}`);
|
|
await expect(commitRow).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Verify the original message is shown
|
|
await expect(session.changes.getByText("Original message")).toBeVisible({ timeout: 5_000 });
|
|
|
|
// Click the amend button (hover action on commit row)
|
|
await commitRow.hover();
|
|
const amendButton = commitRow.getByRole("button", { name: "Amend commit message" });
|
|
await expect(amendButton).toBeVisible({ timeout: 5_000 });
|
|
await amendButton.click();
|
|
|
|
// Fill in the new message in the dialog
|
|
const amendDialog = testPage.getByRole("dialog");
|
|
await expect(amendDialog).toBeVisible({ timeout: 5_000 });
|
|
const messageInput = amendDialog.getByRole("textbox");
|
|
await messageInput.clear();
|
|
await messageInput.fill("Amended message");
|
|
await amendDialog.getByRole("button", { name: /Amend/i }).click();
|
|
|
|
// Wait for the new message to appear and old message to disappear
|
|
await expect(session.changes.getByText("Amended message")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("Original message")).not.toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that external commits (made outside the UI) appear in the history.
|
|
* This tests the real-time update via WebSocket when commits change.
|
|
*/
|
|
test("external commits appear in real-time via WebSocket", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git External Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git External Test", profile.id, {
|
|
description: "Testing external commit detection",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git External Test");
|
|
|
|
// Click the Changes tab first
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for initial load
|
|
await testPage.waitForTimeout(2_000);
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "External User",
|
|
GIT_AUTHOR_EMAIL: "external@test.local",
|
|
GIT_COMMITTER_NAME: "External User",
|
|
GIT_COMMITTER_EMAIL: "external@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a commit externally (simulating another user or the agent)
|
|
git.createFile("external-file.txt", "external content");
|
|
git.stageAll();
|
|
const sha = git.commit("External commit from another user");
|
|
|
|
// The commit should appear in the UI via WebSocket update (when git status polls)
|
|
// Note: The polling interval may mean we need to wait a bit
|
|
await expect(session.changes.getByText("External commit from another user")).toBeVisible({
|
|
timeout: 30_000,
|
|
});
|
|
|
|
// Verify the commit SHA is shown
|
|
await expect(session.changes.getByText(sha.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that commits persist after a page refresh.
|
|
* This was a critical bug where commits would disappear after refresh
|
|
* because the backend was using the wrong WebSocket handler.
|
|
*/
|
|
test("commits persist after page refresh", async ({ testPage, apiClient, seedData, backend }) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Refresh Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Refresh Test", profile.id, {
|
|
description: "Testing commits persist after refresh",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Refresh Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a commit
|
|
git.createFile("persist-test.txt", "test content");
|
|
git.stageAll();
|
|
const sha = git.commit("Commit that should persist");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for the commit to appear
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("Commit that should persist")).toBeVisible({
|
|
timeout: 10_000,
|
|
});
|
|
await expect(session.changes.getByText(sha.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
|
|
// NOW REFRESH THE PAGE - this is the critical test
|
|
await testPage.reload();
|
|
|
|
// Wait for the session to reload
|
|
await session.waitForLoad();
|
|
|
|
// Click the Changes tab again
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// The commit MUST still be visible after refresh
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("Commit that should persist")).toBeVisible({
|
|
timeout: 15_000,
|
|
});
|
|
await expect(session.changes.getByText(sha.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that multiple commits persist after page refresh.
|
|
* Tests that the commit list is correctly fetched from agentctl after refresh.
|
|
*/
|
|
test("multiple commits persist after page refresh", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Multi Refresh Profile");
|
|
|
|
await apiClient.createTaskWithAgent(
|
|
seedData.workspaceId,
|
|
"Git Multi Refresh Test",
|
|
profile.id,
|
|
{
|
|
description: "Testing multiple commits persist after refresh",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
},
|
|
);
|
|
|
|
const session = await openTaskSession(testPage, "Git Multi Refresh Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create multiple commits — use stageFile() instead of stageAll() to avoid
|
|
// picking up leftover files from prior tests in the shared repo.
|
|
git.createFile("file1.txt", "content 1");
|
|
git.stageFile("file1.txt");
|
|
const sha1 = git.commit("First persistent commit");
|
|
|
|
git.createFile("file2.txt", "content 2");
|
|
git.stageFile("file2.txt");
|
|
const sha2 = git.commit("Second persistent commit");
|
|
|
|
git.createFile("file3.txt", "content 3");
|
|
git.stageFile("file3.txt");
|
|
const sha3 = git.commit("Third persistent commit");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for all commits to appear
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("First persistent commit")).toBeVisible({
|
|
timeout: 10_000,
|
|
});
|
|
await expect(session.changes.getByText("Second persistent commit")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
await expect(session.changes.getByText("Third persistent commit")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// Verify all SHAs
|
|
await expect(session.changes.getByText(sha1.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
await expect(session.changes.getByText(sha2.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
await expect(session.changes.getByText(sha3.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
|
|
// NOW REFRESH THE PAGE
|
|
await testPage.reload();
|
|
await session.waitForLoad();
|
|
|
|
// Click the Changes tab again
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// ALL commits MUST still be visible after refresh
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("First persistent commit")).toBeVisible({
|
|
timeout: 15_000,
|
|
});
|
|
await expect(session.changes.getByText("Second persistent commit")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
await expect(session.changes.getByText("Third persistent commit")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// Verify all SHAs still present
|
|
await expect(session.changes.getByText(sha1.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
await expect(session.changes.getByText(sha2.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
await expect(session.changes.getByText(sha3.slice(0, 7))).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that a rebase operation updates the commit history in the UI.
|
|
* Creates commits on main and a feature branch, then rebases.
|
|
*/
|
|
test("rebase updates commit history", async ({ testPage, apiClient, seedData, backend }) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Rebase Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Rebase Test", profile.id, {
|
|
description: "Testing rebase operation",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Rebase Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Helper to clean up branch - ensures cleanup runs even if test fails
|
|
const cleanupBranch = () => {
|
|
try {
|
|
// Abort any in-progress rebase before switching branches
|
|
try {
|
|
git.exec("git rebase --abort");
|
|
} catch {
|
|
/* not in a rebase */
|
|
}
|
|
git.exec("git checkout -f main");
|
|
git.exec("git clean -fd");
|
|
git.exec("git branch -D feature-rebase");
|
|
} catch {
|
|
// Branch may not exist if test failed before creation
|
|
}
|
|
};
|
|
|
|
try {
|
|
// Clean any leftover state from prior tests (including interrupted rebases)
|
|
try {
|
|
git.exec("git rebase --abort");
|
|
} catch {
|
|
/* not in a rebase */
|
|
}
|
|
git.exec("git clean -fd");
|
|
// Remove feature-rebase branch if it already exists from a previous run
|
|
try {
|
|
git.exec("git checkout -f main");
|
|
git.exec("git branch -D feature-rebase");
|
|
} catch {
|
|
/* branch doesn't exist yet */
|
|
}
|
|
|
|
// Create a commit on a feature branch
|
|
git.exec("git checkout -b feature-rebase");
|
|
git.createFile("feature-file.txt", "feature content");
|
|
git.stageFile("feature-file.txt");
|
|
git.commit("Feature commit before rebase");
|
|
|
|
// Go back to main and create a new commit
|
|
git.exec("git checkout main");
|
|
git.createFile("main-file.txt", "main content");
|
|
git.stageFile("main-file.txt");
|
|
git.commit("Main commit after branch");
|
|
|
|
// Go back to feature branch and rebase onto main
|
|
git.exec("git checkout feature-rebase");
|
|
git.exec("git rebase main");
|
|
|
|
// The feature commit should now be rebased on top of main
|
|
// Click the Changes tab to see the commits
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// After rebase, the feature commit should still be visible
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("Feature commit before rebase")).toBeVisible({
|
|
timeout: 15_000,
|
|
});
|
|
} finally {
|
|
cleanupBranch();
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Verifies that an interactive rebase (squash) updates commit history correctly.
|
|
* Creates two commits and squashes them into one.
|
|
*/
|
|
test("squash commits via rebase updates history", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Squash Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Squash Test", profile.id, {
|
|
description: "Testing squash via rebase",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Squash Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
GIT_SEQUENCE_EDITOR: "true", // Skip interactive editor
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Get base SHA for rebase
|
|
const baseSha = git.getCurrentSha();
|
|
|
|
// Create two commits to squash
|
|
git.createFile("squash1.txt", "first");
|
|
git.stageFile("squash1.txt");
|
|
git.commit("First commit to squash");
|
|
|
|
git.createFile("squash2.txt", "second");
|
|
git.stageFile("squash2.txt");
|
|
git.commit("Second commit to squash");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Verify both commits are visible before squash
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("First commit to squash")).toBeVisible({
|
|
timeout: 10_000,
|
|
});
|
|
await expect(session.changes.getByText("Second commit to squash")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// Squash the two commits into one using git reset --soft and recommit
|
|
git.exec(`git reset --soft ${baseSha}`);
|
|
git.commit("Squashed commit");
|
|
|
|
// Wait for the UI to update - old commits should disappear
|
|
await expect(session.changes.getByText("First commit to squash")).not.toBeVisible({
|
|
timeout: 15_000,
|
|
});
|
|
await expect(session.changes.getByText("Second commit to squash")).not.toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// The squashed commit should appear
|
|
await expect(session.changes.getByText("Squashed commit")).toBeVisible({ timeout: 10_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that the cumulative diff is updated correctly after commits.
|
|
* Creates multiple commits and verifies the diff shows all changes.
|
|
*/
|
|
test("cumulative diff shows all changes from multiple commits", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Cumulative Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Cumulative Test", profile.id, {
|
|
description: "Testing cumulative diff",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Cumulative Test");
|
|
|
|
// Wait for the session to fully initialize including base commit capture.
|
|
// The captureBaseCommit runs async after agent launch, we need it to complete
|
|
// before making commits so the cumulative diff works correctly.
|
|
await testPage.waitForTimeout(3_000);
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create commits with distinct content
|
|
git.createFile("cumulative-file.txt", "line 1: first commit\n");
|
|
git.stageFile("cumulative-file.txt");
|
|
git.commit("Add first line");
|
|
|
|
git.modifyFile("cumulative-file.txt", "line 1: first commit\nline 2: second commit\n");
|
|
git.stageFile("cumulative-file.txt");
|
|
git.commit("Add second line");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for commits to appear
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
|
|
// Wait for both commits to be visible
|
|
await expect(session.changes.getByText("Add first line")).toBeVisible({ timeout: 10_000 });
|
|
await expect(session.changes.getByText("Add second line")).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Click the "Diff" button in the header to open the cumulative diff view
|
|
await session.changes.getByRole("button", { name: "Diff" }).click();
|
|
|
|
// Wait for diff viewer to load
|
|
await testPage.waitForTimeout(2_000);
|
|
|
|
// Verify commits are visible (this proves git changes are tracked)
|
|
await expect(session.changes.getByText("Add first line")).toBeVisible({ timeout: 5_000 });
|
|
await expect(session.changes.getByText("Add second line")).toBeVisible({ timeout: 5_000 });
|
|
|
|
// The cumulative diff should NOT show "No changes"
|
|
await expect(testPage.locator("text=No changes")).not.toBeVisible({ timeout: 5_000 });
|
|
});
|
|
|
|
/**
|
|
* Verifies that sections in the changes panel can be collapsed and expanded.
|
|
* Clicking the section header (label + count + chevron) toggles visibility of the section content.
|
|
*/
|
|
test("sections can be collapsed and expanded", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git Collapse Profile");
|
|
|
|
await apiClient.createTaskWithAgent(seedData.workspaceId, "Git Collapse Test", profile.id, {
|
|
description: "Testing section collapse",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
});
|
|
|
|
const session = await openTaskSession(testPage, "Git Collapse Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create an unstaged file and a committed file so both sections appear
|
|
git.createFile("collapse-committed.txt", "committed content");
|
|
git.stageFile("collapse-committed.txt");
|
|
git.commit("Collapse test commit");
|
|
|
|
git.createFile("collapse-unstaged.txt", "unstaged content");
|
|
|
|
// Click the Changes tab
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Wait for both sections to appear
|
|
await expect(testPage.getByTestId("unstaged-files-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
|
|
// Verify the unstaged file is visible
|
|
await expect(session.changes.getByText("collapse-unstaged.txt")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// Verify the commit is visible
|
|
await expect(session.changes.getByText("Collapse test commit")).toBeVisible({ timeout: 5_000 });
|
|
|
|
// --- Collapse the unstaged section ---
|
|
const unstagedToggle = testPage.getByTestId("unstaged-files-section-collapse-toggle");
|
|
await expect(unstagedToggle).toBeVisible({ timeout: 5_000 });
|
|
await expect(unstagedToggle).toHaveAttribute("aria-expanded", "true");
|
|
await unstagedToggle.click();
|
|
|
|
// The unstaged file should now be hidden and toggle reflects collapsed state
|
|
await expect(session.changes.getByText("collapse-unstaged.txt")).not.toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
await expect(unstagedToggle).toHaveAttribute("aria-expanded", "false");
|
|
|
|
// The section header should still be visible (with count)
|
|
await expect(unstagedToggle).toBeVisible();
|
|
await expect(unstagedToggle).toContainText("Unstaged");
|
|
|
|
// --- Collapse the commits section ---
|
|
const commitsToggle = testPage.getByTestId("commits-section-collapse-toggle");
|
|
await expect(commitsToggle).toBeVisible({ timeout: 5_000 });
|
|
await expect(commitsToggle).toHaveAttribute("aria-expanded", "true");
|
|
await commitsToggle.click();
|
|
|
|
// The commit should now be hidden and toggle reflects collapsed state
|
|
await expect(session.changes.getByText("Collapse test commit")).not.toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
await expect(commitsToggle).toHaveAttribute("aria-expanded", "false");
|
|
|
|
// --- Expand the unstaged section back ---
|
|
await unstagedToggle.click();
|
|
|
|
// The unstaged file should be visible again
|
|
await expect(session.changes.getByText("collapse-unstaged.txt")).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
await expect(unstagedToggle).toHaveAttribute("aria-expanded", "true");
|
|
|
|
// --- Expand the commits section back ---
|
|
await commitsToggle.click();
|
|
|
|
// The commit should be visible again
|
|
await expect(session.changes.getByText("Collapse test commit")).toBeVisible({ timeout: 5_000 });
|
|
await expect(commitsToggle).toHaveAttribute("aria-expanded", "true");
|
|
|
|
// Clean up
|
|
git.deleteFile("collapse-unstaged.txt");
|
|
});
|
|
|
|
/**
|
|
* Verifies that local commits section is hidden when all commits are already
|
|
* in the PR. Only unpushed commits should be shown in the local section.
|
|
*/
|
|
test("shows pushed commits with git-commit icon when all commits are in PR", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git PR Dedup Profile");
|
|
|
|
const task = await apiClient.createTaskWithAgent(
|
|
seedData.workspaceId,
|
|
"Git PR Dedup Test",
|
|
profile.id,
|
|
{
|
|
description: "Testing PR commit deduplication",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
},
|
|
);
|
|
|
|
const session = await openTaskSession(testPage, "Git PR Dedup Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create a commit
|
|
git.createFile("pr-dedup.txt", "dedup content");
|
|
git.stageFile("pr-dedup.txt");
|
|
const sha = git.commit("Commit in PR");
|
|
|
|
// Click the Changes tab and verify commit appears locally
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("Commit in PR")).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Mock a PR that contains the same commit
|
|
await apiClient.mockGitHubAssociateTaskPR({
|
|
task_id: task.id,
|
|
owner: "test-org",
|
|
repo: "test-repo",
|
|
pr_number: 1,
|
|
pr_url: "https://github.com/test-org/test-repo/pull/1",
|
|
pr_title: "Test PR",
|
|
head_branch: "feature",
|
|
base_branch: "main",
|
|
author_login: "e2e-test",
|
|
});
|
|
await apiClient.mockGitHubAddPRCommits("test-org", "test-repo", 1, [
|
|
{
|
|
sha,
|
|
message: "Commit in PR",
|
|
author_login: "e2e-test",
|
|
author_date: new Date().toISOString(),
|
|
},
|
|
]);
|
|
|
|
// Reload to pick up the PR association
|
|
await testPage.reload();
|
|
await session.waitForLoad();
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Unified commits section should show the commit as pushed (git-commit icon, not arrow-up)
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
await expect(session.changes.getByText("Commit in PR")).toBeVisible({ timeout: 10_000 });
|
|
const commitsList = testPage.getByTestId("commits-list");
|
|
await expect(commitsList.locator('[data-testid^="commit-row-"]')).toHaveCount(1, {
|
|
timeout: 5_000,
|
|
});
|
|
// Pushed commits use IconGitCommit (tabler-icon-git-commit), not IconArrowUp
|
|
await expect(commitsList.locator(".tabler-icon-git-commit")).toBeVisible({ timeout: 5_000 });
|
|
await expect(commitsList.locator(".tabler-icon-arrow-up")).not.toBeVisible();
|
|
});
|
|
|
|
/**
|
|
* Verifies that pushed and unpushed commits are visually distinguished
|
|
* in the unified commits list.
|
|
*/
|
|
test("distinguishes pushed and unpushed commits in unified list", async ({
|
|
testPage,
|
|
apiClient,
|
|
seedData,
|
|
backend,
|
|
}) => {
|
|
const profile = await createStandardProfile(apiClient, "Git PR Partial Profile");
|
|
|
|
const task = await apiClient.createTaskWithAgent(
|
|
seedData.workspaceId,
|
|
"Git PR Partial Test",
|
|
profile.id,
|
|
{
|
|
description: "Testing partial PR commit deduplication",
|
|
workflow_id: seedData.workflowId,
|
|
workflow_step_id: seedData.startStepId,
|
|
repository_ids: [seedData.repositoryId],
|
|
},
|
|
);
|
|
|
|
const session = await openTaskSession(testPage, "Git PR Partial Test");
|
|
|
|
// Set up git helper
|
|
const repoDir = path.join(backend.tmpDir, "repos", "e2e-repo");
|
|
const gitEnv = {
|
|
...process.env,
|
|
HOME: backend.tmpDir,
|
|
GIT_AUTHOR_NAME: "E2E Test",
|
|
GIT_AUTHOR_EMAIL: "e2e@test.local",
|
|
GIT_COMMITTER_NAME: "E2E Test",
|
|
GIT_COMMITTER_EMAIL: "e2e@test.local",
|
|
};
|
|
const git = new GitHelper(repoDir, gitEnv);
|
|
|
|
// Create two commits
|
|
git.createFile("pushed.txt", "pushed content");
|
|
git.stageFile("pushed.txt");
|
|
const pushedSha = git.commit("Pushed commit");
|
|
|
|
git.createFile("unpushed.txt", "unpushed content");
|
|
git.stageFile("unpushed.txt");
|
|
git.commit("Unpushed commit");
|
|
|
|
// Mock a PR that only contains the first commit
|
|
await apiClient.mockGitHubAssociateTaskPR({
|
|
task_id: task.id,
|
|
owner: "test-org",
|
|
repo: "test-repo",
|
|
pr_number: 2,
|
|
pr_url: "https://github.com/test-org/test-repo/pull/2",
|
|
pr_title: "Partial PR",
|
|
head_branch: "feature",
|
|
base_branch: "main",
|
|
author_login: "e2e-test",
|
|
});
|
|
await apiClient.mockGitHubAddPRCommits("test-org", "test-repo", 2, [
|
|
{
|
|
sha: pushedSha,
|
|
message: "Pushed commit",
|
|
author_login: "e2e-test",
|
|
author_date: new Date().toISOString(),
|
|
},
|
|
]);
|
|
|
|
// Reload to pick up the PR association
|
|
await testPage.reload();
|
|
await session.waitForLoad();
|
|
await session.clickTab("Changes");
|
|
await expect(session.changes).toBeVisible({ timeout: 10_000 });
|
|
|
|
// Unified commits section should show at least the two commits we created.
|
|
// Other tests in the same worker may have left additional commits in the shared e2e-repo.
|
|
await expect(testPage.getByTestId("commits-section")).toBeVisible({ timeout: 15_000 });
|
|
const commitsList = testPage.getByTestId("commits-list");
|
|
await expect(commitsList.locator('[data-testid^="commit-row-"]').first()).toBeVisible({
|
|
timeout: 5_000,
|
|
});
|
|
|
|
// Unpushed commit should have arrow-up icon (emerald). Scope to the
|
|
// commit-row testid so we don't match the parent repo-group <li> too
|
|
// (which also contains the same text since it wraps the commits).
|
|
const unpushedRow = commitsList
|
|
.locator('[data-testid^="commit-row-"]', { hasText: "Unpushed commit" })
|
|
.first();
|
|
await expect(unpushedRow).toBeVisible({ timeout: 10_000 });
|
|
await expect(unpushedRow.locator(".tabler-icon-arrow-up")).toBeVisible({ timeout: 5_000 });
|
|
|
|
// Pushed commit should have git-commit icon (muted)
|
|
const pushedRow = commitsList
|
|
.locator('[data-testid^="commit-row-"]', { hasText: "Pushed commit" })
|
|
.filter({ hasNotText: "Unpushed" })
|
|
.first();
|
|
await expect(pushedRow).toBeVisible({ timeout: 10_000 });
|
|
await expect(pushedRow.locator(".tabler-icon-git-commit")).toBeVisible({ timeout: 5_000 });
|
|
});
|
|
});
|