Commit Graph

25 Commits

Author SHA1 Message Date
José Almeida f218880ecb feat(plugins): add source-control extension contracts (#2117) 2026-08-13 08:29:29 +01:00
João Salavisa 11f1b20134 test(gitlab): cover WS handlers, watch HTTP routes, and provider identity (#2585)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 22:48:41 +01:00
João Salavisa 1b26646e67 test(gitlab): expand client and service coverage (#2545)
Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-08-12 00:33:38 +01:00
João Salavisa 5df7d5be7f test(gitlab): make the package's tests hermetic against ambient env (#2495)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 19:41:24 +01:00
João Salavisa 70e6eb8895 fix(git): count diff lines by hunk position, not by "+++"/"---" prefix (#2427)
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 19:17:09 +02:00
Alassane 131ef6f6c2 feat(gitlab): add MR auto-fix, auto-merge, hover preview, badge (#2301) 2026-08-08 16:01:39 +01:00
nova28 9e6c2098b1 feat: add GitLab support to workflow sync (#2289)
Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-07 21:06:10 +01:00
Carlos Florêncio acfbf58646 fix: harden remote contribution launch safety (#2294) 2026-08-06 12:07:13 +01:00
Carlos Florêncio 84fe8132a1 feat: support remote contribution tasks (#2265) 2026-08-05 19:25:58 +01:00
Alassane ae31fa85a9 feat(gitlab): add task MR lifecycle notifications (#2125)
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
2026-08-05 18:22:31 +01:00
Alassane 5ab60bf26d feat(gitlab): auto-link merge requests on push and on-demand (#2124) 2026-08-02 17:11:56 +01:00
nova28 5459644bf4 fix(gitlab): parse glab's "Token found:" auth status label (#2054) 2026-07-30 12:27:49 +01:00
Alassane 3c5578285e fix: backfill remote_url from local checkout for legacy GitLab repos (#2030) 2026-07-29 18:14:01 +01:00
Alassane 4411f1c057 fix: match GitLab MR against repository remote_url identity (#1996) 2026-07-28 09:24:57 +01:00
Carlos Florêncio b39a668e99 feat(github): add task git credential policy (#1985) 2026-07-27 18:10:12 +01:00
Carlos Florêncio 3c09b1590a fix: make remote repository entry reliable (#1936) 2026-07-25 11:11:03 +01:00
José Almeida 7de788ceed feat: add cross-integration entity references (#1862)
* feat: add cross-integration entity references

* fix(web): anchor entity reference menu to composer

* fix: keep Kandev tasks under @ mentions

* fix: address entity reference review findings

* test(e2e): use option role for prompt menu

* test(e2e): update passthrough mention roles

* fix: preserve queued references and paginate Azure PRs
2026-07-23 09:03:56 +01:00
Carlos Florêncio 7fd99c3f33 feat: complete GitLab integration parity (#1832) 2026-07-21 23:24:22 +01:00
Carlos Florêncio c2a678b023 feat: add Azure DevOps integration (#1778) 2026-07-21 08:40:26 +01:00
Carlos Florêncio 5ed975ddbf feat: redirect and toast when focused task is auto-deleted (#1544) 2026-06-29 19:10:08 +01:00
Carlos Florêncio e52a8c55f2 fix: persist self-managed gitlab host (#1488) 2026-06-24 23:02:16 +01:00
João Salavisa dfaab11959 feat: full GitLab integration — parity with GitHub (#1120)
* feat(backend): full GitLab parity — store, service, poller, WS, presets

Add the watcher/poll/write-action surface on top of the existing GitLab
client + service skeleton:

* 5 new SQLite tables (mr_watches, review_watches, review_mr_tasks,
  issue_watches, issue_watch_tasks, action_presets) + CRUD
* Client + Service: MergeMR, GetProjectMergeMethods, GetProtectedBranch,
  ListUserProjects, SearchProjects, SetMRLabels, SetMRAssignees
* Service: review/issue/MR watch CRUD + Check/Trigger, GetStats,
  CleanupAllReview/IssueTasks (cleanup-policy aware), TriggerMRSync,
  action-presets CRUD with defaults
* Background poller (MR / review / issue loops) wired from main.go
* ~35 GitLab WS action constants + handlers.go registrations
* Mock controller for E2E seeding (MRs, issues, pipelines, discussions,
  approvals, branches)
* eventBus + taskDeleter + taskSessionChecker plumbed through Service
* Event types: GitLabMRFeedback / NewReviewMR / NewIssue / TaskMRUpdated

* feat(web): GitLab frontend parity — types, API, store slice, domain hooks

Extend the frontend GitLab integration on top of the new backend surface:

* HTTP API client expansion (gitlab-api.ts): full CRUD for review/issue/MR
  watches, MR write actions (merge/approve/labels/assignees), MR
  files/commits/feedback, action presets, projects autocomplete, stats
* Store slice expansion: review/issue/MR watches lists, action presets
  by workspace, stats + status with loading flags. Properties prefixed
  with gitlab to avoid collision with GitHub slice
* Domain hooks: use-gitlab-status, use-gitlab-stats,
  use-gitlab-review-watches, use-gitlab-issue-watches,
  use-gitlab-action-presets — mirror github hook shapes
* Type model: ReviewWatch, IssueWatch, MRWatch, ActionPresets, Stats,
  ProjectMergeMethods, MRApproval, Pipeline, MRFeedback, etc.
* Backend controller HTTP routes for watches/presets/write-actions/
  projects/stats so the frontend HTTP API client has endpoints to hit

All passes: backend (build + vet + lint + tests), web (typecheck + lint +
2400 tests).

* fix(gitlab): wire orchestrator event handlers, fix label-filter drop, add tests

Address Claude review blockers on the parity PR:

1. Wire orchestrator subscriptions for GitLab review/issue watch events.
   Add event_handlers_gitlab.go with handleGitLabNewReviewMR /
   handleGitLabNewIssue, dedup reservation handshake, and task-creator
   interfaces (mirrors event_handlers_github.go). main.go now calls
   orchestratorSvc.SetGitLabService so the dedup APIs are usable
2. Fix silent label-filter drop: when a custom_query is set on an issue
   watch, labels were being appended to the unused filter arg. Fold
   labels into customQuery (or default filter) so they actually reach
   GitLab; extracted appendLabelsToQuery helper with explicit handling
   of pre-existing labels= clauses
3. Switch event payloads to pointer types (mirrors GitHub) so
   handlers can type-assert pointer events
4. Backend tests: store_watches_test.go (CRUD + reserve/assign for all
   4 new tables + presets), service_watches_test.go (label-filter
   helper, cleanup policy, project normalisation), action_presets_test.go
5. Frontend slice tests: review/issue watch CRUD round-trips, action
   presets + stats reducer coverage

All green: backend (build+vet+lint+tests), web (typecheck+lint+2403 tests).

* fix(gitlab): address remaining blockers — cleanup wiring, safe defaults, nil guards

Address the second round of Claude review blockers:

1. main.go: wire SetTaskDeleter + SetTaskSessionChecker on services.GitLab
   (mirrors GitHub). Without these, manual cleanup sweeps would always
   error with "task deleter not configured"
2. service_cleanup.go: default cleanup policy on transient DB error is now
   CleanupPolicyNever (preserve tasks) instead of CleanupPolicyAuto
   (silently delete). Genuine "watch was deleted" path also falls under
   the safe-side default; user can manually delete the orphan tasks
3. service_watches.go: add nil guards on requireStore() so the 6 MR-watch
   list/get/delete methods return an errStoreUnavailable error instead
   of panicking when the SQLite store failed to construct at boot
4. use-gitlab-status.ts + use-gitlab-stats.ts: add per-mount attemptedRef
   so an unreachable GitLab doesn't trigger an infinite re-fetch loop —
   the previous useEffect re-ran every render because the failure path
   left status null, satisfying the !status guard

* fix(gitlab): propagate session-check errors, clamp poll interval on update

Address remaining Claude blockers:

* service_cleanup.go: HasUserAuthoredMessage transient errors are now
  preserved (return false → skip delete) instead of silently ignored;
  the alternative was occasionally deleting tasks a user had touched
* service_watches.go: extract clampPollInterval helper applying the same
  bounds (0 → default, <60 → 60) as the create path; both
  applyReviewWatchPatch and applyIssueWatchPatch use it so user-supplied
  zero or tiny values via UpdateXxxWatchRequest no longer hammer GitLab

* fix(gitlab): clear dupl lint, fix preset retry loop + per-workspace watch cache

* service_watches.go: applyReviewWatchPatch / applyIssueWatchPatch get
  nolint:dupl markers — they share shape but per-domain field validation
  lives in the create paths, so deduplicating via generics would obscure
  the contract. Restores backend lint to 0 issues
* use-gitlab-action-presets.ts: per-workspace attemptedRef set so a
  failing preset fetch doesn't retry on every render
* use-gitlab-review-watches.ts + use-gitlab-issue-watches.ts: track
  lastFetchedRef per consumer so a workspace switch triggers a refetch.
  The slice-level loaded flag is shared across instances and can't
  double as a per-workspace cache key

* fix(gitlab): add nil-store guards across review/issue watch + cleanup paths

Round-3 Claude finding: ReviewWatch / IssueWatch / preset / reservation
methods still called s.requireStore().X() directly. If NewStore fails at
boot (table migration error), the service struct's store is nil and every
list/get/update/create/reserve method panics on first request.

Apply the same store-nil → errStoreUnavailable pattern from f95a929 to
every remaining method:
* CreateReviewWatch / CreateIssueWatch
* GetReviewWatch / ListReviewWatches / ListAllReviewWatches /
  UpdateReviewWatch / TriggerReviewWatchAll
* GetIssueWatch / ListIssueWatches / ListAllIssueWatches /
  UpdateIssueWatch / TriggerIssueWatchAll
* ReserveReviewMRTask / AssignReviewMRTaskID / ReleaseReviewMRTask
* ReserveIssueWatchTask / AssignIssueWatchTaskID / ReleaseIssueWatchTask
* lookupReviewPolicy / lookupIssuePolicy (return CleanupPolicyNever)

* fix(gitlab): nil-store guards on CheckXxxWatch + DeleteXxxWatch + cleanup paths

Round-4 Claude finding: 4 remaining panic sites the previous nil-guard
pass missed — these run from the background poller (every 5 min) and the
manual delete/cleanup flows, so a boot-time NewStore failure would
crash the orchestrator process on first tick.

* service_watches.go: add store-nil guards to DeleteReviewWatch /
  DeleteIssueWatch / CheckReviewWatch / CheckIssueWatch
* service_cleanup.go: guard CleanupAllReviewTasks / CleanupAllIssueTasks
  entry points; wrap the trailing DeleteReviewMRTask / DeleteIssueWatchTask
  calls in `if store := s.requireStore(); store != nil` blocks so the
  cleanup succeeds even when the dedup-row delete is unreachable

* refactor(gitlab): split service_watches.go to stay under 800-line revive limit

CI's --new-from-rev lint caught service_watches.go at 808 lines (limit
800). Split into three focused files:

* service_events.go (94 LOC) — publish helpers for MR feedback /
  new review MR / new issue / watch lifecycle events
* service_issue_watches.go (302 LOC) — Issue watch CRUD + Check +
  Trigger + fetch + helpers
* service_reservations.go (59 LOC) — Reserve/Assign/Release dedup
  handles used by the orchestrator event handlers

service_watches.go is now 505 lines and contains MR watch + Review
watch only. No behavioral change.

* fix(gitlab): address inline code-review feedback

Address actionable inline comments from Claude/CodeRabbit/cubic/Greptile:

* appendLabelsToQuery: use url.ParseQuery for exact key match instead
  of strings.Contains; previously false-matched keys like mylabels=
  and silently dropped the watch's labels (test added)
* fetchReviewMRs: drop dead `filter = watch.CustomQuery` assignment —
  SearchMRs's buildMRSearchQuery returns customQuery verbatim and
  ignores filter when customQuery is non-empty
* store.go: add workspace_id indexes on gitlab_review_watches and
  gitlab_issue_watches (the 5-min poller and HTTP list endpoints did
  full table scans)
* mock_client.SearchProjects: switch from == to case-insensitive
  Contains so partial-query autocomplete returns the seeded project,
  matching the doc comment
* Poller: add sync.Mutex to guard `started` field; Start/Stop are
  now safe to call concurrently (go test -race would have flagged
  the previous read/write race)
* Add ErrWatchNotFound sentinel; controller_watches.go maps it to
  HTTP 404 via httpRespondError helper. Update/Trigger handlers
  previously returned 500 for missing watches, hiding the distinction
  from real server faults
* service_events.go: log Publish errors on watch lifecycle events
  instead of swallowing them silently
* handlers.go: reject malformed JSON payloads in list-style WS
  handlers rather than silently falling through to broader
  list/search behavior
* event_handlers_gitlab.go: remove dead gitlabRepoSlug helper +
  blank-identifier suppression

* ci: re-trigger to clear flaky E2E shard 3

* fix(gitlab): address final review round — nil guards, store merge, logs, body validation

- CheckMRWatch, UpdateReviewWatch, UpdateIssueWatch: nil guards for store/req
- handlers: wsNewDiscussionNote rejects empty body
- action_presets: Update reads raw stored row (no default freezing);
  Reset validates workspace_id
- service_search.GetStats: log Warn per sub-call failure before zero
- event_handlers_gitlab: log Release* dedup-row errors with context
- web/store.ts: post-slice merge restores every GitLab sub-state field;
  extract buildStateOverrides helper
- web/default-state.ts: add GitLab fields to defaultState +
  mergeInitialState via mergeGitLabFields helper
- web/gitlab-api.ts: UpdateXxxWatchRequest now Omit workspace_id

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>
2026-06-02 22:10:07 +01:00
João Salavisa 9fabc7f5cd fix(gitlab): scope /gitlab page tabs to the authenticated user (#1068)
* fix(gitlab): scope /gitlab page tabs to the authenticated user

The Assigned/Authored/Review-requested tabs sent the bare tab token
(`assigned_to_me`, `created_by_me`, `review_requested`) as the `filter`
query param. The backend parsed `filter` as a `key=value` string via
`appendFilter`, so the token contributed nothing — combined with the
hardcoded `scope=all`, the page served the global, unscoped MR/issue
listing instead of the user's own queue.

Add `translateUserSearchFilter` to map the well-known tab tokens to the
correct GitLab params (`scope=assigned_to_me`, `scope=created_by_me`,
or `reviewer_username=<me>&scope=all` for review-requested) and call it
from the two user-search controller handlers. `custom_query` and raw
`key=value` filters keep their existing power-user passthrough.

Cover the fix with unit tests on the translator, wire-shape tests on
`SearchMRsPaged`/`ListIssuesPaged`, and a new `controller_test.go` that
drives the controller end-to-end against an `httptest` GitLab stub.

* fix(gitlab): 500 when review_requested resolves to empty GitLab username

Review follow-up: translateMRFilter previously surfaced a 500 only when
GetAuthenticatedUser returned an error. If the call succeeded but
produced an empty username (NoopClient, an unexpected GitLab response),
translateUserSearchFilter returned an empty string and the controller
silently fell through to SearchMRsPaged with the bare "review_requested"
token — appendFilter parsed it as an empty-value key and the page served
the unscoped global listing, re-introducing the original bug.

Now error out with a 500 in that case and cover it with a regression
test that asserts the upstream /merge_requests endpoint is never even
called when the username comes back blank.

* fix(gitlab): reject review_requested on issues endpoint with 400

Silently falling through to an unscoped listing when filter=review_requested
is sent to /gitlab/user/issues would re-introduce the exact bug this PR fixes
for MRs. GitLab has no reviewer-assigned concept for issues, so the controller
now returns 400 Bad Request and short-circuits before calling ListIssuesPaged.

Also extracts filterTokenReviewRequested as a package constant (goconst
enforces this for the three occurrences across controller.go and
client_helpers.go) and adds a regression test.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(gitlab): use filterTokenReviewRequested constant in translateMRFilter

Missed substitution from the previous commit: translateMRFilter still
compared against the raw "review_requested" literal instead of the new
package constant. No behaviour change.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 10:17:49 +01:00
José Almeida 3bc092bf20 feat(terminal): first-class user terminals — stable seq, rename, park/resume (#1009)
* feat(terminal): persist user terminals with stable seq + park state

Ordinary user shells now have a DB-backed `user_terminals` row keyed by
the agentctl PTY id, carrying a per-task monotonic seq (gaps preserved on
delete), custom_name override, and open/parked state. The terminal
service owns the create/list/rename/park/resume/destroy surface and
guards reject `bottom-panel` (cmd+J) + `script-*` ids so passthrough
flows are untouched. Closing a tab now parks (PTY keeps running);
destroy kills the PTY and removes the row.

* feat(web): expose terminal seq badge, rename, and parked-terminals menu

Wires the right-panel strip and SSR page state to the new task-keyed
terminals endpoint and discriminated UserShell union, adds the `#N`
badge for ordinary terminals, plumbs context-menu / double-click rename,
and renders a "Parked" submenu so closed-but-running terminals can be
resumed. Closing a managed tab now parks instead of destroying so the
PTY (and its buffer) survives accidental closes.

* test(terminal): e2e coverage for first-class persistent entities

Covers the persistence guarantees the user explicitly called out:
monotonic seqs, refresh-survives-rename-and-park, gap-preserving destroy,
park+resume cycle, and bottom-panel/script guards. Exercises the new
user_shell.{create,list,rename,park,resume,destroy} WS actions through
the shared ApiClient.wsRequest helper.

* fix(terminal): atomic seq allocation + propagate destroy errors

- Repository.Create folds MAX(seq) read + INSERT into a single
  `INSERT … SELECT` statement so concurrent creates can no longer pick
  the same seq. Locked in with TestCreate_ConcurrentSeqAllocation (25
  parallel creates, all unique).
- wsUserShellStop now propagates the service-Destroy error so the
  frontend stops optimistically removing a row the backend failed to
  delete.
- Service.Destroy / CleanupTask log PTY-stop failures at Warn (instead
  of silently swallowing) while keeping the proceed-on-failure semantics
  intentional — the DB row is the source of truth for "user expects
  this terminal gone".
- IsUserShellAlive copies ProcessID under the read lock before calling
  r.Get(), removing the post-unlock pointer-deref race.
- Get-not-found test asserts errors.Is(err, ErrNotFound) so it locks to
  the repository contract.

* fix(web): close-tab waits for backend ack + className undefined guard

- handleCloseTab defers `removeTerminal` into the `.then()` of the
  park/destroy promise. A failed backend call leaves the tab visible
  rather than vanishing it optimistically; the next `user_shell.list`
  poll reconciles state.
- session-tabs guards `tab.className` with `?? ""` so an undefined value
  no longer produces "undefined group relative..." in the rendered
  class string.
- user-shells.test simplification: `createSessionRuntimeSlice` only
  consumes `set`, so the test passes the slice creator straight to
  `immer()` instead of wrapping it in an adapter with unused args.

* fix(terminal): task-scoped mutations + legacy-shell list + UI hardening

Round-2 review feedback (cubic P1/P2, claude, coderabbit):

Backend:
- Rename/Park/Resume/Destroy now require a task_id and verify the
  terminal belongs to that task via a shared requireOwnership helper.
  Cross-task mutations return ErrTaskMismatch instead of silently
  succeeding by raw terminal id.
- wsUserShellList no longer drops managed-shaped agentctl shells when
  the terminal service is disabled or task_id is missing — legacy
  passthrough callers see their existing shells again. `managedCovered`
  flag scopes the orphan filter to the DB-backed path.
- service_test.go uses the shared-cache in-memory SQLite + MaxOpenConns(1)
  setup, matching repository_test.go and removing the flake-one-race-away
  warning.
- New cross-task guard tests: TestRename_RejectsCrossTask,
  TestPark_RejectsCrossTask, TestDestroy_RejectsCrossTask, plus a
  TestRename_EmptyTaskIDSkipsOwnership for internal callers.

Frontend:
- updateUserShell patch type narrowed to Partial<Omit<UserShellInfo,
  "terminalId">> so the row key can't be silently mutated.
- destroyUserShell now throws on a missing WS client instead of silently
  resolving — handleCloseTab's .then() no longer fires prematurely.
- rename/park/resume/destroy API client + useTerminals hook plumb the
  active task id through every mutating call.

E2E:
- New "cross-task mutating ops are rejected" spec creates a terminal
  under task A and verifies task B can't rename/park/destroy it by raw
  id.
- Existing specs updated to send task_id with their mutating calls.

* fix(terminal): require task_id on all mutators + wire taskID into hooks

Round-3 review feedback (cubic P1, claude blocker, coderabbit):

Backend:
- requireOwnership no longer skips the ownership check when taskID is
  empty. The previous carve-out was reachable from the WS layer (where
  task_id is user-controlled), so an attacker who guessed a terminal id
  could omit task_id and mutate any row. CleanupTask walks the repo
  directly and never touched the bypass.
- TestRename_EmptyTaskIDRejected pins the new contract.

Frontend (the real bug claude caught):
- useUserShells now accepts a taskId parameter and forwards it on the
  user_shell.list WS call. Without it the backend's DB-backed ordinary-
  shell path was skipped and the Zustand store wiped the SSR-hydrated
  panel strip on the first WS fetch.
- Response mapping switched to a discriminated union: id (new field)
  falls back to terminal_id (legacy), and kind/seq/state/pty_status/
  display_name/custom_name flow into the store so the parked-terminals
  submenu actually populates.
- useTerminals + useMobileTerminals read the active task id from the
  store and pass it through to useUserShells.
- destroyUserShell now retries with user_shell.stop when the server
  returns an unknown-action error — keeps the rollout-window
  compatibility intact for older backends that only know the legacy
  action name.

* fix(terminal): list parked, rollout-safe kind default, helper extraction

Round-4 review feedback (claude + greptile P1):

- useUserShells now sends include_parked: true so the "Parked terminals"
  submenu populates after a page reload. Previously the WS list returned
  only state=open rows; parked terminals were invisible until the user
  parked something in the same session. The main strip still hides
  parked entries via buildTerminalsFromShells.
- useAddTerminal stops blindly defaulting kind to "ordinary" — that
  misclassified legacy passthrough payloads (terminal_id without seq)
  during a rollout where the frontend is newer than the backend. The
  managed-tab path then called parkUserShell on a server that didn't
  know the action. Now only tags as ordinary when kind is explicit or
  the row carries a seq.
- handleCloseTab extracted into a standalone useCloseTab + helpers
  hoisted into use-terminals-build.ts / use-terminals-types.ts. Brings
  use-terminals.ts back under the 600-line file limit and the
  useTerminalActions wrapper inside the 100-line function limit.

* fix(terminal): scope-keyed shell cache + null-task guard + tighter rollout default

Round-5 review feedback (cubic P1, coderabbit x4):

- useUserShells now keys its fetch cache on env+task (`${env}:${task}`),
  not just env. An earlier load without a task id (e.g. before the
  active task hydrated) no longer pins the store on a legacy-only shell
  list and blocks the task-scoped refetch.
- useMobileTerminals delays auto-create until a real taskID is
  available. Previously a null taskID could bootstrap a legacy
  non-persistent shell, mark the env as auto-created, and starve the
  real task of its first-class terminal. Guard key is now env:task, and
  releaseAutoCreatedEnvironment clears every scope on that env.
- useAddTerminal tightens the rollout check: a row is "ordinary" only
  when `seq !== undefined`. A bare `kind: "ordinary"` without seq from
  an older backend stays legacy so close → destroy on the first click.
- useRemoveTerminal reads the current activeTab from a ref instead of
  closing over the value captured when handleCloseTab first ran. Async
  park/destroy resolves after a user tab-switch no longer clobber the
  newer selection with the stale fallback shift.

Tests:
- New "waits for taskID before auto-creating — null taskID is a no-op"
  case in use-mobile-terminals.test.ts confirms the null-task guard.
- All existing mobile-terminal + slice + E2E tests pass.

* fix(terminal): live activeTab lookup + selectable-tab guard

Round-6 review feedback (cubic P2 x2):

- getActiveTab now reads the active tab from the Zustand store via
  storeApi.getState() instead of a useRef/useEffect pair. Closes the
  post-render race where an async close handler could resolve between
  the new render's commit and the effect-driven ref sync.
- computeTerminalTabValue requires activeTab to be selectable
  (present in `terminals` or === "commands") before honoring it. A
  stale id left over from a parked/destroyed terminal no longer pins
  the panel on a nonexistent tab and blocks the fallback shift to a
  real shell.

* chore(terminal): inline savedTabFromStorage to drop file under line cap

Round-7 review feedback (claude suggestion): the useMemo around the
synchronous getSessionStorage call was zero-value memoisation that
pushed use-terminals.ts three lines over the 600-line max-lines limit.
Inlined; file now at 600 lines.

* chore(terminal): drop savedTabExists local + comment to land under 600 lines

Round-8 follow-up (claude): the previous commit's two-line comment block
held the file at 603 lines (still over the 600-line cap). Inline
savedTabExists at the only call site and remove the redundant comment —
the round-7 PR thread already explains why the useMemo was removed. File
now at 599 lines.

* fix(terminal): plumb task_id through dockview + tolerate legacy destroys

Manual-test feedback: clicking X on a dockview terminal panel surfaced
"destroy terminal: terminal does not belong to the supplied task" because
the dockview path was creating + destroying terminals without sending
task_id at all. The new requireOwnership guard then correctly rejected
the empty task_id against a non-empty term.TaskID.

Frontend:
- addTerminalPanel grows task_id + title parameters; stamps both into
  panel params at creation time so the destroy cleanup can pass them
  back to user_shell.destroy / .stop.
- Every dockview-side createUserShell call site now passes the active
  task_id, so the backend creates a DB-backed ordinary terminal (with
  seq + displayName) instead of a legacy passthrough shell.
- destroyUserShell + stopUserShell already accepted an optional task_id;
  dockview-layout-setup.onDidRemovePanel now reads the stamped task id
  from panel params and forwards it.

Backend:
- wsUserShellStop now requires both terminalSvc and a non-empty
  req.TaskID before routing through the managed service. An empty
  task_id falls through to the legacy passthrough StopUserShell so older
  clients (and dockview panels persisted before task_id was stamped)
  keep working.

Known follow-ups (separate task): the #N badge, rename context menu,
and parked-terminals dropdown still only show on the mobile/tablet
right-panel strip. Desktop dockview shows the seq inside the panel
title text but doesn't expose the badge/rename/parked-list UI yet.

* feat(terminal): dockview tab badges + rename context menu + existing-terminals list

Manual-test feedback round 2:

- Custom dockview tab component (TerminalTab) renders the #N pill
  only when the active env has more than one ordinary terminal —
  mirrors the session-tab badge semantics. Right-click on any ordinary
  terminal tab now exposes Rename / Park / Destroy.
- Dockview + menu picks up a new "Terminals" section listing every
  ordinary terminal for the active task (open and parked). Clicking a
  row focuses the existing dockview panel if one is mounted, otherwise
  re-opens it; parked rows are auto-resumed via user_shell.resume
  before the panel is added. The base "Terminal" action was renamed
  to "New Terminal" so the existing-terminals list is distinguishable
  in the menu.
- Reopen menu uses a stable EMPTY_SHELLS sentinel for its store
  selector to avoid Zustand infinite re-renders when the env has no
  shells.

E2E:
- terminal-new-tab.spec uses getByRole("menuitem", { name: "New
  Terminal", exact: true }) to disambiguate from the new "Terminals"
  submenu label.
- Full terminal suite still passes (26/26).

* fix(terminal): tab title shows "Terminal" with seq as badge, populate store on session page

Re-reading the user feedback: the title text was rendering as
"Terminal 1" (backend's displayName), and the dockview "+" menu's
Terminals section was empty because nothing on desktop was calling
useUserShells to populate the store.

- TerminalTab.pickDisplayName now returns the literal "Terminal" for
  ordinary terminals (custom names still override). The seq lives only
  in the sibling badge — same split as session-tab where the agent
  name is the title and the seq is a pill before it. Reading "Terminal
  1" out of "[1] Terminal" instead of "[1] Terminal 1".
- LeftHeaderActions (dockview "+") now calls useUserShells on mount.
  Without this the desktop layout never triggered the WS list fetch,
  so the Terminals submenu and the badge "count > 1" check both saw
  an empty store and silently disappeared.
- TerminalReopenMenuItems also calls useUserShells defensively (cheap
  thanks to scope-keyed cache) so it works when mounted in isolation.

* feat(terminal): "New X" rows live inside their section labels

User feedback: move "New Agent" under the Agents section header and
"New Terminal" under the Terminals section header so the dockview "+"
menu reads top-to-bottom as Agents → New Agent → existing sessions →
Terminals → New Terminal → existing terminals → other panels.

- SessionReopenMenuItems accepts an optional onNewSession prop and
  renders the "New Agent" row as the first item under the "Agents"
  label. Render gate now keeps the section visible whenever the create
  handler is supplied, even with zero existing sessions.
- TerminalReopenMenuItems gets a matching onNewTerminal prop with
  the same behaviour ("New Terminal" row under the "Terminals" label).
- dockview-add-panel-items drops its standalone "New Agent" and "New
  Terminal" rows since both now live inside their sections.

* feat(terminal): auto-migrate default panel to DB-backed ordinary terminal

The legacy `terminal-default` dockview panel was hard-wired to a
non-managed `shell-default` PTY so it never picked up an ordinary
seq/customName/parked state — the new "Terminal N" badge UX could
only show a badge once the user had explicitly created a second
terminal. With useEnsureDefaultTerminalOrdinary the default panel is
upgraded into a real `shell-<uuid>` row on session-page mount, so
every visible tab is now a first-class ordinary terminal.

Plus a UI-level e2e spec asserting the multi-terminal title + badge
contract, and an expectation bump on the existing rename+park spec
since visiting the session page now mints 1 extra ordinary terminal.

* fix(terminal): park ordinary terminals on tab close so they survive refresh

Dockview's tab X close button routed straight to stopUserShell (an
alias for destroyUserShell), wiping the DB row on close — after a
refresh the user had no way to resume a still-running PTY they had
just tucked away.

The X is now a "hide for now" affordance: ordinary terminals get
parked (PTY survives, row stays in DB, reappears in the "+" →
Terminals menu with a `parked` pill), while scripts / bottom-panel /
legacy passthrough shells stay on the destroy path because they have
no resume story.

Permanent delete still lives on the right-click Destroy menu item
and (in the next commit) on each reopen-menu row.

* fix(terminal): preserve DB-backed terminal panel ids across layout restore

The serializer's normalizePanel rewrote every user-created terminal
panel id to `terminal-saved-N` and dropped environmentId/taskID from
params, so after a reload that panel couldn't be matched back to its
live PTY or its store record — the tab rendered with no badge and a
stale fallback title.

Treat `shell-<uuid>` panel ids the same way we already treat
`terminal-default`: preserve id and params on restore. Legacy
ephemeral `terminal-saved-*` ids still mint a fresh PTY on restore.
Also force tabComponent=terminalTab and title="Terminal" for any
restored terminal panel so layouts persisted before the badge UX
land on the new presentation.

* feat(terminal): destroy button on reopen-menu rows for permanent delete

Destroy used to live only on the tab's right-click menu — useless once
the tab was already closed. Each ordinary terminal row in the dockview
"+" → Terminals submenu now ends with an × button that confirms-then
calls destroyUserShell, killing the PTY and dropping the DB row so the
terminal does not reappear after reload.

Pairs with the previous close-to-park change: closing the tab parks
(soft, resumable), the × button on the menu row destroys (hard,
permanent).

* fix(terminal): reopen-menu focuses existing tab, drops parked pill, says Terminate

Three small fixes to the dockview "+" → Terminals submenu:

1. Clicking a row whose terminal is already mounted now FOCUSES the
   existing panel instead of duplicating it. The default-migrated
   panel keeps its registry id `terminal-default` even after the
   migration to a `shell-<uuid>` PTY, so a direct getPanel(uuid) miss
   would fall through to addTerminalPanel and create a second tab for
   the same PTY. Fall back to scanning `params.terminalId` so the
   lookup catches that case.

2. Drop the "parked" pill from the row — parking is now an internal
   detail (close = park) that the user doesn't need to read off the
   menu. Clicking the row brings the terminal back into view either
   way, so distinguishing it visually is noise.

3. Rename the row × tooltip + confirm copy from "Destroy" / "Permanently
   delete" to "Terminate" to match the new tab-context-menu label.

Spec: add a test that asserts no duplicate tab when reopening an
already-open terminal, and drop the parked-pill assertion from the
existing close+reload test.

* feat(terminal): empty-group watermark uses the rich + menu

When a user splits a group (split-right / split-down) the new half is
empty and dockview renders the watermark. Before this, the watermark
showed a hard-coded Agent/Plan/Terminal/Browser row and clicking
"Terminal" called createUserShell without a taskId — so it spawned a
legacy passthrough shell that never appeared in the user-shell list,
and clicking "Agent" only ever focused the singleton chat panel
(invisible if the task had multiple sessions).

The watermark now renders the same AddPanelMenuItems content the
header "+" uses, so the user gets:
- The Agents list (existing sessions, greyed when already open)
- The Terminals list (existing terminals, greyed when already open)
- The Browser/Plan/VS Code/Changes/Files/PR options

…served behind a single "Add panel" dropdown trigger centered on the
empty group.

* feat(terminal): inline rename on the tab; drop Park, rename Destroy → Terminate

The tab title is now editable in place — picking Rename from the
right-click context menu swaps the title for an input. Enter commits,
Escape / blur-with-no-change cancels, and the new name is pushed
through renameUserShell + the user-shell store so the API and badge
list stay in sync. Replaces the previous window.prompt which felt
out of place in the dockview chrome.

While here:
- Drop the "Park (hide, keep PTY)" context-menu item. Tab close
  already parks ordinary terminals, so the explicit Park action was
  redundant and broke the "one obvious affordance per outcome" rule.
- Rename "Destroy" → "Terminate" in the context menu. Matches the
  reopen-menu × tooltip and reads more like a system action than a
  destructive UI primitive.

Spec adds an inline-rename test asserting the input appears, accepts
typed text, and commits the new title to the tab.

* fix(terminal): right-click Terminate closes the tab; drop displayName DOM warning

Two unrelated fixes both landing in terminal-tab.tsx:

- Terminate used to fire the WS destroy and update the store, but left
  the dockview panel mounted with a dead PTY underneath. Now it
  optimistically drops the shell row from the store, closes the panel
  via api.close(), then sends the destroy — same effect as the X close
  but routed to the hard-destroy path (the onDidRemovePanel cleanup
  sees no shell entry and skips its park branch).

- TerminalTabBody typed `displayName` as a prop but never destructured
  it, so {...props} spread it into DockviewDefaultTab and on into a DOM
  div, triggering "React does not recognize the `displayName` prop on
  a DOM element". Drop it from the spread.

* feat(terminal): polish + menu — badge-style indices, flush-left New rows, terminate closes panel

Polish pass on the dockview "+" → Agents / Terminals submenus:

- Replace the plain `#N` text with the same pill-style badge the tabs
  use (small bg, rounded, 11px). Agents and terminals both pick this
  up — so the menu row reads "[N] label" matching the tab style.
- Drop the empty index-column placeholder span on the "New X" rows so
  the icon + label sit flush-left under the section header instead of
  awkwardly indented.
- Strip the backend "Terminal {seq}" suffix from row labels — the
  badge already carries the number, so showing "Terminal 1" next to
  the "1" pill duplicated it. Custom-renamed terminals still show
  their name.
- The row × button now also closes the dockview panel if the terminal
  is currently open, mirroring the right-click → Terminate flow.

Spec: switch the row-by-seq lookups from `hasText: "#N"` (now stale
since the `#` prefix is gone) to a `has:` filter against the new
`reopen-terminal-seq-N` badge testid, and add a regression test for
right-click → Terminate closing the tab and removing the row in one
gesture.

* fix: address terminal review feedback

* fix: resolve terminal review suggestions

* fix: catch terminal close stop failures

* fix: harden terminal terminate failures

* fix: use pinned pnpm docker arg

* fix: satisfy backend lint after main merge

* fix: stabilize e2e after layout merge
2026-05-24 12:59:30 +01:00
João Salavisa 68aeefa296 feat(gitlab): add GitLab integration with MR / discussions support (#861)
* feat(gitlab): add GitLab integration with MR / discussions support

Adds a GitLab integration parallel to the GitHub one: PAT and glab CLI auth,
self-managed host configuration, MR feedback (approvals + discussions +
pipelines), and discussion reply / resolve so agents can address review
comments. The pr skill detects the host from git remote and creates a real
GitLab merge request via glab or REST.

Closes #820

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(gitlab): address review feedback and tighten lint surface

- Add service_test.go covering ConfigureToken / ClearToken / ConfigureHost.
- Drop speculative MRWatch / TaskMR / ReviewWatch / IssueWatch / preset
  scaffolding that had no migrations or handlers behind it.
- Consolidate /approvals into one round-trip via fetchApprovals.
- Use http.DefaultClient in CheckHost (context already carries the deadline).
- Rename misleading id → configured in ConfigureToken.
- Introduce mrStateOpen constant so the lint goconst rule passes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): address PR review feedback (CodeQL SSRF, races, atomicity)

- connectivity: parse host with url.Parse, validate http/https scheme,
  build probe URL via &url.URL{} so user-controlled host can't smuggle
  into the request — clears the CodeQL go/request-forgery alert.
- pat_client: guard cached username with sync.RWMutex; IsAuthenticated
  now propagates non-401/403 errors instead of masking transport
  failures; GetMRStatus skips pipelines query when HeadSHA / HeadBranch
  are both empty; parseNextLink drops cross-host links instead of
  returning bare absolute URLs that get() would double-prefix.
- service: findTokenSecret returns (bool, string, error) and all
  callers propagate the secrets.List error so a backend outage isn't
  mistaken for "token absent"; ConfigureHost persists to hostStore
  before mutating in-memory host + client + authMethod under one lock.
- repoclone: SSH clone URL falls back to ssh:// form when the host has
  a port (scp-style git@host:path can't carry one).
- gitlab/client_helpers: namespace fallback uses LastIndex("/") so
  subgroup paths (acme/team/squad/repo) are preserved.
- pr skill / plan doc: drop hardcoded --target-branch main, derive host
  from git remote instead of $CI_SERVER_URL, build curl payload with
  jq -n; fix /pipelines/:id/jobs → :pipeline_id typo.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): preserve host base path in CheckHost; broaden validation; test

- connectivity: extract validateHost so the parse / scheme / hostname /
  userinfo / opaque-URL checks each have a single home. Preserve the
  configured base path (TrimRight slash) so a host like
  https://gitlab.acme.corp/gitlab probes /gitlab/api/v4/version instead
  of dropping the prefix.
- connectivity_test: cover validateHost (default, https, http, trailing
  slash, subpath, missing scheme, ftp, empty host, userinfo) and
  CheckHost end-to-end (version endpoint, base-path preservation,
  scheme rejection, unreachable host).
- pr skill: drop the broken `glab repo view --json defaultBranch`
  branch — glab doesn't accept --json, so the lookup silently fell
  back to "main" every time. Fetch default_branch via the GitLab
  REST API directly using the PAT we already have.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): override filter defaults, refresh auth uncached, mock pipelines

- appendFilter: Del before re-Add so user-supplied filter keys actually
  override caller defaults (e.g. state=closed swaps the seeded state=opened
  instead of appending a second value GitLab silently ignored).
- IsAuthenticated: probe /user directly instead of routing through the
  username cache; a token revoked upstream now surfaces as not-connected
  immediately. Cache is opportunistically refreshed on success.
- MockClient.GetMRFeedback: include pipeline state in HasIssues, matching
  the real PATClient behavior so test flows can't miss a broken MR.
- pr skill: document `glab mr note create --reply <id>` for replies (bare
  `glab mr note` opens a new thread); fix host-extraction block to handle
  ssh://host:2222/team/repo.git without leaking the port into PROJECT.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): guard mock pipelines on empty MR head; preserve HTTPS port in pr skill

- MockClient.GetMRFeedback now mirrors PATClient: skip the pipelines
  fetch when HeadSHA and HeadBranch are both empty. The mock'\''s
  ListPipelines ignores its branch argument and returns every pipeline
  seeded under the project, so without this guard a brand-new MR would
  inherit a sibling MR'\''s failing pipeline and flip HasIssues to true.
  Tests cover both the empty-head and head-present cases.
- pr skill: derive HOST scheme-aware so https://host:8443 keeps the port
  (HTTPS API endpoint), ssh://host:2222 strips it (different transport),
  and scp-style git@host stays portless. Avoids silently re-routing
  self-managed API calls to the default 443.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): export SeedPipelines; mock GetMRStatus parity; drain bodies; test cache hit

- MockClient: add exported SeedPipelines(project, iid, []) alongside the
  other Seed* methods; mirror PATClient.GetMRStatus by populating
  PipelineState / jobs counts via summarizePipelines, guarded on a
  non-empty head ref. Brings mock parity with the real client so any
  future test seeding pipelines sees the same MRStatus shape.
- PATClient HTTP plumbing: drain resp.Body via io.Copy(io.Discard, ...)
  when result == nil in both getWithTotal and doWrite, so HTTP/1.1 can
  reuse the connection instead of opening a new TCP socket per call.
- TestPATClient_GetAuthenticatedUser: assert calls == 1 after the second
  GetAuthenticatedUser hit so the cache contract is actually verified
  (a non-caching implementation would have passed the prior version).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): surface connection errors, align MR pipeline guards, fix mock seed key

- service.GetStatus now captures the IsAuthenticated error into a new
  Status.ConnectionError field (empty on healthy / 401-403, populated on
  network / 5xx / parse failures). Frontend GitLabStatus + settings page
  render a distinct "Unreachable" badge + alert so users don't delete a
  still-valid token during a transient GitLab outage.
- PATClient.GetMRFeedback now guards on HeadSHA || HeadBranch, matching
  GetMRStatus and MockClient.GetMRFeedback (which had been updated in an
  earlier round). The three call sites were inconsistent — a mock test
  with HeadBranch-but-no-SHA would pass while the real client silently
  dropped pipelines.
- MockClient.pipelines is now keyed by project alone (was
  map[mockMRKey][]Pipeline). SeedPipelines takes (project, []) so
  successive seeds for the same project deterministically overwrite,
  instead of leaving multiple entries that ListPipelines would resolve
  in Go's unspecified map-iteration order.
- Tests: TestService_GetStatus_{PopulatesConnectionErrorOn5xx,
  ClearsConnectionErrorOn401} cover the new error surface;
  TestMockClient_SeedPipelines_OverwritesByProject locks the key change.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): tighten validateHost; init Status scopes; close token-host race

- validateHost: drop the parsed.Opaque != "" branch — Go only sets
  Opaque for opaque URIs, which have an empty Host the prior check
  already rejects. Narrow the userinfo error to mention the actual
  user:password@host shape so the message matches what users see.
- service.GetStatus: initialize RequiredScopes: []string{} on the
  nil-client defensive branch so the JSON payload keeps the
  always-an-array contract declared on the TypeScript side. The branch
  is effectively unreachable (every Provide path returns at least a
  NoopClient) but the empty-slice fallback costs nothing.
- service.ConfigureToken: build the installed client inside the write
  lock using the up-to-date s.host instead of the pre-probe snapshot.
  A concurrent ConfigureHost between RUnlock and Lock used to leave
  s.client pointing at the prior host while s.host advertised the new
  one — every subsequent API call would silently target the wrong
  instance until the next reconfigure.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): drop MR-commit stats fields; rename AuthorName; log post-lock host

- MRCommitInfo: drop Additions / Deletions / FilesChanged. GitLab's
  /merge_requests/:iid/commits endpoint doesn't return a stats object,
  so those fields were always 0 — better to omit them than feed callers
  silently-wrong numbers. Rename AuthorUsername to AuthorName since the
  API returns a display name, not a login handle. Doc-comment records
  the per-commit endpoint to use if a future revision wants real stats.
- ListMRCommits: drop the Stats anonymous struct from the JSON decode
  target now that the destination fields are gone.
- service.ConfigureToken: capture installedHost inside the write lock
  and log that value. The previous log used the pre-validation host
  snapshot, so a concurrent ConfigureHost between snapshot and lock
  would leave the log entry referring to a stale value while the
  client itself was correctly built against the new host.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): encode subgroup paths; sentinel-route errors; mock approval parity

- pat_client.SearchGroupProjects now encodes the group path through a new
  groupRef helper that %2F-substitutes slashes (mirrors projectRef). Subgroup
  paths like "acme/team" used to land at /groups/acme/team/projects, which
  GitLab routed to the parent group only and returned 404 for. Subgroups now
  work end-to-end.
- service.ErrInvalidToken sentinel + controller errors.Is routing: token
  validation failures now wrap a package-level sentinel and the HTTP layer
  switches on it via errors.Is, replacing the fragile strings.Contains
  prefix check that would silently fall through to 500 if the message ever
  changed. Coverage: TestService_ConfigureToken_WrapsErrInvalidToken.
- MockClient gains seedable approvals: SeedApprovals(project, iid, list,
  required) backs a dedicated approvals + requiredApprovals map.
  ListMRApprovals, GetMRFeedback, and GetMRStatus all consume them so
  ApprovalState / ApprovalCount / RequiredApprovals match what the real
  PATClient.GetMRStatus computes. Coverage:
  TestMockClient_GetMRStatus_UsesSeededApprovals.
- ClearToken: same host-snapshot race ConfigureToken was fixed for last
  round — NewClient now runs under the write lock against s.host rather
  than a pre-acquired snapshot.
- CheckHost: drain resp.Body before close so http.DefaultClient's keep-alive
  pool can reuse the connection for the next probe.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): full-path projectRef round-trip; unlock during glab probe

- splitFullReference now returns (namespace, fullPath) where fullPath is
  the namespace-qualified project path ("group/sub/project") instead of
  the last segment alone. Callers can pass MR.ProjectPath straight to
  projectRef for round-trip API calls (GetMR, GetMRFeedback, etc.) —
  matches GitLab's own path_with_namespace convention. Existing test
  cases updated.
- ClearToken: build the fallback client OUTSIDE the write lock so
  NewClient's glab subprocess (bounded by glabAuthTimeout = 10s)
  doesn't freeze every concurrent GetStatus / GetMRFeedback /
  Client() RLock reader for the duration. Brief WLock now only wraps
  the field swap. Tradeoff with the concurrent-ConfigureHost race is
  documented in-code: narrow stale-host window vs. 10s of blocked
  readers, and the next reconfigure resolves it.
- New regression test TestPATClient_SearchGroupProjects_EncodesSubgroupSlash
  asserts the request URL is /groups/acme%2Fteam/projects so a future
  refactor that swapped groupRef back to a bare url.PathEscape would
  fail visibly instead of silently 404ing subgroup lookups.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): equality-guard ClearToken's client swap against ConfigureHost race

ClearToken builds the fallback client outside the write lock to avoid
blocking RLock readers for up to 10s while glab auth-probes. The
swap-only critical section now compares s.host against the pre-probe
snapshot before assigning — if a concurrent ConfigureHost moved the
host underneath us, we leave its (newer, correctly-targeted) client
alone instead of overwriting with our stale-host build.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): add GitLab to the settings integrations sidebar

The /settings/integrations/gitlab page existed and the index card listed
GitLab alongside the other integrations, but the settings sidebar nav
(IntegrationsNavGroup) only listed GitHub / Jira / Linear / Slack. The
page was unreachable through the standard sidebar.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(gitlab): task-MR topbar surface + DB-backed task↔MR store

Phase 1 of the GitLab UI build-out: brings the MR side of the task topbar
to parity with the existing GitHub PR button.

Backend
- gitlab_task_mrs table + Store wiring (UpsertTaskMR,
  ListTaskMRsByTask, ListTaskMRsByWorkspaceID, DeleteTaskMR), uniqued
  on (task_id, repository_id, project_path, mr_iid) for multi-repo.
- service.SyncTaskMR folds a live GetMRStatus probe into an upsert;
  ListTaskMRsByTask / ListTaskMRsByWorkspace expose the rows.
- Three HTTP endpoints: GET /workspaces/:id/task-mrs, GET
  /tasks/:taskID/mrs, POST /tasks/:taskID/mrs/sync.
- initGitLabService now takes a *db.Pool and constructs gitlab.Store.
  Failures non-fatal: integration keeps working without the table.

Frontend
- TaskMR type + listWorkspaceTaskMRs / listTaskMRs / syncTaskMR API.
- lib/state/slices/gitlab slice (taskMRs.byTaskId) wired through
  default-state, store.ts AppState, and slices/index exports.
- hooks/domains/gitlab/use-task-mr.ts: useWorkspaceMRs (fetch-on-
  workspace-switch) and useTaskMRs (per-task selector).
- components/gitlab/mr-topbar-button.tsx — single/multi MR variants,
  status icons mirroring pr-task-icon priority order.
- task-top-bar.tsx renders PRTopbarButton and MRTopbarButton side-by-
  side; each returns null when empty, so the union handles GitHub-only,
  GitLab-only, and multi-repo tasks without an explicit switch.
- kanban-board.tsx hydrates useWorkspaceMRs alongside useWorkspacePRs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(gitlab): add /gitlab page for browsing user MRs and issues

Adds the GitLab counterpart to /github so users can browse their own
merge requests and issues from inside kandev, parallel to the existing
GitHub "My GitHub" page.

Backend
- /api/v1/gitlab/user/mrs and /user/issues — paginated wrappers around
  the existing SearchMRsPaged / ListIssuesPaged client methods.
  paginationFromQuery clamps page/per_page the same way as the client.

Frontend
- /gitlab SSR page + client with MR/Issue tabs, scope filters
  (assigned / created / review-requested), and a free-text search box
  that falls back to raw GitLab query-string for power users.
- searchUserMRs / searchUserIssues API helpers + MR / Issue / *SearchPage
  types in lib/types/gitlab.
- useGitLabAvailable hook (probes /status + refreshes on window focus)
  feeds the integrations menu so the GitLab link only shows when a
  token is configured or auth is green.

Tests
- task-top-bar.test mocks the new MRTopbarButton so renders no longer
  pick up useAppStore without a StateProvider.
- integrations-menu.test wires the new useGitLabAvailable mock and
  gitlabReady prop into mockAvailability / getAvailableIntegrationLinks
  fixtures.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): stable empty array in useTaskMRs to avoid infinite re-render

useTaskMRs returned `state.taskMRs.byTaskId[taskId] ?? []` — that fresh
literal made the zustand selector produce a new reference on every
render when the task had no MRs, triggering an infinite re-render loop
in MRTopbarButton that crashed the task page with a Next.js client-side
exception.

The page never mounted session-chat, so Docker E2E tests that drive
`/t/:id` (slow-bootstrap progress, external-stop resume, environment
reset) all timed out waiting for the chat panel.

Mirror the GitHub side's `EMPTY_PRS` pattern: hoist a module-level
`EMPTY_MRS = []` and return it for the empty case.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): address PR review — cache header, in-flight cancel, tests

- Top-level `cache: "no-store"` in 5 sites (use-task-mr.ts, gitlab-api.ts,
  gitlab-page-client.tsx). The earlier `init: { cache: "no-store" }`
  placement was silently overwritten by fetchJson with undefined, so probes
  hit the browser cache instead.
- useWorkspaceMRs now invalidates in-flight responses and calls
  resetTaskMRs when the workspace becomes null, so the previous workspace's
  MRs don't linger after sign-out / workspace switch.
- Drop unpopulated UnresolvedThreads/DiscussionCount from TaskMR (model,
  schema, TS type). SyncTaskMR's source MRStatus never populated them and
  no surface reads them; the dropped columns are skipped via an explicit
  projection in store.go so existing dev DBs keep binding.
- Extract MRList/IssueList inline fetches in /gitlab into useGitLabUserMRs
  / useGitLabUserIssues — matches CLAUDE.md "never fetch in components".
- Tests for store (UpsertTaskMR, composite key, workspace-JOIN isolation,
  ordering, Delete), service (SyncTaskMR mock round-trip + field mapping +
  store-unset error, ListTaskMRsByWorkspace JOIN isolation, ListTaskMRsByTask),
  pat_client (ListIssuesPaged X-Total), gitlab-api (5 new fns), gitlab-slice
  (setTaskMR composite key), and the use-task-mr / use-user-search hooks.
- pr SKILL.md: skip note for steps 5–6 on GitLab remotes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): only wrap 401/403 probe errors as ErrInvalidToken

Network failures, 5xx, and DNS errors during `ConfigureToken` previously
surfaced to the user as HTTP 400 "invalid token: …" — during a GitLab
outage a user with a valid token might delete it assuming it was rejected.
Now only `*APIError` with 401/403 is mapped to `ErrInvalidToken`; other
errors propagate unwrapped so the controller routes them to "GitLab
unreachable" instead.

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>
2026-05-23 23:17:16 +01:00