Commit Graph

1154 Commits

Author SHA1 Message Date
Carlos Florêncio f4be0d279c fix: dockview, sprite, auth, and CLI db backup improvements (#1075) 2026-05-28 16:23:17 +01:00
Carlos Florêncio 905b9f9727 fix: improve UX for subtasks with repo setup scripts (#1105) 2026-05-28 16:07:51 +01:00
Carlos Florêncio d97ec5b8fd ci: skip Playwright CDN download for e2e-containers job (#1123) 2026-05-28 15:35:13 +01:00
Carlos Florêncio 15721860e9 ci: migrate backend/frontend/e2e workflows to kandev-ci base image (#1115) 2026-05-28 13:11:33 +01:00
Carlos Florêncio 3b1b3473f1 fix(web): avoid trailing-context crash in multi-file diff panel (#1097) 2026-05-28 10:12:40 +01:00
Carlos Florêncio 191df54f38 fix(backend): support model switching for passthrough sessions (#1100) 2026-05-27 23:34:11 +01:00
Carlos Florêncio a340f528e4 fix(backend): use official cursor CLI install command in InstallScript() (#1099) 2026-05-27 23:33:27 +01:00
Carlos Florêncio 0c2df491cc ci: add kandev-ci base Docker image and publish workflow (#1102) 2026-05-27 20:52:51 +01:00
João Salavisa 0822d41372 fix(backend): drain orphaned queued messages on agent boot ready (#1096)
* fix(backend): drain orphaned queued messages on agent boot ready

When autoStartStepPrompt hits a transient PromptTask error (e.g. "agent
stream disconnected" mid-prompt), it records the auto-start user message
and then queues the same prompt for retry. The drain only fires from
handleAgentReady (turn-end) — but the failed prompt never reached the
agent, so no agent.ready ever arrives for it. After the user resumes the
session, handleAgentBootReady only flipped state and returned, leaving
the workflow auto-start prompt stuck on the queue forever (the "1 queued"
that wouldn't go away after resume).

handleAgentBootReady now drains via drainQueuedMessageAfterTransition
after the WAITING_FOR_INPUT flip — also on the early-return path where
state was already WAITING (boot signal raced persistResumeState).
Terminal sessions short-circuit before the drain so cancelled/completed
sessions don't revive their queued prompts.

Tests: TestAutoStartTransientError_BootReadyDrainsOrphanedQueue
reproduces the production scenario end-to-end (transient PromptAgent
failure → record + queue → boot_ready → drained). Plus
TestHandleAgentBootReady_DrainsOrphanedQueuedMessage covers both
STARTING→WAITING and the persistResumeState-race path, and
TestHandleAgentBootReady_DoesNotDrainForTerminalSession guards the
terminal-session short-circuit.

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

* test(backend): wait for drain goroutine and verify prompt dispatch in repro

Greptile flagged that the queue-empty assertion in
TestAutoStartTransientError_BootReadyDrainsOrphanedQueue raced the
drain's executeQueuedMessage goroutine: the goroutine would re-enter
the same isTransientPromptError path and re-queue the message
immediately, but the assertion would usually win on timing.

Clear agentMgr.promptErr before Phase 2 (simulating the agent
recovering), then poll capturedPrompts until the drained prompt
actually reaches PromptAgent. This turns a timing-fragile assertion
into a deterministic end-to-end check: drain → executeQueuedMessage
→ PromptTask → PromptAgent → queue empty.

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

* test(backend): wire executor in boot-ready drain test to fix nil-deref under -race

Claude and cubic flagged that TestHandleAgentBootReady_DrainsOrphanedQueuedMessage
constructed Service without an executor field. The drainQueuedMessageAfterTransition
goroutine spawned by handleAgentBootReady would nil-deref s.executor via
PromptTask -> ensureSessionRunning -> s.executor.GetExecutionBySession.
Passed today by luck of scheduling but would panic under -race.

Wire a real executor (built from the same mockAgentManager and repo as the
other tests) and seed an executors_running row so the drained PromptTask
lands on a working code path instead of crashing. Verified passes with
`go test -race -count=3`.

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

* test(backend): replace time.Sleep polling with promptDone channel sync in repro

Claude flagged that the polling loops in
TestAutoStartTransientError_BootReadyDrainsOrphanedQueue used time.Sleep
where mockAgentManager.promptDone (closes on first PromptAgent call) gives
a deterministic sync point per AGENTS.md.

- Phase 1: wait on firstPromptCalled, then a 500ms / 1ms tight poll covers
  the synchronous PromptAgent-returns → queue-row-commits gap.
- Phase 2: swap in a fresh secondPromptCalled channel (the mock's
  `first := len(capturedPrompts) == 0` guard requires resetting captured*
  slices so the close re-fires for the drain's second call), then wait on
  that signal before the queue-empty assertion.

Verified with `go test -race -count=5` — all pass, no goroutine leaks.

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-27 15:20:17 +01:00
João Salavisa 7be0db04d8 fix(backend): restrict branch/dir name sanitizers to ASCII alphanumerics (#1095)
* fix(backend): strip non-ASCII chars from branch/worktree names

Non-ASCII titles (CJK, Cyrillic, Arabic, emoji) flowed verbatim into git
branch names and worktree directory names because the sanitizers used
unicode.IsLetter/IsDigit, which accept any Unicode letter or digit. The
resulting names broke many downstream tools and left worktrees
effectively inaccessible.

Restrict SanitizeForBranch and SanitizeRepoDirName to ASCII
alphanumerics. Non-ASCII runes now route through the existing
hyphen-replace + collapse + trim pipeline, and the existing fallback
chain (sanitized title -> sanitized task ID -> "task") handles
titles that become empty after stripping. The "Issue #N:" / "PR #N:"
prefix already added by the GitHub ingestion path means a non-ASCII
issue title still produces a recognizable name like "issue-123".

Closes #1081

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

* refactor(worktree): fix comment accuracy and harden test assertion

- Remove "emoji" from isASCIIAlphaNum doc — emoji are not Unicode
  letters (unicode.IsLetter returns false), so the prior code never
  admitted bare emoji. Correct examples to CJK, Cyrillic, Arabic.
- Replace hard-coded len(dirName) != 8 with strings.Contains check
  so the assertion stays correct if suffix length ever changes.

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

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 13:36:00 +01:00
José Almeida 23dab31a98 fix(backend): honor base_branch for same-repo subtasks via MCP (#1093)
* fix(backend): forward base_branch override for same-repo subtasks via MCP

The create_task_kandev MCP handler dropped base_branch silently unless
the caller also passed a repository identifier. Same-repo subtasks then
inherited the parent's repos verbatim, so "branch off feature/X" calls
landed on the parent's branch instead.

Forward base_branch at the top level of the WS payload and apply it as
an override on the resolved repo list when no per-repo entries were
supplied; explicit per-repo BaseBranch wins as before.

* docs(backend): correct BaseBranch field comment to match actual fallback semantics

The struct doc on `req.BaseBranch` claimed it won over explicit per-repo
entries, but the override only fires when `len(req.Repositories) == 0`.
Reword as a fallback applied to inherited/resolved repos when no
per-repo list is supplied; explicit per-repo BaseBranch stays
authoritative when set. Flagged by CodeRabbit and Greptile.

* refactor(backend): forward top-level base_branch only when no per-repo entries

When the MCP caller supplies a repo identifier, the per-repo base_branch
is already authoritative on the backend side, so emitting a top-level
base_branch in the same payload was dead weight that the backend's
override gate explicitly ignored. Move the top-level forward into the
else of hasRepo so the two paths are mutually exclusive and the wire
contract reads as "top-level base_branch means inherit-with-override".
Flagged by the Claude review bot.
2026-05-26 19:21:06 +01:00
José Almeida ec8039ca71 fix(web): always allow expanding tool execute to reveal full command (#1086)
* fix(web): always allow expanding tool execute to reveal full command

* fix(web): keep tool execute tooltip trigger keyboard-focusable
2026-05-26 18:21:47 +01:00
João Salavisa 991a6315c3 fix(backend): force fresh git status on session subscribe (#1092)
* fix(backend): force fresh git status on session subscribe

Every new WS subscriber to a session now triggers a fresh `git status
--porcelain` in agentctl instead of replaying the cached snapshot.
This makes the cache an optimization for already-subscribed observers
only — a fresh observer revalidates ground truth on every connect, so
a stale cache (e.g. left over when the poll loop missed a HEAD change
in paused mode or dropped a tick) self-heals on the next subscribe.

- `?fresh=true` on `/api/v1/git/status/multi` propagates through to
  `WorkspaceTracker.GetGitStatus(ctx, true)`.
- New `GetGitStatusMultiFresh` client method; `tryGetLiveGitStatus`
  (the session-subscribe hydration path) uses it.
- Regression test reproduces the bug: dirty file → cache primed →
  commit without refresh → cached read still shows the file as
  modified; fresh=true returns the clean truth.

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

* fix: address PR review feedback

- Reframe regression-test precondition comment so it reads as scenario
  setup (Claude review).
- Document GetGitStatusMultiFresh's read-only-vs-cache contract in its
  godoc so a future reader doesn't try to write the result back into
  the tracker's currentStatus (Claude review).
- Trim multi-line block comment in helpers.go to a single line per the
  backend AGENTS.md convention (Claude review).
- Parallelize handleGitStatusMulti's per-repo fan-out via sync.WaitGroup
  to keep the fresh-path wall-clock close to the slowest single repo
  regardless of repo count, so multi-repo workspaces don't blow past
  the 2s subscribe-path timeout (Greptile review). Pre-sized result
  slice means each goroutine writes its own slot — no shared-slice
  contention. collectStatusForRepo now takes context.Context directly
  instead of *gin.Context.
- Add a third assertion in the regression test that locks in the
  documented cache-unchanged contract — after fresh=true, a subsequent
  GetGitStatus(ctx, false) call must still return the stale cached
  value, so any future change that silently writes through fresh would
  fail the test (Greptile review).

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

* fix: address round 2 review feedback

- Trim the parallelization rationale in handleGitStatusMulti to a
  single line per AGENTS.md convention (Claude review).
- Drop unused GetGitStatusMulti client method (cached variant) and its
  internal getGitStatusMulti helper — only GetGitStatusMultiFresh has
  a caller after this PR, and AGENTS.md says to delete unused code
  outright (Claude review).

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-26 17:44:44 +01:00
João Salavisa d7d74a8bc5 chore(office): delete duplicated scheduler/channels/configloader files (#1084)
IdleTimeoutManager, the BuildPrompt family, ChannelRelay, and
configloader.Watcher were forked into internal/office/service/ and
internal/orchestrator/watcher/ during the scheduler/→service/ refactor
but never removed from their original homes. All four types (and their
two same-package self-tests) had zero importers across the repo.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-26 17:03:11 +01:00
João Salavisa 6ee7369efc fix(backend): keep cancelled office turns promptable instead of parking IDLE (#1088)
* fix(backend): keep cancelled office turns promptable instead of parking IDLE

A user-initiated turn cancel on an office task was racing the
agent.complete stream handler. The complete handler unconditionally
flipped the session to IDLE (the "parked between scheduler runs"
state), overwriting Service.CancelAgent's WAITING_FOR_INPUT write
that arrived a moment earlier. The next prompt was then rejected by
checkSessionPromptable with "session is in IDLE state".

Skip the office IDLE branch when the complete event carries
stop_reason="cancelled". The cancel handler already drives state
reconciliation for user cancels; falling through to the kanban
WAITING_FOR_INPUT path leaves the session promptable.

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

* refactor(backend): shorten extractStopReason and stopReasonCancelled comments

Trim multi-line docstrings that violated CLAUDE.md's one-short-line rule
down to one or two lines, keeping only the non-obvious cross-file sync note.

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

* refactor(backend): compress remaining multi-line comment blocks to one line

Second pass of comment trimming per CLAUDE.md convention — the
handleCompleteStreamEvent stop_reason context block and the
handleOfficeTurnComplete stopReason paragraph were still too long.

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

* refactor(backend): collapse remaining multi-line comments to one-liners

Address Claude bot review threads on PR #1088: the production helper
docs (extractStopReason, stopReasonCancelled, handleOfficeTurnComplete)
and the new test functions still carried multi-line comment blocks,
which violate CLAUDE.md's "one short line max" rule.

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-26 16:33:12 +01:00
João Salavisa dcab8aaa05 fix(backend): drain stuck auto-start prompts after step transitions (#1087)
* fix(backend): drain stuck auto-start prompts after step transitions

Adds flipStaleRunningToWaiting, a helper that detects when a session's
in-memory state reports RUNNING/STARTING but the orchestrator's
authoritative activeTurns map has no entry, and pre-flips the session
to WAITING_FOR_INPUT. processOnEnter now calls this before reaching
queueAutoStartPromptIfRunning, so the auto-start prompt is sent directly
via PromptTask instead of being queued against a session whose agent.ready
will never fire.

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

* docs(backend): clarify reset guard scope and add STARTING-state test

- Expand isSessionResetInProgress comment to note it guards concurrent
  goroutines only; sequential reset_agent_context OnEnter actions run
  after flipStaleRunningToWaiting returns (markIdleAfterReset no-ops
  if state is already WAITING_FOR_INPUT).
- Add call-site comment explaining why the pre-flip must happen before
  the len(step.Events.OnEnter)==0 early-return check.
- Add test: flipStaleRunningToWaiting flips STARTING session with no
  active turn (addresses reviewer gap noted in code review).

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-26 16:02:15 +01:00
João Salavisa cf76a27488 feat(web): normalize /gitlab page to match /github layout (#1082)
* feat(web): normalize /gitlab page to match /github layout

Adds a presets sidebar (MR/Issue toggle, Inbox/Created groups, Saved
section), a top toolbar with project filter and custom-query input,
paginated MR/Issue lists, and a save-preset dialog backed by a
localStorage store at kandev:gitlab-presets:v1.

Replaces the bespoke tabbed layout and supersedes
hooks/domains/gitlab/use-user-search with the pagination-aware
useGitLabSearch under components/gitlab/my-gitlab/. Project filtering is
applied client-side since GitLab's global MR/issue endpoints have no
path_with_namespace qualifier. No backend changes — the controller
already accepts filter / custom_query / page / per_page.

* fix(web): address /gitlab review feedback

- Merge duplicate cn/formatRelativeTime imports in list-toolbar.
- Drop the generic T from useGitLabSearch — it always resolved to MR | Issue,
  so the as-unknown-as double-cast was just hiding that. Now returns
  Array<MR | Issue> directly and exposes rawTotal alongside total.
- When projectFilter is active, total reflects the client-side filtered
  count instead of the server's unfiltered total so the toolbar badge and
  pagination don't claim "47 results" while only 3 rows render.
- Save flow uses committedQuery, not the draft customQuery, so a preset
  saved without pressing Enter matches what's actually displayed.
- Wrap mobile sidebar handlers in useCallback to keep props stable.
- Drop the unused refresh callback in useGitLabStatusFetch (no caller).
- Add hook-level tests for useSavedPresets save/remove/sync; use
  resetKnownProjectsStore directly in the known-projects test.

* fix(web): address round-2 /gitlab review feedback

- useSavedPresets save/remove now read from localStorage on every call so a
  concurrent write from another tab can't be silently overwritten by a stale
  in-memory snapshot.
- Tighten persisted shape validation: customQuery, projectFilter, and
  createdAt must all be strings (plus 3 regression tests).
- ResultsPagination clamps page to [1, totalPages] before deriving start/end
  and prev/next state, so a stale out-of-range page doesn't render an
  invalid range like "101–30 of 30" after a refresh that shrinks results.
- PresetsSidebar: ignore keydown bubbling from the nested delete button so
  Enter/Space on delete doesn't also trigger row selection, and add an
  aria-label to the icon-only delete control.
- Revert the hook's filtered-total policy: useGitLabSearch always returns
  the raw server total now (so pagination can still navigate to later
  pages). The page client owns the toolbar's displayedCount, computing
  filtered.length only when a project filter is active.

* fix(web): drop dead gitlab preset re-exports, tighten save dialog deps

- Remove unused IconBug / IconPencil imports and the re-export from
  presets.ts — no consumer imports them from this module.
- save-preset-dialog: inline the trimmed check inside handleSubmit so
  canSubmit no longer needs to be in the deps array. ESLint exhaustive-
  deps forced the previous duplication; inlining removes it cleanly.

* fix(web): null-safe response unwrap in useGitLabSearch

If the API returns null, the cast `(response as {mrs: ...}).mrs` would
crash before the `?? []` fallback could run. Optional-chain the cast so a
null payload yields an empty list, matching the existing total_count guard.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-26 16:00:55 +01:00
João Salavisa 2cb3f4a384 chore: remove dead non-ACP provider client packages (#1083)
* chore: remove dead non-ACP provider client packages

Delete five Go packages under apps/backend/pkg/ that were unreachable
from any binary: amp, codex, claudecode, copilot, opencode. These were
the client libraries for legacy non-ACP agent implementations removed in
a5b54b53 — that commit deleted the callers but missed the client libraries.

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

* chore: drop orphaned copilot-sdk dep and stale architecture doc

go mod tidy removes github.com/github/copilot-sdk/go v0.1.18 and its
transitive dep github.com/google/jsonschema-go v0.4.2; both were only
imported by the deleted pkg/copilot/client.go.

Delete docs/agents/claude_code.md: it describes the pre-ACP streamjson
transport and pkg/claudecode/ package. Every source file it references
has been removed (pkg/claudecode/ in this PR; streamjson/ and
agents/claude_code.go in a5b54b53).

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-26 15:31:14 +01:00
João Salavisa dcfec0d23c refactor(backend): classify errors via sentinels instead of substring matches (#1057)
* refactor(backend): classify errors via sentinels instead of substring matches

Introduce package-local sentinel errors in the github, task repo, agent
lifecycle, and office/skills packages. Producers wrap with fmt.Errorf("%w: ...")
so callers can classify via errors.Is/errors.As instead of brittle
strings.Contains(err.Error(), ...) checks that break on library upgrades.

Sentinels added (or relocated to errors.go):
- github: ErrInvalidToken (new); ErrInvalidPRURL, ErrTaskNotFound, ErrSelfApprove
  moved from service.go.
- task/repository/sqlite: ErrTaskNotFound, ErrOfficeSessionRaceConflict.
- lifecycle: ErrAgentAlreadyRunning, ErrAgentReported.
- office/skills: ErrSkillNotFound, ErrSkillFileNotFound.

Consumers updated to errors.Is/errors.As across orchestrator, task/handlers,
github, and office/skills. AssociateExistingPRByURL switches %v -> %w so the
inner parsePRURL error stays in the chain. process_handlers now uses
errors.Is(err, syscall.ECONNREFUSED) and lifecycle.ErrNoExecutionForSession
plus a small isTimeoutError helper backed by errors.As.

A new taskDeleterAdapter in cmd/kandev/turn_adapters.go translates
taskrepo.ErrTaskNotFound to github.ErrTaskNotFound at the wiring boundary,
avoiding a layering violation between the github and task packages.

The one remaining substring check, in CreateTaskSession, is encapsulated
inside the repo and converts the SQLite UNIQUE-violation message into the
typed ErrOfficeSessionRaceConflict sentinel so callers never see the driver
string.

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

* test(backend): add TestErrorsAreClassifiable for refactored packages

Pin the new sentinel-based contract for each refactored package. Each test
exercises the producer paths and asserts errors.Is reaches the sentinel
through the wrap chain, and (where applicable) confirms untyped lookalike
strings no longer classify.

- github: isTaskNotFound, AssociateExistingPRByURL/ErrInvalidPRURL,
  ConfigureToken/ErrInvalidToken (using a noop secret manager).
- task/repository/sqlite: GetTask, DeleteTask, UpdateTaskState wrap
  ErrTaskNotFound.
- task/handlers: isNotFound + isAgentReportedError follow the typed chain.
- orchestrator: each isXError classifies exact + wrapped sentinels, rejects
  untyped lookalikes.
- office/skills: readUserHomeSkillInventoryFile wraps ErrSkillFileNotFound;
  ErrSkillNotFound survives fmt.Errorf("%w", ...).

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

* test(github): drop network-hitting subtest from errors_test

The "ConfigureToken wraps ErrInvalidToken when validation fails" subtest
constructed a real PATClient and called GetAuthenticatedUser, which makes
a live HTTP request to api.github.com. That's flaky in CI / offline dev
and violates the unit-test boundary (caught in review).

Replace with a sentinel-survives-wrap-pattern check that locks in the
exact %w/%w shape used by ConfigureToken, plus an assertion that the
inner cause stays reachable through errors.Is. The full ConfigureToken
flow stays covered by service_token_test.go and integration tests.

Remove the now-unused noopSecretManager stub type.

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

* fix(task): restore "timed out" UX for plain-fmt.Errorf timeout producers

The original createPromptErrorMessage rendered the friendly "Request timed
out…" hint via strings.Contains(err.Error(), "timeout"). The refactor
replaced it with errors.Is(context.DeadlineExceeded) + a net.Error
Timeout() helper — strictly typed. But several upstream producers along
the prompt path (service.WaitForSessionReady, agent-stream connect waits
in lifecycle/session.go and manager_interaction.go, agentctl health waits
in agentctl/client.go and launcher.go, the orchestrator's own
waitForSessionReady) return plain fmt.Errorf("timeout …") with no typed
Timeout() method, so the typed check missed them and the user saw the
generic "Failed to send message to agent" instead.

Add a substring fallback inside isTimeoutError as a UX safety net while
keeping the primary typed paths intact. Lock the contract with table
tests covering all three classes (net.Error timeout, plain string,
context.DeadlineExceeded) so any future trim of the fallback breaks
loudly. Migrating each upstream producer to a typed sentinel is tracked
as out-of-scope follow-up.

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

* test(backend): tighten classification tests to exercise typed-sentinel contracts

Addresses bot-review feedback on PR #1057:

- task/handlers/errors_test.go: cover all four not-found sentinels
  (taskrepo.ErrTaskNotFound, service.ErrDocumentNotFound,
  service.ErrTaskPlanNotFound, service.ErrRevisionNotFound) in
  TestErrorsAreClassifiable via a table-driven loop, instead of only
  one. Drop the spurious Deadline() *time.Time method on timeoutNetErr
  — it isn't part of net.Error and the existing `var _ net.Error =
  timeoutNetErr{}` line already pins the interface.

- orchestrator/scheduler/scheduler_test.go: testTaskRepository was
  still returning the local scheduler.ErrTaskNotFound, which doesn't
  satisfy the production processTasks check (now errors.Is on
  taskrepo.ErrTaskNotFound). Mirror the real sqlite repo's wrap so the
  mock and prod paths agree. The local scheduler.ErrTaskNotFound is
  truly dead after that, so drop it from scheduler.go.

- office/skills: the wrap-pattern subtest in errors_test.go was only
  testing fmt.Errorf, not production code. Move the contract assertion
  to service_test.go (external skills_test package) where it drives
  the real GetSkillFromConfig lookup path against an empty in-memory
  repository.

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

* refactor(backend): drop redundant context.DeadlineExceeded check and fix doc grammar

Addresses bot-review feedback on PR #1057:

- task/handlers/message_handlers.go::createPromptErrorMessage: the
  explicit errors.Is(promptErr, context.DeadlineExceeded) is redundant
  with isTimeoutError, which already matches via errors.As against
  Timeout() — context.DeadlineExceeded implements Timeout()==true.
  Inline comment documents the consolidation.

- github/errors.go: fix grammar in the ErrTaskNotFound doc comment
  ("is the sentinel cleanup paths check for to distinguish" →
  "is the sentinel that cleanup paths check to distinguish").

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-26 13:07:46 +01:00
José Almeida 823117ba48 fix: wire MCP config into CLI passthrough (#1078)
* fix: wire MCP config into CLI passthrough

* fix: address passthrough MCP review feedback

* fix: fail fast when passthrough MCP port is missing

* fix: track passthrough MCP config with nil metadata
2026-05-26 11:38:30 +01:00
José Almeida 8345480fe5 fix: group sidebar tasks by real state (#1077)
* fix: group sidebar tasks by real state

* test: cover sidebar state fallback

* fix: stabilize sidebar state groups
2026-05-26 11:37:43 +01:00
Carlos Florêncio 9f0b8f6bc6 fix(settings): remove duplicate breadcrumbs and system sidebar badges (#1080) 2026-05-26 10:27:07 +01:00
Luan Martins 1a467b969f fix(web): wire permission approval UI for Kandev MCP tools (#1037)
* fix(web): wire permission approval UI for Kandev MCP tools

KandevToolMessage adapter ignored the permissionMessage prop, so MCP tools
that block on a permission request rendered the result row but no Approve/
Deny buttons — users could not unblock the agent. Extract the shared
permission handlers into use-permission-handlers.ts and reuse them from
both ToolCallMessage and KandevToolMessage. KandevRow now also shows an
amber pending clock icon and hides the result-count summary while waiting
for approval so the row reads correctly before the result arrives.

Adds a mock-agent scenarioKandevMCPPermission emitting
mcp__kandev__list_workspaces_kandev plus a Playwright e2e and unit tests
covering the pending UI and the absence of "0 workspaces" while pending.

* fix(web): collapse tool + permission status into resolved Kandev row

After approve/reject the orchestrator stamps the decision onto the
permission_request message immediately, but the tool_call's own
meta.status stays "pending" until the next tool_call update lands.
KandevToolMessage previously passed meta.status straight to the renderer,
so the row kept the amber pending clock and the hidden-summary state for
the brief window between the two events. resolveKandevStatus now prefers
the permission decision once present, mapping approved -> complete and
rejected -> error.

Drops a redundant Playwright `.first()` after a toHaveCount(1) assertion
on the same locator. Adds unit coverage for the resolved-decision state.

* fix(web): keep Kandev tool status independent of permission decision

The previous fix collapsed an approved permission into tool status
"complete" and a rejected permission into "error". That was wrong on two
counts: an approved tool that's still running rendered as already done
(green check + visible result summary built from an empty payload), and
any later tool_call error was silently masked because the status had
already been forced to "complete".

Replace the status override with a separate display overlay. KandevRow
now reads a `KandevPermissionUIContext` ("pending" | "rejected" |
undefined) and uses it only to drive the waiting-on-user affordances —
amber clock, hidden summary — and a rejection mark that wins over the
tool's own success state. The renderer always receives the real
tool_call status, so a tool that's approved-but-pending still reads as
pending and a tool that errors after approval still renders the red X.

Adds explicit regression tests for the two race-window failure modes
plus the new rejected overlay.

* test(web): tolerate duplicate-render backend race in Kandev MCP e2e

CI shard 1 sometimes renders two approve buttons for the same Kandev MCP
permission because the orchestrator can create a second generic tool_call
message for the same tool_call_id alongside the kandev-routed one. Both
buttons resolve the same pending_id, so clicking the first unblocks the
agent either way.

The bug the test guards against is "no approve button at all" — the
strict toHaveCount(1) assertion was tying the test to that separate
backend issue. Relax to at-least-one and click the first.

* fix: persist Deny clicks as rejected, not approved

Backend RespondToPermission previously derived status purely from cancelled:
cancelled=true -> "rejected", otherwise "approved". Deny clicks sent
cancelled=false with a reject_* option_id, so they were recorded as
"approved". Add an explicit rejected flag from the WS request so the
backend can record "rejected" without taking the cancellation path (which
races against permission_cancelled -> "expired").

Also refactor permission-request-message.tsx to consume the shared
usePermissionResponseHandlers hook (the duplicated inline handler had the
same bug) and introduce a typed models.PermissionStatus enum on the
backend so status strings are not scattered literals.

* test(web): scope Kandev MCP permission e2e to the Kandev row

Previously the test clicked the first matching permission-approve button,
which could be a duplicate generic ToolCallMessage fallback rendered for
the same pending_id by a backend race -- a green test no longer proved the
custom Kandev approval UI rendered.

Add a `data-testid="kandev-tool-permission"` wrapper around the Kandev
action row and a `kandevPermissionApproveButtons` page-object locator that
scopes through it, then assert `toHaveCount(1)` so the test only passes
when the Kandev custom row actually mounts.

* chore(orchestrator): log rejected flag in RespondToPermission

Debug log was missing the new rejected param, making it impossible to
distinguish explicit Deny from dialog cancellation when triaging
permission-flow issues.
2026-05-26 00:22:45 +01:00
github-actions[bot] 97c5b9dc17 release: 0.52.0 v0.52.0 2026-05-25 21:27:20 +00:00
Daniel Brown c0eaafaf29 fix(mobile): isPassthroughMode falls back to TaskChatPanel when snapshot is missing (closes #1031) (#1034)
* fix(mobile): passthrough TUI rendering + touch-scroll

Two related mobile-UI fixes for cli_passthrough sessions, both
filed in #1031.

1. task-center-panel.tsx: align isPassthroughMode with the rest
   of the codebase by checking session.is_passthrough first. The
   memo previously only consulted agent_profile_snapshot.cli_passthrough,
   which can be undefined in the Redux store on re-mount (the snapshot
   isn't always present on the leaner session-list responses). When
   that happened on mobile, the chat panel rendered the persisted-
   messages TaskChatPanel fallback instead of the live PassthroughTerminal.
   Desktop was immune because dockview-desktop-layout.tsx already uses
   the session.is_passthrough field directly. is_passthrough is the
   source of truth used by manager_startup.go's StartAgentProcess
   routing — keeping the frontend consistent with that invariant.

2. passthrough-terminal.tsx: wire touch-drag scrolling on the xterm
   viewport. xterm.js handles mouse wheel natively but not touch
   gestures, so swiping inside the terminal on mobile bubbled up
   and scrolled the page instead of the terminal scrollback —
   effectively making everything that scrolled off-screen unreachable
   on mobile. The new hook attaches touchstart/touchmove/touchend
   handlers that map vertical drag delta to term.scrollLines(),
   gated on (pointer: coarse) so desktop xterm behaviour stays
   identical. Row-height comes from xterm's internal render dimensions
   with a measured fallback (xterm 5.x layout) and a 16px constant
   fallback if both fail.

Closes #1031

* fix(mobile): also fix useSessionLayoutState's isPassthroughMode + tighten touch-handling

Three follow-on fixes after Dan's mobile QA surfaced more cases:

1. apps/web/hooks/use-session-layout-state.ts — the mobile layout actually
   uses THIS hook's isPassthroughMode memo (not the one in
   task-center-panel.tsx that I previously fixed). It had the identical
   snapshot-only bug. Aligned with the same is_passthrough-first priority.

2. apps/web/components/task/passthrough-terminal.tsx — always preventDefault
   on touchmove (was only doing so when the row-delta calculation rounded
   to non-zero, so sub-row drags slipped through to parent scroll). Added
   touch-action: none + overscroll-behavior: contain inline on the terminal
   element so the browser never claims the gesture.

3. apps/web/app/globals.css — overscroll-behavior: none on body to block
   pull-to-refresh. iOS Safari ignores this in some configurations but
   blocking it where possible reduces the page-reload race that was
   triggering the stuck-on-loading-messages state.

* fix(mobile): trim PR to minimum required changes

After QA showed the user-visible mobile bug is fully addressed by the
useSessionLayoutState memo fix alone, revert the parallel changes to
the desktop hook (task-center-panel.tsx's useSessionApprove) and the
body-level overscroll-behavior — neither was required for the
reported bug, and Dan asked for the smallest possible diff.

Remaining changes:
- apps/web/hooks/use-session-layout-state.ts — actual mobile fix
- apps/web/components/task/passthrough-terminal.tsx — touch-scroll feature

* fix(mobile): tighten isPassthroughMode + drop terminal touch-scroll from this PR

Adversarial-review feedback applied:
- Change `is_passthrough === true` to `!== undefined` so an explicit
  server-side false isn't overridden by a stale snapshot.
- Comment now cites the specific WS handler quirk in
  ws/handlers/agent-session.ts where snapshot writes are truthy-guarded
  but is_passthrough writes are !== undefined-guarded — that's the
  concrete path where partial events land one without the other.

Dropped: the useMobileTouchScroll hook. Terminal scroll on mobile is a
separate feature that deserves its own discussion (xterm renders the
canvas above the scrollable viewport so native scroll doesn't reach the
viewport; the right fix likely lives in xterm itself or a small
event-redirect addon). Keeping this PR scoped to the rendering bug.

* fix(mobile): add minimal touch-scroll fallback for xterm viewport

xterm.js renders .xterm-screen (canvas) above .xterm-viewport, so iOS /
Android native scroll on the viewport never sees the touches and the
terminal is unscrollable on mobile.

useTouchScrollFallback wires touchstart/touchmove/touchend to
Terminal.scrollLines via an accumulated fractional-row delta. No
inertia — the proper fix is upstream in xterm-js. Gated on
(pointer: coarse) so desktop xterm behaviour is unchanged.

Sets touch-action: none + overscroll-behavior: contain inline on the
terminal element so the browser doesn't claim the gesture for
pull-to-refresh.

* fix(mobile): inertia decay on touch-scroll release for native-scroll feel

* fix(mobile): address adversarial review of touch-scroll hook

- Read xterm from ref inside each handler so renderer recreate doesn't
  strand the handlers on a stale Terminal instance (React refs are
  stable so dep array doesn't catch .current swaps).
- Drop the internal _core._renderService private-API path for row
  height in favor of public term.rows + measured element height. The
  internal path was API-unstable across xterm majors.
- Velocity window 80ms → 50ms so a direction reversal at the tail of
  the gesture is the release velocity, not averaged against the early
  motion.
- Reset pendingRows fractional accumulator on direction reversal — was
  causing perceptible stickiness when reversing from slow-up to fast-down.
- Style restoration now uses removeProperty when the inline style was
  never set, rather than leaking an empty string in its place.

* fix(mobile): revert touch-scroll hook from this PR — separate concern

After several iterations the touch-scroll fallback kept surfacing new
issues (iOS pull-to-refresh leaking through preventDefault, scroll
direction reversal edge cases) that suggest a more involved upstream
discussion is needed about whether to ship a workaround in
PassthroughTerminal at all vs fixing xterm.js's mobile story upstream.

Splitting that work out so this PR can land the rendering bug fix
cleanly. Will file a separate issue for the touch-scroll work with
the diagnosis + alternatives we explored.

* fix(mobile): honor is_passthrough when snapshot missing

---------

Co-authored-by: Carlos Florêncio <carlosmflorencio@gmail.com>
2026-05-25 22:09:17 +01:00
Carlos Florêncio 0a3ffadad1 refactor(orchestrator): address watcher dispatch review feedback (#1074) 2026-05-25 21:41:33 +01:00
Nicolas Lenepveu 9a462e52c8 refactor(orchestrator): extract WatcherDispatchCoordinator + WatcherSource (#1070) 2026-05-25 20:13:23 +01:00
Carlos Florêncio f1dbad1dbd feat(cli-mode): auto-inject task prompt + dynamic submit sequence + passthrough UX fixes (#923) 2026-05-25 19:14:36 +01:00
Carlos Florêncio 8a7b7a0b60 feat(agentctl): azure Repos PR follow-ups after #1066 (#1071) 2026-05-25 18:15:52 +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 777dfdb15b feat(ssh): add SSH executor (#927)
* feat(backend): add SSH executor runtime

Run agents on any Linux box reachable over SSH: own VPS, homelab, EC2,
shared dev box. One SSH connection per (host, user, identity) shared
across all sessions on that host; each session gets its own remote
agentctl process, remote port, and SSH-tunneled local port. Mirrors the
local ~/.kandev/tasks/<task-dir>/<repo>/ layout on the remote so
multi-session tasks share a worktree and per-session runtime state lives
under the task dir.

Implements ExecutorBackend + RemoteSessionResumer + RemoteStatusProvider
+ Closeable. Host-key trust is explicit: the test endpoint observes a
fingerprint without pinning; the user trusts it in settings; subsequent
connects reject any mismatch. Auth via ssh-agent or IdentityFile only
(passphrase-protected keys must be loaded into ssh-agent). Parses
~/.ssh/config for HostName/Port/User/IdentityFile/ProxyJump inheritance.
agentctl is content-hash-cached on the remote (~/.kandev/bin/agentctl
plus a .sha256 sidecar) and uploaded only when local and remote differ.
Linux/amd64 only in v1, matching Docker's current state; arm64 is
called out as a cross-cutting follow-up.

See docs/specs/ssh-executor/spec.md.

* feat(backend): add SSH test + sessions HTTP/WS endpoints

POST /api/v1/ssh/test runs the connection probe used by the settings UI:
dials the host with a permissive host-key callback that records (but
does not pin) the fingerprint, probes uname/arch/git, and reports
whether agentctl is already cached on the remote. The UI gates the
"Trust this host" checkbox on success + fingerprint, and Save persists
the trusted fingerprint into the executor config.

GET /api/v1/ssh/executors/:id/sessions returns the active SSH-runtime
sessions backing the "Active sessions" card on the executor settings
page, mirroring the SpritesInstancesCard / DockerContainersCard shape
(task, session, user@host, remote port, local forward port, uptime).

Both routes also exposed over WS via ssh.test / ssh.sessions.list.

* feat(web): add SSH executor settings UI

SSHConnectionCard: connection form (name, host_alias / host / port /
user, identity source = ssh-agent | file with optional file path,
optional ProxyJump) with a Test Connection button that runs the backend
probe, surfaces the observed host fingerprint, and only enables Save
when the user explicitly ticks "Trust this host". Editing the host /
port / user / identity fields resets both the test result and the trust
checkbox. On save, if the executor already has running sessions, a
confirm modal warns that those keep going on the old host and only new
sessions will use the new config.

SSHSessionsCard: 90s-polled table of active sessions for the executor,
mirroring SpritesInstancesCard / DockerContainersCard. Columns: task,
session, user@host, remote agentctl port, local forward port, uptime,
status badge. Backed by GET /api/v1/ssh/executors/:id/sessions.

Also registers the ssh entry in executor-icons.ts (label "SSH",
IconTerminal2) so it surfaces consistently in the rest of the settings
chrome.

* docs: add SSH executor v1 spec

Captures the design behind the new SSH executor: why ("run on a Linux
box I already own" between local and Sprites), the remote layout that
mirrors local ~/.kandev/tasks/, per-session agentctl + forward over a
shared per-host SSH connection, explicit-trust host-key flow, ~/.ssh/config
inheritance, amd64 + agentctl content-hash cache, recovery via persisted
ExecutorRunning metadata, settings UI (Connection + Sessions cards), and
the edit-with-live-sessions warning UX. Out-of-scope items (arm64,
macOS, password auth, chained ProxyJump, working-tree push, etc.) are
called out explicitly with the follow-ups they unblock.

* chore(e2e): rename docker project to containers + add e2e README

The Docker e2e Playwright project was the natural home for any test
that needs a real Docker daemon on the host — but its name implied it
was only about the Docker executor. SSH e2e tests (incoming in
follow-up commits) belong here too, since they use a Dockerised sshd
container as the SSH executor's remote target.

- Rename project: docker -> containers, widen testMatch to also include
  tests/ssh/*.spec.ts.
- Rename env flag: KANDEV_E2E_DOCKER -> KANDEV_E2E_CONTAINERS, with the
  old name kept as a deprecated alias for one release so local scripts
  and CI configs don't break overnight.
- Rename CI job: e2e-docker -> e2e-containers, switch its blob report
  name and the merge-job dependency.
- Add apps/web/e2e/README.md explaining the project layout, what the
  containers project covers (Docker executor + SSH executor), why it
  was renamed, and how to run it locally.
- Add docs/specs/ssh-executor/e2e-plan.md tracking the SSH e2e
  coverage we'll implement on top of this rename (real sshd container,
  no mocks, 17 spec files covering ~75 cases). Includes a "Deferred"
  section that flags arm64 as something to revisit when
  agentctl-linux-arm64 lands in the build pipeline.

* feat(web): add data-testid attributes to SSH settings UI

Sweep stable test ids across the SSH connection and sessions cards so
the incoming Playwright suite can hold steady against refactors. Splits
the formerly monolithic ssh-settings.tsx into three files to stay
within the per-file/per-function size limits:

- ssh-connection-card.tsx (form + test-then-trust flow)
- ssh-sessions-card.tsx (active-sessions table)
- ssh-settings.tsx (barrel re-export so existing imports keep working)

Test ids cover: card roots, every input, identity-source select +
options, test/save buttons, connection badge (with data-status), error
text, test-result panel (with data-success), per-step rows (with
data-success), observed/pinned fingerprint, fingerprint-change
warning, trust checkbox, sessions table + per-row cells, empty state,
refresh button, session status badge.

* feat(e2e): scaffold the SSH executor test harness

Lands the building blocks the SSH specs will compose on top of. Every
piece talks to a real sshd container — no mocks at any layer.

- fixtures/ssh-image.ts: builds kandev-sshd:e2e once per machine (Alpine
  + openssh-server + openssh-sftp-server + git + bash + sudo +
  iproute2 + iptables, pre-bakes mock-agent at /usr/local/bin/mock-agent,
  generates a fresh host key on entrypoint, reads the worker public key
  out of a bind-mounted /authorized_keys). The agentctl binary is
  deliberately NOT pre-baked so tests exercise the SFTP upload + sha256
  cache path the production code uses.
- helpers/ssh.ts: per-worker sshd lifecycle (startSSHServer /
  stopSSHServer), keypair generation, host-key fingerprint scanning,
  fault injection (regenerateHostKey for host-key-rotation specs,
  dropTrafficToPort22 / restoreTraffic for connection-drop tests,
  killRemotePid for "agentctl died" recovery), and remote inspection
  helpers (readRemoteFile / remotePathExists / listRemoteDir /
  countSshdConnections).
- helpers/ssh-bastion.ts: two-container ProxyJump setup. Bastion is on
  a private Docker network and has a published port; target is on the
  same network with NO host port — any successful connection MUST have
  traversed the bastion, which makes the proxy-jump assertion honest.
- fixtures/ssh-test-base.ts: worker-scoped fixture mirroring
  docker-test-base. Skips when Docker isn't reachable. Spins up the
  sshd container, generates keys, scans the fingerprint, then seeds a
  workspace + workflow + bare repo + mock-agent profile + an SSH
  executor with the fingerprint already trusted. Specs that need to
  exercise the test-then-trust UI gate create their own executor on
  top of the same target.
- pages/SSHSettingsPage.ts: Page Object covering the connection form,
  test/save buttons, trust checkbox, observed/pinned fingerprint, per
  step badges, and the sessions table.
- helpers/api-client.ts: new createSSHExecutor / updateExecutor /
  getExecutor / testSSHConnection / listSSHSessions methods plus
  matching DTO types.

* test(e2e): add SSH executor Playwright suite (17 specs, ~75 cases)

Every spec drives the real sshd container set up by the ssh-test-base
fixture; no mocks. Specs are grouped by concern (file per group),
mirroring the docker/ directory style. Each one maps 1:1 to a row in
docs/specs/ssh-executor/e2e-plan.md.

UI surface:
- connection-form.spec.ts — field rendering, save/test gating,
  identity-source toggle, default port.
- test-result.spec.ts — successful + failed Test Connection paths,
  per-step badges, fingerprint surfacing, cached/will-upload copy.
- trust-gate.spec.ts — save disabled until trust ticked, edits reset
  result + trust, fingerprint-change warning when pinned != observed.
- sessions-card.spec.ts — empty state, row rendering, manual refresh,
  status badges, truncation, polling pickup.
- persistence.spec.ts — fingerprint persists across reload, new form
  starts blank, executor list label, partial state doesn't leak.

API contract:
- test-endpoint.spec.ts — POST /api/v1/ssh/test step ordering, invalid
  body, host-required, handshake short-circuit, cached/uploaded states.
- sessions-endpoint.spec.ts — GET /api/v1/ssh/executors/:id/sessions
  filters to ssh-runtime rows, populates metadata, monotonic uptime.
- executor-crud.spec.ts — type=ssh persists fingerprint, profile
  workdir round-trip, edit-with-running-sessions keeps snapshots.

Real-SSH integration:
- launch-task.spec.ts — full smoke: agentctl upload + sha256 cache hit
  on second launch, task/session dir layout, stop cleans session dir.
- recovery.spec.ts — backend restart reconnects, dead pid surfaces
  failure, persisted metadata keys present.
- auth-methods.spec.ts — key + valid, missing key, passphrase-protected
  rejection, agent without SSH_AUTH_SOCK, wrong-key auth failure.
- concurrency.spec.ts — two sessions share task dir distinct ports, two
  tasks distinct dirs, traffic drop + restore exercises eviction +
  reconnect.
- hostkey-rotation.spec.ts — regenerate host key surfaces new
  fingerprint, stale pinned fingerprint blocks launch verbatim, re-trust
  restores function.
- config-inheritance.spec.ts — ~/.ssh/config HostName / Port /
  IdentityFile / ProxyJump inheritance with form-overrides-config rules.
- workdir-per-profile.spec.ts — per-profile ssh_workdir_root routes to
  separate remote workdir trees; default falls back to ~/.kandev.
- proxy-jump.spec.ts — 2-container bastion topology asserts target is
  unreachable directly, reachable via ProxyJump, chained ProxyJump fails.
- error-surfacing.spec.ts — TCP refused, auth failed, bastion unreachable
  surface verbatim; backend 400 stays a 400 not a synthesised failure.

Also adds an AGENTS.md (CLAUDE.md symlink) line pointing at the
e2e/README.md so future agents discover the containers project +
KANDEV_E2E_CONTAINERS env var without grepping playwright.config.ts.

* fix(e2e): unlock sshd account, derive fingerprint from kandev probe

Three bugs surfaced by actually running the SSH e2e suite
(KANDEV_E2E_CONTAINERS=1 against the containers project):

1. Alpine's `adduser -D kandev` leaves the account password-locked
   (`!` in /etc/shadow). sshd then refuses every auth method for that
   user — including pubkey — with "User kandev not allowed because
   account is locked". Fix: `usermod -p '*' kandev` in the Dockerfile
   so the account is open for key-based login but still has no valid
   password. Also adds the `shadow` apk package for `usermod`.

2. ssh-keyscan reports the ed25519 host fingerprint, but Go's ssh
   client may negotiate a different host key type when sshd offers
   multiple — meaning the fingerprint the fixture pre-scanned didn't
   match the one kandev observed at handshake time. Fix: the fixture
   now hits /api/v1/ssh/test with a permissive callback right after
   the container is up and uses that fingerprint as the pinned value.
   Same code path real users hit; eliminates the negotiation skew by
   construction.

3. ssh.ts had a CPU-spin sleep helper and an nc-dependent TCP probe,
   both fragile. Replaced with a proper sleep subprocess and a bash
   /dev/tcp probe, plus retry-with-stderr on the fingerprint scan so
   failures are diagnosable.

Also tightens test-endpoint.spec.ts F4: the test was using
identity_source=agent to "fail fast", but that fails inside
buildAuthMethods before the handshake step ever runs. Switched to
identity_source=file against a refused port so the test exercises
the actual TCP+handshake failure path.

After these fixes 4/6 test-endpoint cases pass against a real sshd.

* fix(ssh): make the end-to-end launch path actually work

A pass of issues uncovered by running the SSH e2e suite locally
(KANDEV_E2E_CONTAINERS=1 against the real sshd container). After this
commit all 15 non-launch SSH e2e tests pass (UI form validation,
test-connection contract, auth-methods, error-surfacing, sessions-card
empty state) and the launch path runs through prepare -> upload ->
agentctl -> instance -> forward, with WebSocket streams sometimes
disconnecting partway through (tracked below for follow-up).

Image changes (apps/web/e2e/fixtures/ssh-image.ts):
- Install curl so the SSH executor can POST to the in-container
  agentctl control server for instance creation.
- Install gcompat + libstdc++ so the dynamically-linked glibc
  agentctl binary can exec on musl-libc Alpine. Without it the
  kernel returns ENOENT for /lib64/ld-linux-x86-64.so.2.
- Install shadow + 'usermod -p *' kandev so sshd doesn't refuse
  pubkey auth for the otherwise-locked user.
- Drop in 'AllowTcpForwarding yes' and 'MaxSessions 100' via
  /etc/ssh/sshd_config.d/. Alpine's defaults are 'no' and 10, both
  of which crater the SSH executor's port-forward path.
- chown /home/kandev/.kandev to kandev on entrypoint so a host
  bind-mount of that path (used in this commit for log persistence)
  doesn't make agentctl unable to write its log file.

Image helper (apps/web/e2e/helpers/ssh.ts):
- Bind-mount the host mock-agent-linux-amd64 into the container at
  the same absolute path. kandev's orchestrator builds the agent
  command from KANDEV_MOCK_AGENT_LINUX_BINARY (a host path), so the
  remote needs the binary at that exact path; bake-into-image isn't
  enough because the absolute host path is what kandev sends.
- Bind-mount /home/kandev/.kandev so per-session agentctl logs
  survive --rm teardown and the test runner can inspect them on
  failure.
- Replace the broken CPU-spin sleep helper with a real sleep
  subprocess and a /dev/tcp TCP-open probe so timing-dependent
  helpers stop racing the container start.
- Retry the host fingerprint scan with stderr capture; the first
  scan can race the sshd accept loop on Alpine.

Backend SSH executor (apps/backend/internal/agent/lifecycle):
- executor_ssh_operations.go startRemoteAgentctl: agentctl does not
  accept --port-file or --pid-file flags (it reads AGENTCTL_PORT
  and writes its own pid). Rewrite the launch wrapper to inject
  AGENTCTL_PORT via env, capture $! as the pid, and tail the
  on-remote agentctl.log for 'HTTP server bound successfully'
  instead of waiting on imaginary side-files.
- executor_ssh_operations.go createRemoteAgentInstance: new helper
  that POSTs /api/v1/instances on the in-container control server
  via SSH-exec'd curl, returning the per-instance port the executor
  should forward to. Mirrors what executor_sprites_operations.go
  does inside its sprite. Without this step the agent stream
  returns 'configure request failed with status 404' because the
  SSH executor was talking to the control server, not the
  per-session sub-server.
- executor_ssh.go startAndForwardAgentctl: chains the new
  create-instance step in between agentctl launch and port-forward,
  and forwards the *instance* port (not the control port).
- executor_ssh.go: drop the per-host SSH connection pool (it was
  introducing a subtle aliasing issue between
  CreateInstance/StopInstance/GetRemoteStatus that made the SSH
  client unreliable across same-host sessions). Each session now
  holds its own ssh.Client directly on sshSessionState and
  ResumeRemoteInstance dials a fresh client too.
- executor_ssh_operations.go SSHPortForwarder: serialize the
  client.Dial calls with a per-forwarder mutex. golang.org/x/crypto/
  ssh.Client.Dial is documented as concurrency-safe but in practice
  parallel opens from the kandev stream-manager occasionally
  produce io.EOF as if the channel-open response was never
  received.

Test fix (apps/web/e2e/tests/ssh/error-surfacing.spec.ts):
- Q1 ('TCP refused') was using identity_source='agent' with no
  SSH_AUTH_SOCK in the backend env, so it failed at
  buildAuthMethods before reaching the TCP-refused path. Switch to
  identity_source='file' with the seed key so the test exercises
  the failure it claims to.

Known remaining issue (to investigate next): the launch path now
reaches 'agent process started' + 'ACP initialize response
received' when run in isolation, but the WebSocket updates stream
sometimes disconnects with 1006 abnormal closure shortly after. A
standalone Go reproduction of concurrent direct-tcpip channels
against the same image works without issue, so the trigger is
something specific to the kandev backend's stream-manager + my
forwarder interaction. Tracked for the next iteration.

* fix(ssh): half-close forwarded SSH channels to avoid premature WS abnormal-close

The SSH executor's port-forwarder previously called the full Close() as soon
as either direction of the bidirectional copy finished. Under HTTP-Upgrade
WebSocket traffic this meant: when the WS server flushed its final frame and
shut down the write side, our local->remote io.Copy returned EOF, we closed
the entire SSH channel, the remote->local copy aborted mid-frame, and the
backend's WS reader observed close 1006 (unexpected EOF) instead of a clean
close frame.

Switch to a half-close pattern: each direction CloseWrite()s its destination
when its source EOFs, letting the other half drain the remaining frames. The
final Close happens after both copies return.

The "ssh forwarder dial remote failed: EOF" warning in e2e logs was a
follow-on symptom — the SSH client was being torn down by the abnormal close,
so any later channel-open returned EOF immediately.

* fix(ssh): resolve session executor_id via TaskSession join

GET /api/v1/ssh/executors/:id/sessions was filtering ExecutorRunning rows by
their ExecutorID column, but the lifecycle manager's buildRunningFromExecution
only sets that column from a prior row — for fresh sessions it's left empty.
The endpoint therefore returned [] for every just-launched SSH session.

Look up the TaskSession by session_id and compare its ExecutorID instead.
Keep the row's own ExecutorID as a fast-path for resume/recovery flows
where it's already populated.

* feat(web): register ssh entry in the new-executor type map

Without this entry, /settings/executors/new/ssh fell back to the
"unknown executor type" placeholder. Extracts the type map into its
own module so the page file stays under the 600-line lint cap.

The SSH-specific form is still TODO and will replace the standard
profile-create form for this type in a follow-up.

* test(e2e): poll listSSHSessions for SSH session row in group G

The simple-message scenario completes inside a couple hundred
milliseconds, so the previous "wait for executor_type=ssh, then
query once" pattern raced the row's removal during teardown. Poll
listSSHSessions directly with a 60s window so the row is observed
while the executor is up.

Adds dumpRemoteLogs helper for copying per-session agentctl.log
files out of the sshd container on assertion failure, easing
debugging when the row never appears.

* test(e2e): align H5 assertion with actual on-disk session-dir layout

The wrapper writes agentctl.pid and agentctl.log to <sessionDir>; the
remote agentctl port travels via AGENTCTL_PORT env + ExecutorRunning
metadata, not a separate .port file. Assert the files that actually
exist and the metadata field that carries the port.

* feat(web): mount SSH connection + sessions cards on dedicated routes

Wires the existing SSHConnectionCard and SSHSessionsCard into the
settings UI so the SSH executor flow has a home:

- /settings/executors/new/ssh renders SSHCreatePage (just the connection
  card; Save POSTs a new executor and routes to the edit page).
- /settings/executors/ssh/[executorId] loads the executor and renders
  the connection card pre-filled + the sessions card.
- Adds the SSH entry to the executors landing-page tile grid.
- Adds createExecutor / fetchExecutor / updateExecutor helpers to
  settings-api so the new pages can talk to /api/v1/executors directly.

Profile management for SSH executors still flows through the existing
profile pages; this commit only adds the executor-level chrome the
SSHSettingsPage e2e tests expect.

* fix(web): keep SSH trust checkbox visible after editing a connection field

Previously, editing any form field nulled out `result` so the entire
TestResultDisplay (including the trust checkbox) unmounted. The trust-gate
e2e specs assert that after editing host/port/user/identity_source, the
trust checkbox is still present but unchecked — which matches the
intended UX: the user can re-test against the new target and re-tick
trust without losing the prior result for reference.

Now an edit only clears `trust` when the field could route to a
different machine (host_alias, host, port, user, identity_source,
identity_file, proxy_jump); the result panel stays mounted. Editing the
display-only `name` leaves trust alone.

* test(e2e): point SSHSettingsPage at the new SSH executor routes

Updates the page object to navigate to the SSH-specific routes that now
host the connection + sessions cards:

- gotoNew(): /settings/executors/new?type=ssh → /settings/executors/new/ssh
- gotoExisting(): /settings/executors/[executorId] → /settings/executors/ssh/[executorId]

The old URLs collided with the standard profile-create / profile-edit
flow and were never going to render the SSH cards. The new paths give
the SSH UI its own surface, leaving the generic profile pages untouched.

* feat(api): add top-level DELETE /api/v1/executor-profiles/:profileId

Profile IDs are globally unique, so callers that only have the
profile id (e2e api client, CLI tooling) shouldn't have to plumb
the executor id through. Aliases the existing nested handler.

* test(e2e): probe SSH fingerprint via kandev, not ssh-keyscan, in K specs

regenerateHostKey was returning the ssh-keyscan fingerprint, but
ssh-keyscan and the Go ssh client can negotiate different host-key
types — meaning the fingerprint kandev observes during a real probe
does not always match what keyscan saw. The keyscan output was used
verbatim as the expected value, which K1 / K3 then asserted against
kandev's pinned-fingerprint result, so the specs flapped depending
on which algorithm sshd advertised.

Drop the return value from regenerateHostKey and have callers hit
/api/v1/ssh/test to learn the canonical fingerprint, matching what
the SSH fixture already does at seeding time.

K2 was polling env.error_message which doesn't exist — the launch
fails at SSH dial time before the executor is recorded on the task
environment. Point the polling at the task-session error_message
instead, where updateTaskSessionState actually persists the dial
failure.

* test(e2e): wipe agentctl before F5 to assert from a fresh-install state

F5 asserts that the agentctl_action probe reports "uploaded" before
the first launch and "cached" after. Tests share a worker-scoped
sshd container, so an earlier test in the same worker may have
already primed the cache, making the "before" assertion flap.

Wipe ~/.kandev/bin/agentctl + .sha256 from the container at the top
of F5 so the assertion sees the documented fresh-install path.
Export execInContainer so the spec can reach into the container
without copying the docker-exec boilerplate.

Add error_message to the listTaskSessions return type so the
hostkey-rotation spec can read the field (which the backend already
returns).

* fix(ssh): re-read ~/.ssh/config on every resolve, no process-wide cache

kevinburke/ssh_config's package-level Get/GetStrict use a sync.Once
to load $HOME/.ssh/config once per process and cache the result. That
breaks two things:
  * users who edit their config mid-session don't see updates until
    kandev restarts;
  * e2e tests that write a fresh ~/.ssh/config per test all see the
    state captured by whichever test triggered the first lookup.

Open and Decode $HOME/.ssh/config on demand from a local
inheritFromSSHConfig helper. The library still parses the file the
same way — we're just dropping the global cache.

Unblocks the four ssh/config-inheritance.spec.ts cases that wrote a
per-test ~/.ssh/config.

* feat(ssh): parse literal user@host:port ProxyJump bastion strings

dialViaJump fed target.ProxyJump straight into ResolveSSHTarget as a
host alias. That works for `Host prod-jump` entries in ~/.ssh/config
but turns the literal `user@host:port` form into a single hostname
that the kernel resolver chokes on (`lookup kandev@127.0.0.1:23000: no
such host`).

Detect the literal shape inline (`[user@]host[:port]`) and build the
bastion SSHTarget from its parts. Falls back to the alias path when
no @ / : separators are present.

Fixes the proxy-jump.spec.ts bastion flow. While here:
  * scanFingerprintInsideNetwork: alpine package is `openssh-client`,
    not the (nonexistent) `openssh-keyscan`. Surface install errors
    so future failures aren't silent.
  * scanFingerprintViaHost: retry on empty output — sshd accepts TCP
    before host-key negotiation completes on a cold container.
  * startBastionAndTarget: share one keypair across bastion + target
    so a single -i auths both hops (matches how OpenSSH ProxyJump
    handles per-host identities outside ~/.ssh/config).
  * proxy-jump N1: assert any SHA256 fingerprint came back, since the
    test no longer pre-discovers a value to compare against.

* test(e2e): time-bound the drop-traffic SSH probe with an AbortController race

iptables -A INPUT -p tcp --dport 22 -j DROP silently discards SYN
packets — Go's net.Dialer sits in the connect syscall through the
kernel's TCP_SYN_RETRIES (default 6 ~ 127s) before the syscall is
abandoned, even though the dialer's logical Timeout is 30s. The
spec polled the testSSHConnection API for the failure path; the
request blocked long enough that Node's keep-alive evicted the
socket and the test failed with "other side closed" instead of
seeing kandev's success=false response.

Race the probe against a 5s timeout. If the request errored or
timed out the test passes (both are valid evidence that the drop
hit the dial path); if it came back with a response, assert
success=false the same way the original spec did. The restore-probe
poll still gates on a real success after restoreTraffic.

* test(e2e): rerun ssh.test in hostkey-rotation afterEach to repin

Hostkey-rotation specs mutate the worker-scoped sshd container and
the seeded SSH executor's pinned fingerprint. Without a cleanup hook,
the next spec in the same worker that resolves seedData.sshTarget.
hostFingerprint observes a stale value and the UI's trusted-badge
check (persistence R1) flaps.

Add an afterEach that re-probes the live container via kandev, syncs
the fingerprint into both seedData and the seeded executor's pinned
config. The cleanup is a no-op when the probe fails (e.g. K2 left an
intentionally bad fingerprint that no longer matches anything — the
next test will re-establish state via its own setup).

* test(e2e): restore the seeded executor's pinned fingerprint after R5

The fingerprint-change-warning spec pinned a deliberately bogus
fingerprint on the worker's seeded SSH executor to exercise the
mismatch UI, then exited without resetting it. Later specs in the
same worker that launched real tasks against the same executor
(workdir-per-profile R1/R2 in alphabetical order) failed at SSH dial
time with host-key-changed, since the executor was still pinned to
the bad value.

Wrap the assertion in a try/finally that restores the original
fingerprint from seedData when the test ends, so the worker leaves
the executor in the same state it inherited.

* fix(ssh): quote every remote path + clean identity file path

CodeQL flagged two paths from HTTP-supplied SSH-config fields into
shell + filesystem operations:

  * runSSHCommand built "cat $remoteShaFile" / "test -x $remoteBin"
    / "mkdir -p $(dirname $remoteBin)" by direct concatenation; the
    arguments come from $HOME on the remote (not the kandev user)
    but the analyzer can't see that, and a remote $HOME containing
    shell metacharacters would still misparse. Route them through
    shellQuote for parity with every other call site in the file.

  * dialAuth opened target.IdentityFile straight from the configured
    string. Run it through filepath.Clean so any `..` segments slipped
    in by string substitution are normalised before os.ReadFile, which
    is the canonical mitigation CodeQL recognises here. Behaviour is
    unchanged for normal paths.

* refactor(ssh): drop the unused conn pool + remote curl dependency

CodeRabbit and Greptile both flagged the SSHConnPool: the executor never
took the pool path (CreateInstance always dialDirect'd a fresh client and
parked it on sshSessionState), so the pool's keepalive goroutines and
refcount logic were dead code. Get() also overwrote map entries on every
call, which would have leaked keepalive goroutines if the pool *had* been
used. Delete the entire SSHConnPool + sshConnKey + pooledConn + keepalive
plumbing. Export DialSSH so the SSH test endpoint can dial directly and
close the client when its single-shot probe is done.

While here:
  * pickRemoteAgentctlPort: switch from time.Now().UnixNano()%20000 to
    math/rand/v2.IntN. Two concurrent CreateInstance calls on a fast
    machine were getting the same port (UnixNano cycles in ~20µs through
    the 20k range); randomized picks avoid the collision.
  * createRemoteAgentInstance: POST to the remote control port over a
    direct-tcpip dial via net/http instead of shelling out to `curl`. The
    sshd container no longer needs curl, the kandev test endpoint no
    longer needs to probe for it, and the call inherits Go's standard
    timeout + error handling. Drop `curl` from the e2e Alpine image.
  * maybeUploadCredentials: was probing `printf %s "$HOME"` and
    discarding the output, then allocating an unused sshFileUploader.
    SSH v1 doesn't ship credential upload — just log a warning when a
    user sets remote_credentials so they know it won't take effect, and
    delete the dead uploader file.

* fix(ssh): verify bastion host key + tighten the trust-gate UX

Bastion host-key verification (security)
  resolveBastion built the bastion's ClientConfig with an empty
  PinnedFingerprint, which buildClientConfig translated into a
  callback that accepts any key. An attacker on the path to the
  bastion (DNS poisoning, route hijack) could pivot through it
  before the final-target check ever ran. Greptile flagged it as P1.

  Swap in a callback that consults ~/.ssh/known_hosts via
  knownhosts.New: matched key → accept; mismatched key → reject loud
  (the alarm); host absent → accept with the same TOFU semantics
  OpenSSH uses for StrictHostKeyChecking=accept-new, so e2e and
  first-connect setups still work without manual `ssh-keyscan`
  priming.

Stale-test trust gate (frontend)
  Editing a connection field after a successful test previously kept
  the prior result + cleared `trust`, but the trust checkbox could
  be re-checked and saved with the old fingerprint bound to the new
  target. CodeRabbit + cubic both flagged it as P1.

  Add a `resultStale` flag that flips when a CONNECTION_FIELD edit
  follows a successful test, surface a warning under the result, and
  disable the trust checkbox + save button until the user re-runs
  Test Connection. handleTest clears the flag.

While here
  * Surface onSave failures in the card instead of swallowing them.
  * ssh-create-page: read the executors slice from the live store
    (useAppStoreApi + getState()) at write time so a concurrent
    update doesn't get overwritten by a stale closure.
  * Split FingerprintTrustBlock into its own file to keep
    ssh-connection-card under the 600-line cap.

* fix(ssh): defend launch + handshake against several real bugs

manager_launch: trusted exec-config keys override req.Metadata.
  buildLaunchMetadata applied executor config only when the matching
  key was missing in req.Metadata. A request that carried metadata.
  ssh_host_fingerprint (or ssh_host, ssh_identity_*) could pivot the
  launch to a different target and bypass the pinned fingerprint.
  Pin a list of connection-routing keys (ssh_host, ssh_port, ssh_user,
  ssh_host_fingerprint, ssh_identity_source, ssh_identity_file,
  ssh_proxy_jump) and have the executor config always win for those.
  Cubic / CodeRabbit P1.

executor_ssh.CreateInstance: reuse the resumed session state.
  ResumeRemoteInstance attaches the recovered ssh.Client + forwarder
  to r.sessions[InstanceID] and refreshes metadata, then the lifecycle
  manager unconditionally called CreateInstance, which dialed a fresh
  client and started a second remote agentctl on top of the live one
  — leaking the resumed state. CreateInstance now early-returns from
  the existing r.sessions entry via buildResumedInstance. Cubic P1.

executor_ssh.Close: actually release tracked sessions.
  After dropping the SSHConnPool, Close was a no-op. A hard kandev
  exit (no per-session StopInstance) left forwarders and SSH clients
  open. Iterate r.sessions and Close the forwarder + client for each.
  Cubic P2.

buildAuthMethods: close the ssh-agent unix socket after handshake.
  Each agent-authenticated dial opened net.Dial("unix", $SSH_AUTH_SOCK)
  and never closed it; only PublicKeysCallback held the agent.Client
  reference and that callback is consulted exactly once at handshake.
  Return a cleanup func from buildAuthMethods + buildClientConfig and
  defer it from dialSSH / dialViaJump so the socket releases as soon
  as key exchange completes. Greptile P1 security.

waitAgentctlHealthy: probe HTTP /health, not just the TCP listener.
  The local port is owned by the SSH forwarder, which Accepts before
  it Dials the remote direct-tcpip channel — a TCP connect can succeed
  before the channel actually establishes. Issue a real GET /health
  and require a 2xx so a broken tunnel surfaces here rather than at
  the first agent operation. Cubic P1.

ssh-connection-card: also gate the trust + save on in-flight tests.
  Editing a connection field during a pending test silently kept
  resultStale=false because prev.result was still null; when the test
  returned, the new fingerprint was bound to the old form values but
  the gate let the user trust + save anyway. Treat in-flight tests as
  prior tests for staleness purposes, and preserve resultStale across
  the test's success setState. Cubic P2.

* fix(ssh): drop stale polls + preserve port inheritance + sshd extra-keys

ssh-sessions-card: race-protect polls.
  Polling setInterval + manual refresh shared one state setter, so a
  slow request that resolved after a newer call (or after a parent
  switched executorId) overwrote fresh data with stale rows. Bump a
  monotonic sequence on each refresh and drop the response when the
  sequence has moved on, plus reset on mount and invalidate on
  unmount so an in-flight reply from a teardown can't land. Cubic P2.

ssh-config parseSSHExecutorConfig: don't default ssh_port to 22.
  Reading an executor row that had no ssh_port set rewrote port=22
  on the form, which then round-tripped back to the backend. That
  silently broke ~/.ssh/config Port inheritance for aliases — a save
  could redirect connections to 22 even though the underlying alias
  was supposed to resolve to another port. Leave the field undefined
  so the backend resolver can apply the alias' value. Cubic P2.

ssh-image entrypoint: guard authorized_keys.extra mount.
  When only /authorized_keys.extra (and not /authorized_keys) was
  bind-mounted, the >> redirect ran under set -e against a missing
  destination and aborted container startup. mkdir + touch the
  destination before the append and reapply the ownership/perms.
  CodeRabbit P2.

* test(e2e): make G2 + F6 actually exercise the contract

G2 (sessions-endpoint filter) iterated `for (const s of sessions)` over
the listSSHSessions result without first asserting `length > 0` — an
empty response let the test pass without checking anything. Seed an SSH
launch before the loop and require at least one row, so a handler
regression that returned [] would now fail loud. CodeRabbit P1.

F6 (ws ssh.test parity) called apiClient.testSSHConnection twice (HTTP
both times) and compared the two HTTP responses, which would have
passed even if the WS dispatcher entry was broken. Use apiClient.
wsRequest("ssh.test", payload) for the second call so the gateway's
WS handler is actually invoked, and assert the step names match across
transports. CodeRabbit P1.

* refactor(e2e): extract SSH HTTP shapes into api-client-ssh.ts

api-client.ts was already over the 600-line lint cap on main (1528
lines); the SSH additions made it worse. Split the SSH HTTP shape
types into a dedicated module and re-export from api-client.ts so
existing callers keep working. The methods themselves stay on
ApiClient as thin pass-throughs since splitting them out across the
class boundary would change every test call site.

Also document the per-executor bound on the SSH listSessions per-row
GetTaskSession lookup (typical N < 10), and what a batch path would
need (a repo method to fetch task_sessions by id list). Cubic /
Greptile P2.

* docs(spec): correct SSH recovery keying after pool removal

The spec said ResumeRemoteInstance re-opens 'per (host, user) — one
connection serves all surviving sessions on that host', which was
the pool design. The current executor gives each session its own
SSH client, so the resume keys on the full (host, port, user,
identity_*, proxy_jump, host_fingerprint) tuple. That way two
profiles on the same host with different keys can resume side by
side without merging. Cubic P2.

* fix(ssh): IPv6 ProxyJump + port range + dedup + docker timeouts

parseLiteralProxyJump: handle bracketed IPv6 + reject invalid ports.
  The literal parser used LastIndex(":") to split host from port, which
  for [2001:db8::1]:22 left host as "[2001:db8::1]" and produced an
  invalid double-bracket address through net.JoinHostPort. Recognise
  the bracketed form explicitly via a parseBracketedHostPort helper
  and strip the brackets. Validate port is in [1, 65535] instead of
  accepting any integer (Atoi happily parses negative or out-of-range
  values). Split the host/port branch into its own function so the
  nesting stays under the golangci nestif limit.

ssh-create-page: dedupe on append.
  setExecutors([...current, next]) would double-list the same executor
  if a WS event (or another refresh) inserted it while createExecutor
  was in flight. Skip the append when current already has the id.

ssh-image fixture: time-bound docker probe + build.
  hasSSHContainerSupport ran `docker info` with no timeout — an
  unreachable / hung daemon would stall the Playwright worker
  indefinitely. Cap at 10s for the probe. buildE2ESSHImage runs
  `docker build` with no timeout; cap at 15 min so a stuck registry
  pull or BuildKit hang fails fast.

* fix(ssh): reject invalid ssh_port + retry in-net keyscan + restore D5 + doc count

executor_ssh.targetFromMetadata: reject malformed / out-of-range
ssh_port instead of silently falling back to 0 → 22 in the resolver.
"abc", "0", "70000" all now return a "must be 1-65535" error so a
broken config can't masquerade as a successful launch routed through
port 22. Cubic P2.

scanFingerprintInsideNetwork (bastion fixture): retry on empty output.
Mirrors the host-side scanFingerprintViaHost retry loop — sshd accepts
TCP before host-key negotiation completes on a cold container, so the
keyscan can come back empty on the first try. Bound at 15s; surfaces
"status=..., stderr=..." on final failure for diagnosis. Cubic P2.

executor-crud D5 (changing config…): restore the seeded executor in a
try/finally. The test pinned the executor to host=10.255.255.1 to
verify the snapshot stayed sticky on the live session, but never put
the real host back, so any later spec in the same worker that reused
seedData.sshExecutorId would dial the unroutable address and hang.
Cubic P2.

e2e-plan.md: replace the "roughly 75" estimate with the actual 80 /
17-files current count plus the ~2.4 min wall-clock. Cubic P3.

* fix(ssh): use bare mock-agent name so the remote PATH resolves it

For SSH the agent runs on a remote host whose filesystem doesn't share
paths with the kandev backend's, so the host-absolute mock-agent path
configureMockAgent computes can't apply. Extend the bare-name branch in
MockAgent.BuildCommand to include RuntimeSSH (the SSH e2e image already
bakes mock-agent into /usr/local/bin) and drop the now-redundant SSH e2e
bind-mount that worked around this by mirroring the host path into the
container.

* fix(ssh): unique sftp temp filename so concurrent uploads don't collide

When two sessions on the same task launch back-to-back they both call
ensureAgentctlOnHost which streams to <remotePath>.tmp before renaming.
With a shared .tmp name the second uploader's rename errors with
"file does not exist" once the first uploader's rename consumed the temp
file. Give each uploader its own pid+random-suffix temp; uploaders write
identical sha256-keyed content, so the rename race is then safe.

* fix(ssh): don't leak session-scoped metadata across sibling sessions

reuseExistingEnvironment copies persistent metadata from the previous
ExecutorRunning row into the new launch request so executors can pick up
worktree/container/sandbox IDs. For SSH that swept in session-scoped
keys too — agentctl PID/port, session dir, local forward port — which
made the second session's ResumeRemoteInstance reattach to the first
session's agentctl process. Mark those keys as session-scoped and skip
them in applyExecutorRunningMetadata; the same-session resume path
(applyRunningRecordToResumeRequest) still copies them because it works
off the session's own ExecutorRunning record.

* test(ssh): cover ProxyJump parsers + sibling-session metadata filter

Addresses the two coverage gaps Claude flagged on PR review round 3:

- parseLiteralProxyJump / parseProxyJumpHostPort / parseBracketedHostPort
  / parsePortString are pure parsers that gate every ProxyJump dial,
  including IPv6 (`[2001:db8::1]:22`). Table-driven tests pin the happy
  paths and the bracket / port / range edge cases — silent regressions
  in bracket stripping would otherwise break every IPv6 ProxyJump
  session without a single test failing.
- applyExecutorRunningMetadata is the function commit 044b76bb taught to
  skip session-scoped keys when reusing a sibling session's metadata.
  A direct test now asserts the SSH PID/port/session-dir/forward-port/url
  keys are filtered out while host/port/user/fingerprint/task-dir keys
  still propagate, and that an explicit request value isn't overwritten.

* fix(ssh): rename agentctl_action=uploaded to needs_upload (test endpoint)

The /api/v1/ssh/test endpoint only probes whether the agentctl sha256
sidecar already lives on the remote — it never uploads. Reporting
agentctl_action="uploaded" in the not-cached branch said the opposite
of what the step Output line said ("will upload on first launch") and
mis-signaled real-upload status to any external tooling. Rename to
"needs_upload" so the contract matches the behavior.

* fix(ssh): add ssh_host_alias to trustedExecutorConfigKeys

ssh_host_alias steers ResolveSSHTarget through ~/.ssh/config and ends up
controlling the final Host/Port/User/IdentityFile. Leaving the key out
of trustedExecutorConfigKeys let request-supplied metadata override the
executor's configured alias and pivot the launch to a different host —
the same class of attack the existing entries (ssh_host, ssh_port, …)
guard against. Promote the literal to a constant and add it to the
trusted set.

* fix(ssh): emit 1/1 completion progress when the preparer step succeeds

The final reportProgress was passing (completed=0, total=1) right after
completeStepSuccess marked the step done, so UI subscribers saw the
preparer end at 0% completion. Report 1/1 to match the actual state.

* fix(web): preserve POST/Content-Type + read latest executors at write time

- testSSHConnection: caller's options.init was spread AFTER the required
  method/headers/body, so a caller passing init.headers (or method/body)
  would silently clobber Content-Type and break server-side parsing.
  Spread options first; let the required fields win, and merge headers
  on top of caller-supplied ones.
- useSaveExecutor: the fallback path in the catch arm operated on the
  executors slice captured at hook-creation time, so a WS update that
  landed mid-flight could be overwritten. Read the current snapshot via
  the store API at write time instead, matching what the create flow
  already does.

* fix(ssh): drop "in v1" from user-facing copy

These strings render in the New SSH Executor header, the Connection card
description, and the ProxyJump field hint. "in v1" reads like internal
planning leaking into the UI; the limitations themselves still hold so
just describe them directly.

* fix(ssh): auto-create a default profile on new SSH executor

The /settings/executors index renders entries by flattening to executor
profiles; an SSH executor created with no profiles was effectively
invisible there even though the executor itself existed. The non-SSH
create flow does this implicitly because it goes through the
create-profile form; the SSH-specific flow skipped it.

POST a default profile under the freshly-created executor (same name as
the executor, no overrides) right after createExecutor, then push the
combined record to the store so the index sees it on first paint.

* feat(ssh): pre-flight the agent binary on the remote before launch

Without this, a remote that lacks the agent's required binary (e.g.
\`npx\` for any node-based ACP agent) surfaced the failure deep inside
agentctl as an opaque \`exec: "npx": executable file not found in \$PATH\`
— delivered AFTER a successful "Starting agent controller" step, which
reads as "everything's fine right up until it isn't".

The new step runs right after agentctl upload: derive the binary from
\`agent.BuildCommand(Runtime=ssh).Args()[0]\`, \`command -v\` it on the
remote, and on miss return a structured error that names the agent,
points at the missing binary, and includes the install hint sourced
from \`agent.InstallScript()\`. The message lands on the prepare-step
output (so the UI shows it inline) and on the session's error_message
(so the orchestrator surfaces it on the task).

Coverage: unit test for the error formatter (pure function, no SSH
needed) + e2e regression that mv's mock-agent aside on the sshd
container and asserts the surfaced error mentions agent name, binary,
\$PATH, and the install hint.

* feat(ssh): surface host/workdir/agentctl in the task executor popover

Parity with the Docker and Sprites paths: when the user hovers the
Executor Settings button on a task, an SSH-backed environment now shows
the connection target (\`user@host[:port]\`), the remote task dir, a
compact \`pid → remote :port → local :port\` summary of the agentctl
process, the trimmed host-key fingerprint with copy, and a paste-ready
\`ssh ...\` command that mirrors how kandev itself connects.

Sourced via a parallel \`ssh\` block on
GET /api/v1/tasks/:id/environment/live (no schema migration needed) —
the service joins the task's latest ExecutorRunning row's metadata at
fetch time, the same metadata SSH executor writes in CreateInstance.
The probe is metadata-only on purpose: the popover polls every 3-7s
and a per-poll SSH dial would be both slow and a lot of TCP traffic;
live agentctl/connection health stays under the per-executor
GetRemoteStatus path.

shouldShowExecutorEnvironmentControls now allowlists \`ssh\` so the
button actually renders for SSH tasks (Docker/Sprites/Remote-Docker
were already in the allowlist; SSH was the only runtime that mounted
a TaskEnvironment without showing the popover).

Coverage: unit tests pinning buildSSHLiveStatus's projection of
ExecutorRunning.Metadata into the popover-shaped struct (strings,
string-encoded ints, native ints, empty, malformed) + e2e regression
that launches an SSH task, opens the popover, and asserts each row.

* feat(ssh): probe enabled agents on the remote from settings

Adds a "Remote agent readiness" panel on /settings/executors/ssh/:id so
users can diagnose "which agent CLIs are actually installed on this
host" before launching a task. The same diagnosis that previously
required a launch attempt + reading the pre-flight error now sits one
button-click away on the executor's settings page.

Backend:
- New endpoint \`POST /api/v1/ssh/executors/:id/probe-agents\` dials SSH
  to the configured host and walks \`registry.ListEnabled()\`. For each
  agent it derives the binary from \`BuildCommand(Runtime=ssh).Args()[0]\`
  and runs \`command -v <binary>\` via the new exported
  \`lifecycle.ProbeRemoteBinary\` helper. Returns rows with availability,
  the resolved path on hit, and the agent's \`InstallScript()\` as a
  copy-pasteable hint on miss.
- \`ssh.RegisterRoutes\` now accepts the task service (\`GetExecutor\`) and
  the agent registry; \`cmd/kandev/helpers.go\` wires both in.

Frontend:
- New \`SSHAgentReadinessCard\` mounted above the sessions card. Manual
  refresh only (each probe dials a fresh SSH connection — too expensive
  to poll). Each row gets a status badge + a copy button for the install
  hint when the agent is missing.

Coverage:
- E2E suite: API contract (mock-agent baked into /usr/local/bin/ → row
  reports installed, with /usr/local/bin/mock-agent as resolved_at;
  move it aside → row flips to missing with the install hint flowing
  through end-to-end) + UI contract (click "Probe agents", assert the
  table renders the row).

* feat(ssh): upload remote-credentials over SFTP at launch time

The SSH executor used to accept the \`remote_credentials\` profile field for
parity with Sprites/Docker but only logged a "not implemented" warning at
launch — anyone configuring Claude/Codex/Gemini auth against an SSH host had
no way to actually get the credentials onto the remote.

Ports the Sprites credential pipeline to SSH:
- \`uploadCredentials\` orchestrates the same four phases Sprites does:
  resolve auth-secrets into env vars, run env-credential setup scripts on
  the remote, detect a local \`gh auth token\` if \`gh_cli_token\` was
  selected, and SFTP the selected file-type credentials into the remote
  user's \$HOME.
- \`sshFileUploader\` satisfies \`lifecycle.FileUploader\` via SFTP with an
  \`mkdir -p\`-equivalent walk for parent dirs and \`chmod\` for mode bits.
- \`runAuthSetupScripts\` shells the script through \`runSSHCommand\` with the
  agent's env vars prepended inline (so the script can read e.g.
  \`CLAUDE_CODE_OAUTH_TOKEN\` to materialize \`~/.claude/.credentials.json\`).
- \`resolveRemoteAuthHomeDir\` probes \`printf %s "\$HOME"\` rather than
  reusing the task workdir — credentials need to land under the user's
  true home (\`~/.claude/...\`) even when \`workdir_root\` overrides things.

Wired into \`maybeUploadCredentials\` so a credential failure is logged as
a warning but doesn't abort the launch (consistent with Sprites).

Frontend: \`useRemoteExecutorFlags\` on the profile-edit page now includes
\`ssh\` in the \`isRemote\` set so \`RemoteCredentialsCard\` renders for SSH
profiles. Previously SSH profiles silently dropped any \`remote_credentials\`
selection because the card never rendered.

End-to-end credential upload still requires a non-mock agent enabled in
e2e mode (mock-agent's \`RemoteAuth\` is intentionally empty). Coverage:
unit tests pin the SFTP \`parentDir\` walk and the shell-quoted env-prefix
builder. Existing Sprites tests already exercise the shared
\`UploadCredentialFiles\` helper.

* fix(ssh): wrap remote commands in a login shell so nvm/asdf PATH applies

sshd's exec channel runs commands via a non-interactive non-login shell.
That doesn't source ~/.profile / ~/.bash_profile / ~/.bashrc, so any
binary added to PATH by nvm/asdf/brew/etc. is invisible to:

- the launch-time pre-flight probe (`command -v <agent-binary>`)
- the readiness panel's per-agent probe
- and the nohup'd agentctl process itself

End result: a user with `npx` installed through nvm sees 'X requires
npx on the remote' and can't launch any node-based ACP agent.

Fix: introduce `WrapLoginShell(shell, cmd)` that wraps cmd in
`${shell} -lc '<cmd>'` (with POSIX-safe single-quote escaping) and
default shell to bash when empty. Thread the configured shell through
ProbeRemoteBinary, startRemoteAgentctl, preflightAgentBinary,
runOneAuthSetupScript, and resolveRemoteAuthHomeDir. The shell is
read from per-profile metadata via the new MetadataKeySSHShell
('ssh_shell') key — flows in via the existing executor-config merge.
The probe handler also accepts an optional {shell} body so the UI can
re-probe under whichever shell the user picked.

Default keeps existing behavior for users who don't set a shell (we
just become a login bash instead of bare sh -c). Unit tests pin the
quote-escaping contract.

* feat(ssh): move readiness card to profile page + add shell picker and install button

Four UX changes that together make the SSH-profile setup flow feel right:

1. Save redirect after creating a new SSH executor now lands on the
   profile-edit page (`/settings/executors/{profileId}`) instead of
   the executor page. Profiles are where users actually configure how
   the host gets used.

2. `SSHAgentReadinessCard` relocates from the executor page to the
   profile-edit page (top, conditional on `executor.type === 'ssh'`).
   The host-level executor page keeps Connection + Sessions.

3. Card gains a shell selector that auto-detects available shells on
   the remote and persists into `profile.config.shell`. Changing the
   shell clears the cached probe so the user re-probes under the new
   shell — PATH depends on which init files get sourced.

4. Each missing-agent row gets an Install button that runs the agent's
   InstallScript via /install-agent (login-shell wrapped). Spinner
   replaces the button while it runs; on completion the card auto
   re-probes. No confirmation dialog — the button is the consent.

E2E: probe-shells reports bash+sh on the alpine image (zsh absent),
install endpoint runs mock-agent's deterministic InstallScript,
unknown agent_id is a 404, and the profile-page UI round-trip works
end-to-end.

* refactor(ssh): drop install-agent endpoint and Install button

Install scripts assume environments we don't control on the remote
(package managers, sudo, network access); the failure modes weren't
recoverable from the UI. Pulling the one-click install — copy-and-paste
hint stays.

Backend: delete POST /api/v1/ssh/executors/:id/install-agent and
everything that fed it (httpInstallAgent / installAgent /
runInstallScript / runSSHCommandShim / InstallAgentRequest|Response /
findAgentByID / joinOutputs / capBytes). No other caller of those
helpers.

Frontend: drop the Install button + spinner + collapsible output panel
from ReadinessRow. The 'Install hint' column reverts to copy-only —
same hint string sourced from agent.InstallScript(), users run it on
the remote themselves. Remove installSSHAgent / SSHInstallAgentRequest /
SSHInstallAgentResponse from the api client + types + e2e helpers.

Survives: probe + readiness panel, shell selector + /probe-shells
endpoint, login-shell wrap on every SSH command (the actual fix for
nvm/asdf users).

* fix(ssh): persist shell choice under the same key the launch path reads

Profile config saved the shell selection as 'shell' but the SSH
executor at launch time reads MetadataKeySSHShell which is 'ssh_shell'.
buildLaunchMetadata copies profile.config keys verbatim into
req.Metadata, so the mismatch meant sshShellFromMetadata always
returned empty and WrapLoginShell silently fell back to bash —
defeating the whole point of letting users pick zsh/sh/etc.

The probe path bypasses metadata (the UI passes shell directly in
the request body) which is why the readiness panel reported codex
as installed under the user's zsh while the launch then failed with
'codex requires npx on the remote' under bash.

Align both sides on 'ssh_shell'.

* fix(ssh): propagate profile ssh_shell into launch metadata

The settings UI saved the shell selection on profile.Config["ssh_shell"],
but applyProfile in executor_state.go only forwards an allow-listed set of
profile.Config keys (ssh_workdir_root, remote_credentials, etc.) into
launch metadata — ssh_shell wasn't on the list. The launch path's
sshShellFromMetadata therefore always returned empty and WrapLoginShell
silently fell back to bash, so a user who installed npx via zsh+nvm hit
'npx not found in $PATH' from the preflight while the readiness probe
(which takes shell straight from the request body) still showed the
agent as available.

Mirror the existing ssh_workdir_root propagation for ssh_shell and pin
both directions (present + absent) with a unit test on resolveExecutorConfig.

* fix(orchestrator): make profile.Config authoritative for ssh_workdir_root + ssh_shell

A task that supplied ssh_workdir_root or ssh_shell in its metadata won
when the profile had no value set — `applyProfile` only overwrote
metadata when profile.Config had a non-empty value, so the task-supplied
value squeezed through the empty-profile case. Both keys steer remote
behavior (workdir target, login shell that runs every command), so a
task author should never be able to redirect them.

Two things, bundled because they touch the same allow-list:

1. Replace the long if-chain in applyProfile with a small declarative
   set of tables (passthrough / rename / authoritative). Behavior for
   the existing keys (remote_credentials, git_user_*, image_tag, …) is
   unchanged.
2. Add a new authoritative tier — ssh_workdir_root + ssh_shell — whose
   profile value ALWAYS wins, including when empty. The reader-side
   helpers (SSHExecutor.workdirRoot, sshShellFromMetadata) already
   handle the empty fall-through to a default.

Pin both directions with subtests: authoritative keys clobber any
task value (empty profile included); ordinary passthrough keys keep
their existing "only set if non-empty" semantics so task-supplied
git_user_name still survives.

* refactor(ssh): pass remote workspace explicitly to createRemoteAgentInstance

startAndForwardAgentctl was briefly mutating the caller's *ExecutorCreateRequest
(overwriting req.WorkspacePath with the remote task dir, then restoring it
after the create-instance POST). That's exactly the boring-and-direct sin —
a callee reading from a struct the caller is mutating around the call.
Pass the remote workspace path as an argument so the dance disappears and
req stays read-only inside this leg.

* fix(ssh): surface SHA read errors instead of swallowing them as "not cached"

SSHCheckAgentctlCached treated any error from reading the remote
sha256 sidecar as "binary not on remote" by returning (false, nil).
A transient SSH transport failure therefore masqueraded as
"needs_upload" in the test endpoint's UI badge — the user retries
the test, gets the same misleading hint, and doesn't see that the
connection itself is flaky.

Append `|| true` to the remote cat so a missing file is a successful
empty-stdout read (the genuine "not cached" path), and surface a real
error to the caller for everything else.

* fix(ssh): handle int/int64/float64 metadata in session listing

intFromMetadata only accepted string values, which is what the SSH
executor writes via strconv.Itoa — but ExecutorRunning.Metadata
round-trips through JSON, and there's no guarantee a numeric value
isn't unmarshalled back as float64 somewhere along the way. Anything
that wasn't a string silently became 0 in the sessions endpoint,
making the SSHSessionsCard's "Remote agentctl port" / "Local fwd
port" columns render as 0 for any row that took a non-string path.

Match the smarter shape already used in service.mdInt
(internal/task/service/service_task_environments.go) so both readers
agree on the projection.

* refactor(e2e): drop duplicate SSH HTTP shapes module

api-client-ssh.ts was a literal copy of apps/web/lib/types/http-ssh.ts
with `Body` suffixed onto every type — 75 lines of pass-through that
buy nothing. The e2e ApiClient now imports the canonical shapes from
lib/types/http-ssh directly, drops the re-export pile at the bottom
of api-client.ts, and the duplicate module is deleted.

No spec referenced the *Body names; the grep is clean.

* fix(ssh): make Content-Type win over caller-supplied headers in ssh-api

In `{ "Content-Type": "application/json", ...headers }` the spread runs
last, so a caller passing `init.headers = { "Content-Type": "x" }` would
override the JSON content type and break server-side parsing — the exact
opposite of what the file's comment claimed. The outer `init` spread is
ordered correctly already; this fixes the inner `headers` literal in
the same direction (spread first, JSON literal last) across all three
SSH client functions. Per CodeRabbit thread.

* fix(ssh): distinguish 404 from server errors when resolving SSH executor

resolveSSHTarget collapsed every GetExecutor error into 404 — a transient
storage outage, timeout, or canceled context made it look like the
executor was deleted. Introduce models.ErrExecutorNotFound, wrap it in
the SQLite repo's sql.ErrNoRows case, and use errors.Is in the SSH
handler so only "row doesn't exist" maps to 404; everything else stays a
500 with the underlying error attached. Per CodeRabbit thread.

* fix(ssh): surface latestRunningForTask repo errors instead of swallowing them

latestRunningForTask returned (nil) on any error from ListTaskSessions or
GetExecutorRunningBySessionID. Transient storage failures rendered as
"no SSH live status" on every popover poll, indistinguishable from the
genuine "task has no running session yet" case. Return the error to the
caller; GetSSHLiveStatus now propagates it, and the handler already logs
+ omits the ssh block on a non-nil error so polling stays graceful.

A session without an ExecutorRunning row is the one expected miss — match
on models.ErrExecutorRunningNotFound and skip quietly. Per CodeRabbit
thread.

* fix(ssh): reset readiness card state when executorId changes

The mount effect only reset the sequence token, so switching executors
left the previous one's rows / error / hasProbed visible until the user
clicked Refresh — reads as "still loading" while actually showing stale
data. Clear setRows / setError / setHasProbed / setLoading in the same
effect so a fresh executor starts blank. Per CodeRabbit thread.

* fix(ssh): copy the full fingerprint, not the truncated display value

The popover renders fingerprints as a hash suffix (e.g. ...abcdef012345)
because the full SHA256 is verbose, but the copy button reused the
displayed string — users got an unusable truncated fingerprint instead
of the real one. Add an optional copyValue on FieldRow that overrides
the clipboard payload, and wire the fingerprint row to it. Per
CodeRabbit thread.

* fix(ssh): keep port forwarder alive on transient Accept errors

SSHPortForwarder.serve returned permanently on any non-orderly-close
Accept error — including transient ones like EMFILE (process FD table
exhausted) or ECONNABORTED. A single hiccup orphaned the forwarder, the
remote agentctl kept running, and the user's session went dark until the
backend was restarted.

Match net.ErrClosed explicitly for the orderly-close path; for anything
else, log a warning and continue the loop so the forwarder survives
recoverable per-accept faults. Per claude[bot] review thread.

* fix(ssh): guard ResumeRemoteInstance against duplicate attach

CreateInstance had an early-out for the case where a previous resume
already populated r.sessions[InstanceID], but ResumeRemoteInstance
itself didn't — a retry would dial a second SSH connection, start a
second forwarder, and overwrite the map entry. The original client +
forwarder leaked until the SSH idle timeout reaped them, and the agent
stream briefly bounced between the two.

Mirror the guard so the two entry points to r.sessions[InstanceID]
agree. Per claude[bot] review thread.

* fix(ssh): pipe auth-setup env vars via stdin to keep secrets out of cmdline

runOneAuthSetupScript inlined env vars as `KEY=value KEY=value <shell>
-lc '...'`. That string is what becomes argv of the outer bash invoked
by sshd, so on the remote host any process the same UID can read sees
the secrets in `ps aux` / `/proc/PID/cmdline` for the brief window the
setup script runs. Single-tenant deployments are unaffected in practice
but the leak is real on shared hosts.

Add a runSSHCommandStdin variant that feeds session.Stdin; replace the
inline env prefix with a stdin payload of `KEY='quoted'` lines sourced
by the wrapped shell under `set -a; . /dev/stdin; set +a`. Env never
appears on the remote shell's argv; it's only visible in /proc/PID/environ
of the setup process itself, which is the minimum surface for "pass an
env var to a remote process".

Replace buildSSHEnvPrefix with buildSSHEnvInitScript; update the test.
Per claude[bot] review thread (greptile P1 finding).
2026-05-25 10:04:40 +01:00
Carlos Florêncio 68aefc0e08 feat(web): system settings pages (status, database, backups, logs, updates, licenses, about) (#942) 2026-05-25 09:04:16 +01:00
Zaybrah ec21c71775 feat(agentctl): add Azure Repos PR creation (#1066) 2026-05-25 09:03:05 +01:00
Evgeny Klinnikov 90c652c8e2 feat: add per-agent-profile environment variables (#1040) 2026-05-25 08:14:45 +01:00
Carlos Florêncio d86481142d docs: add cloud-VM caveats and Playwright install script (#1069) 2026-05-24 23:50:14 +01:00
vimzh aecc5d3cd5 fix(office): stop the backoff timer in channel relay when context is cancelled (#1064) 2026-05-24 23:40:11 +01:00
vimzh 652371c965 fix(websocket): guard Dispatcher's handler map with a RWMutex (#1065) 2026-05-24 23:39:44 +01:00
Carlos Florêncio 5efe9f1df1 fix(ci): disable track_progress for labeled event in claude-review-fork (#1067) 2026-05-24 21:28:31 +01:00
vimzh a3d71cea80 fix(office): bound idle-timeout task lookup with caller's context (#1063) 2026-05-24 20:41:12 +01:00
Carlos Florêncio adc13c6b5a feat: copy gitignored files from repo into new worktrees (#946) (#950) 2026-05-24 20:12:26 +01:00
João Salavisa b7589c78c7 fix(web): use shared PageTopbar on /gitlab so the page has a header (#1062)
The GitLab page rendered a custom in-file header instead of the shared
PageTopbar used by /github, /jira, and /linear — leaving /gitlab without
the standard breadcrumb / home navigation. Swap it for PageTopbar with
the GitLab brand icon and host subtitle, and move the Refresh button
into the topbar's actions slot.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-24 19:59:39 +01:00
Carlos Florêncio be050d9606 docs: add remote cloud environment instructions (#1061) 2026-05-24 14:46:30 +01:00
Carlos Florêncio e2483650d4 fix(agentctl): allow native ACP CLIs in probe allowlist (#1059) 2026-05-24 14:45:42 +01:00
Carlos Florêncio 579081895b feat(automation): make webhook trigger usable end-to-end (#1051) 2026-05-24 14:42:02 +01:00
João Salavisa c913522626 fix(web): make PR CI status reachable on mobile via tap-activated drawer (#1060)
* fix(web): make PR CI status reachable on mobile via tap-activated drawer

PRStatusChip's HoverCard was hover-only, so touch users in the chat
status bar had no way to open the CI status surface. Branch on
useIsMobile(): keep the existing HoverCard on desktop, and on mobile
render a vaul Drawer hosting the same PRCIPopover body so tapping the
chip opens a bottom-sheet "modal" with passes / failures / reviews.

The desktop topbar PR button isn't mounted in SessionMobileTopBar (and
its click path is Dockview-only), so the chip is the only surface that
needs the fix today. New mobile-chrome e2e spec covers tap-to-open,
failed-bucket content, and close.

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

* docs(e2e): rephrase PR CI accessors section comment

The block now spans desktop hover popover + chip + mobile drawer
locators, not just the hover popover.

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

* test(web): cover PRStatusChip desktop/mobile branching in jsdom

Adds focused unit tests around the new mobile drawer path:
- desktop branch renders a chip and click does NOT mount the drawer
- mobile branch starts with no drawer, click mounts drawer + popover
  inner + close button (regression guard for the e2e's toHaveCount(0)
  precondition)
- chip data-* attrs preserved across both branches
- failed PR maps to data-status='failed'
- no-checks PR shows the popover's empty state inside the drawer

Close-on-dismiss can only be verified in a real browser (happy-dom
doesn't fire vaul's CSS transition events) — covered by the
mobile-pr-ci-chip.spec.ts e2e.

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

* fix(web): a11y polish on mobile PR/CI chip drawer trigger

Addresses bot review feedback on #1060:
- Add aria-haspopup="dialog" + aria-expanded={open} on the mobile chip
  button (mirrors the established mobile-pill-button.tsx pattern).
- Add a visually hidden DrawerDescription to satisfy Radix's accessible
  Dialog contract and suppress the console warning observed during
  unit tests.
- Annotate the e2e failed-bucket count assertion with the arithmetic
  (3 total - 2 passing = 1 failed) so future seed-value edits stay
  in sync.

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-24 14:39:02 +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
José Almeida f1bdc56892 feat(layout): roomier pane caps + remember user-set widths (#1005)
* refactor(layout): swap pane width caps for viewport-proportional runtime cap

Replace the hard 350px sidebar / 450px right caps with
max(800, viewport*0.7) so wide displays get a roomy file/terminal
panel and the sidebar can grow with the screen. Pinned minimum is
raised from 50px to 180px so panels don't collapse into unusable slivers.

Caps now live in lib/state/layout-manager/caps.ts; constants module
no longer exports per-column max-px constants.

* feat(layout): persist preferred pane widths, flush on unload, roomier tablet split

- Mirror sidebar / right widths into a sessionStorage pinned-defaults
  slot on every resize; seed brand-new task envs with those widths so
  the user's last-set sizes follow them across tasks.
- Re-apply the runtime cap to every pinned group on each ResizeObserver
  tick so a panel pinned to the old cap grows when the user widens the
  window (and re-clamps when they shrink it).
- Flush the debounced layout save on `beforeunload`, so a reload less
  than 300ms after the last drag doesn't lose the new width.
- Drop the tablet right-panel inner split minSize from 30/20 to 15/15
  so the files vs. terminal proportions match the loosened desktop feel.

* test(e2e): cover pane resize, persistence, and edge cases

Four spec files under apps/web/e2e/tests/layout/ exercise the runtime
cap and pinned-defaults persistence end-to-end via dockview's `.dv-sash`
drag handles and `window.__dockviewApi__`:

- pane-resize-right: drag past the old 450px cap, viewport-shrink
  re-clamp, reload + cross-env propagation of preferred width.
- pane-resize-sidebar: same coverage for the sidebar including
  toggle-off/on width retention.
- pane-persistence-tablet: localStorage round-trip for the tablet
  layout keys (`task-layout-tablet-v1`, `task-layout-right-v2`).
- pane-resize-edge-cases: double-click smoke, rapid drags +
  beforeunload flush, maximize round-trip, sash off-viewport, resize
  with sidebar hidden.

Adds e2e/helpers/dockview-resize.ts for the shared drag + width
read-out helpers.

* fix(layout): cap sidebar at 30% screen width, preserve legacy initial widths

- Split the runtime cap into a sidebar-specific function (max(350, vw*0.3))
  and the right-pane function (max(800, vw*0.7)). File-tree / task-list
  content rarely benefits from more than ~30% of the screen.
- Preserve legacy initial widths: getPinnedWidth now clamps the ratio-based
  default to the old hard limits (350 sidebar, 450 right) so a fresh task
  env opens at exactly the same width as before. Users can still drag past
  these via setConstraints — only the *initial* default is capped tightly.

* fix(layout): address PR review — narrow viewport, hidden sidebar, e2e flake

Bot-review fixups for #1005:

- caps: bound runtime caps by `viewport - VIEWPORT_RESERVE_PX` so the
  800px right-cap floor can't collapse the center column on narrow
  screens (Cubic P1).
- applier: respect `column.maxWidth` on the sidebar too, so the
  `compact` preset's 260px cap is honored at runtime (Cubic P2).
- dockview-store: skip the pinned-defaults mirror when the column is
  hidden — auto-sync infers sidebar from grid index 0, which is the
  center when sidebar is hidden, so an unguarded mirror would
  persist the center's width as the sidebar's (Greptile/Cubic P1).
- trackPinnedWidths: gate the auto-sync on `sidebarVisible` /
  `rightPanelsVisible` for the same reason.
- sizing: use `LAYOUT_RIGHT_RATIO` for non-sidebar columns instead of
  silently reusing the sidebar ratio (Greptile P2).
- e2e: tablet viewport bumped from 1024 → 700 (≥1024 is desktop, not
  tablet — the old viewport never rendered the tablet layout and
  every assertion timed out). Tests now also verify rendered panel
  proportions, not just the localStorage echo (CodeRabbit #2/#3).
- e2e helpers: throw on missing `.dv-sash` instead of returning `-1`
  (CodeRabbit #1); shared `openWideTask` extracted from three spec
  files (CodeRabbit #5); silent `return` in evaluate blocks
  replaced with `throw` for fail-fast (CodeRabbit #4).

* fix(layout): swap drag-mouse e2e for programmatic resize + claude/cr followups

Round 2 of PR review fixups:

- e2e: convert pane-resize-right/sidebar/edge-cases specs from
  `page.mouse` drag-by-delta to a programmatic `splitview.resizeView()`
  call. The mouse-drag approach was flaky in headless CI (5 chromium
  failures across shards 2-4); the programmatic path tests the same
  cap-enforcement and persistence contract without depending on
  pointer-events targeting through a 1px .dv-sash overlay.
- dockview-layout-setup: remove an unreachable guard in
  trackPinnedWidths — `rightIdx === 0 && sidebarVisible` cannot occur
  given the `sv.length < 2` early return (Claude).
- dockview-layout-setup: cancel any in-flight debounce timer in the
  setupLayoutPersistence disposer so a fire can't race with teardown
  and persist stale layout (CodeRabbit).
- constants: document why LAYOUT_SIDEBAR_RATIO and LAYOUT_RIGHT_RATIO
  are both 0.25 today — separate constants stay decoupled so a future
  tweak to one doesn't silently change the other (Claude).

* fix(layout): drop cross-env width propagation — defaults stay unchanged

User feedback: the initial sidebar width on a brand-new task should be
the same as it was before this PR (350px on typical viewports). The
plan's "propagate preferred widths across envs" feature changed that
in practice: after the first resize, every new task opened at the
resized width instead of the legacy default.

- Remove `getPinnedDefaults` / `setPinnedDefaults` helpers and the
  sessionStorage `kandev.dockview.pinned-defaults` slot.
- Drop the write-through in `setPinnedWidth` and the seed in
  `performBuildDefault`. `freshPinned` is back to `new Map()`, so a
  brand-new env always renders at the ratio-based default (same as
  before this PR, since `getPinnedWidth` already clamps the initial
  ratio to the legacy 350/450 hard caps).
- Per-env layout persistence still works via `setEnvLayout` — when a
  user resizes inside a task and switches back later, the width is
  restored. Only the cross-env *default* is no longer carried over.
- Remove e2e tests + helpers that exercised the propagation contract.
- Drop the flaky `rapid resizes persist across reload` edge test —
  too brittle around the debounce/beforeunload race.
- `LAYOUT_INITIAL_RATIO` introduced as the canonical name;
  `LAYOUT_SIDEBAR_RATIO` / `LAYOUT_RIGHT_RATIO` kept as deprecated
  aliases for backwards compatibility while sizing.ts dispatches.

* fix(layout): bump saved-layout storage keys to v2

Layouts saved by intermediate builds of this PR captured sidebar/right
widths beyond the legacy initial caps (when the larger runtime cap was
the only thing constraining serialized widths). Restoring those layouts
on the current build replays the over-wide widths, defeating the
"defaults stay the same" guarantee.

Bumping the storage key prefixes (`env-layout` → `env-layout-v2`,
`env-maximize` → `env-maximize-v2`, `dockview-layout-v1` →
`dockview-layout-v2`) invalidates legacy saves once on first open;
subsequent opens persist + restore under v2 normally. Existing users
lose stored column widths once and re-customize from defaults — a
one-time cost in exchange for the upgrade being clean.

* fix(layout): apply target env's widths after fast-path switch

Fast-path env switch (`tryFastEnvSwitch`) skips `fromJSON` for speed,
which means column widths carry over from the *outgoing* env. If a
user resized the sidebar to 480px in task A and then opens task B,
B inherits A's 480px sidebar — even with empty sessionStorage on
different dev-server ports, because the widths live in dockview's
in-memory grid state, not in storage.

Explicitly resize sidebar/right after the panel swap:
  - saved layout exists for target env → use its serialized sizes
  - no saved layout (brand-new env) → compute defaults via
    `getPinnedWidth` (legacy initial caps: 350 sidebar / 450 right)

* fix(layout): pass measured dims to fromJSON so widths don't grow on rescale

Even on a fresh dev instance with no prior storage, brand-new tasks
were opening with oversized sidebar/right widths. Root cause: applyLayout
fed `api.width` into toSerializedDockview, but `api.width` lags the live
container during the dockview mount sequence. fromJSON wrote a layout
sized for the stale width; the subsequent `api.layout(safeWidth, ...)`
in performBuildDefault's rAF rescaled the grid proportionally — and
without the old hard cap (350/450) clamping it, the sidebar grew past
its legacy default.

Pass the measured container dimensions through applyLayout into
toSerializedDockview so fromJSON's grid.width already matches the live
container. api.layout in the rAF is then a no-op, no rescale, and
sidebar/right open at exactly their legacy defaults.

Also applies to applyBuiltInPreset and applyCustomLayout for the same
flow.

* fix(layout): lock pinned column max width to current size, unlock on drag

The real reason brand-new tasks opened with oversized sidebar/right:
dockview's splitview rebalances pinned columns proportionally on every
`api.layout` call. After we relaxed setConstraints from the legacy
350/450 hard caps to viewport-proportional runtime caps (576/1344),
nothing clamped the rebalance — sidebar grew from 350 → ~450, right
from 450 → ~530 on the first ResizeObserver tick.

New invariant: pinned-column `maximumWidth` is locked to the column's
*current* width whenever the user is not actively dragging a sash. The
rebalance has zero room to grow.

- `applyLayout` / `applyLayoutFixups` set the lock as soon as fromJSON
  finishes — sidebar/right open at exactly their just-computed widths.
- `setupContainerResizeSync` re-applies the lock on every viewport
  ResizeObserver tick before and after `api.layout`.
- `setupSashDragCapToggle` listens for mousedown/mouseup on `.dv-sash`:
  on mousedown, widen the cap to the runtime viewport-proportional cap
  so the user can drag past the legacy default; on mouseup, snap the
  cap back to the new current width.

Also addresses Claude's latest review:
- caps.test.ts: rename "hits the 350px floor on roomy viewports" → "…
  when vw*0.3 falls below the minimum" (test name now matches assertion).
- dockview-resize.ts: drop the stale "pinned-defaults mirror" comment;
  guard the sidebar splitview index against the hidden-sidebar footgun.
- pane-resize-right.spec.ts: rename the reload test to mention the
  correct localStorage key (`dockview-layout-v2`).
- new `dockview-env-switch-pinned.test.ts` unit-tests applyPinned-
  ColumnSizes with a spy splitview — verifies sidebar/right are
  explicitly resized after a fast-path env switch.

* fix(layout): constrain all groups, loosen e2e resize cap, drop stale docs

Round of PR-review fixes:

- applier: `applyConstraintsToAllPanelGroups` replaces the previous
  first-only helper. The default right column has separate top + bottom
  groups; constraining only the first left the bottom group unbounded
  and let the column grow on rebalance via that group (cubic P2 +
  Claude regression).
- sizing: collapse `LAYOUT_SIDEBAR_RATIO` / `LAYOUT_RIGHT_RATIO`
  dispatch — they alias the same `LAYOUT_INITIAL_RATIO`, so the
  ternary was a silent no-op (Claude).
- sizing: doc — drop "widths seeded from pinned-defaults sessionStorage"
  reference; that feature was removed in fb3dbe4 (Claude).
- e2e/dockview-resize: the latest fix locks pinned-column maxWidth to
  current width, which clamps `sv.resizeView` in tests. Loosen the
  constraint to the same runtime cap the sash-drag handler uses on
  user mousedown — so cap-enforcement assertions still work end-to-end
  without burning the 10-minute CI timeout retrying clamped resizes.

* fix(layout): mirror viewportBound clamp in e2e test cap helper

Claude & cubic flagged that `resizeColumnViaSplitview`'s runtime-cap
computation skipped the `viewportBound(value, vw - 300)` step that
production caps go through. On narrow viewports (vw < ~1143px) the
helper's cap would exceed what dockview actually enforces, so
cap-clamp assertions would drift from real app behaviour.

Mirror the caps.ts logic exactly in the helper.

* fix(layout): pin-by-target, not lock-by-current — defeats the ratchet bug

My previous attempt (lock max=current width except during sash drag) was
fundamentally broken: any transient container shrink would lock the cap
at the smaller size, and dockview's proportional rebalance could never
restore the column. Under heavy ResizeObserver fluctuation on reload, the
sidebar marched all the way down to LAYOUT_PINNED_MIN_PX (180px).

New invariant: pinned-column max is the *runtime cap* (loose enough for
the user to drag past the legacy default), and a separate "target width"
is tracked per pinned column. After every `onDidLayoutChange` event the
column is force-restored to its target via `sv.resizeView`.

Target is updated only by explicit actions:
- `applyLayout` sets it to the computed default after `fromJSON`.
- `applyLayoutFixups` sets it to the just-restored width on saved-layout
  restore.
- `applyPinnedColumnSizes` (fast-path env switch) sets it to the saved /
  default width.
- The sash-drag handler sets it to the new width on mouseup.

`pinnedTargets` live in a new module `lib/state/layout-manager/pinned-targets.ts`.
`setPinnedTarget` / `getPinnedTarget` are exported from the layout-manager
barrel. An `enforcing` guard around `enforcePinnedTargets` prevents the
restore-via-resizeView from re-triggering itself.

E2E helper additions:
- `__persistDockviewLayout__` exposed on `window` (test seam) — calls the
  setupLayoutPersistence `persistNow` directly. `sv.resizeView` doesn't
  emit `onDidLayoutChange` in dockview 4.x, so the helper now force-flushes
  the layout after each programmatic resize. Without this, reload tests
  never saw a saved layout.
- `__setPinnedTarget__` exposed too so the helper can update the target
  after a programmatic resize, mirroring sash-drag mouseup.
- Dropped the brittle `data-panel-id` width assertion in the tablet
  persistence test; the localStorage round-trip is the persistence
  contract, and `react-resizable-panels`' internal DOM is version-dependent.

Local validation: all 15 layout e2e tests pass; full unit suite (2087)
green; format + lint + typecheck clean.

* fix(layout): pause target enforcement during sash drag + cleanup test seam

Three follow-ups from the latest review round:

- cubic P1: pause `enforcePinnedTargets` while the user is actively
  dragging a sash. Without this, an in-progress layout-change event
  during the drag would revert the in-flight resize before mouseup
  records the new target. The new `sashDragging` flag is set on
  mousedown over `.dv-sash` and cleared on mouseup.
- claude: clear `window.__persistDockviewLayout__` in the
  setupLayoutPersistence disposer so a remount can't be racing with a
  stale closure from the previous mount.
- claude: third unit test exercises the right column's saved-layout
  resize path (sv.length = 3 covering both pinned columns), now that
  the previous test bounded the loop at sv.length = 2 and only
  reached the sidebar.

* test(e2e): bump dockview-layout-v1 → v2 in plan-panel-indicator spec

The storage key was bumped from v1 → v2 in fb3dbe4 (drop cross-env
width propagation). The plan-panel-indicator spec was waiting for the
old `dockview-layout-v1` localStorage key to materialise after a
debounced save — that key is never written under v2, so the
waitForFunction always timed out.

* fix(layout): reset sashDragging on disposer + only track left-button drags

Two safety fixes for the module-scope `sashDragging` flag:

- claude: clear it in the setupSashDragCapToggle disposer. If the user
  starts dragging a sash and unmounts mid-drag (e.g. navigates away),
  the flag stayed `true` forever and `enforcePinnedTargets` would never
  fire again on the next mount.
- cubic P2: only set the flag on left-button mousedown. A right/middle
  click over a sash currently flipped it true, and the mouseup handler
  ignores non-left buttons — so the flag would stick and pause
  enforcement until a left mousedown→up cycle.

* fix(ui): preserve session mode selector state

* fix(ui): format fallback session mode labels
2026-05-24 11:26:56 +01:00
Carlos Florêncio 372779ad32 feat(preview): inspect mode with pin and area annotations (#917) 2026-05-24 11:21:50 +01:00
Carlos Florêncio 1395a7a416 feat(web): add Share to session tab context menu (#1050) 2026-05-24 10:50:28 +01:00
Carlos Florêncio b090a0157e feat(web): move automations entry above agents in settings sidebar (#1049) 2026-05-24 00:38:31 +01:00