Commit Graph

923 Commits

Author SHA1 Message Date
José Almeida 379230892b feat: brew install + npm sibling channels via OIDC trusted publishing (#806)
* chore: ignore local secret file

* feat(cli): replace self-update with package-manager-owned runtime resolution

The CLI no longer downloads runtime bundles from GitHub on first run. Instead:

- A new resolveRuntime() in apps/cli/src/runtime.ts resolves the bundle in
  three steps: KANDEV_BUNDLE_DIR env var (Homebrew wrapper, tests) → installed
  @kdlbs/runtime-{platform} npm package → cached download (only when
  --runtime-version is given explicitly).
- apps/cli/src/run.ts is split: launch logic separated from download logic.
  The download path stays for the explicit --runtime-version flag only.
- The --version flag now prints CLI semver (was: runtime tag selector). The
  old behavior moves to --runtime-version, documented as advanced/debug.
- The npm self-update prompt (apps/cli/src/update.ts) is removed entirely.
- apps/cli/package.json declares optionalDependencies for five
  @kdlbs/runtime-{platform} packages and engines.npm: ">=7" (required for
  optional-dep resolution during npx).
- Adds esbuild + a "bundle" script that produces dist/cli.bundle.js — a
  single-file CJS bundle with all Node deps inlined. The Homebrew formula
  uses this; the npm package keeps the unbundled dist/cli.js.

Tests: 130/130 passing. Bundle smoke-tested in a directory with no
node_modules to confirm tree-kill is correctly inlined.

* feat(release): unified vX.Y.Z release flow with brew + npm sibling channels

GitHub release artifacts become the canonical build output. npm and Homebrew
are independent sibling channels — both consume the same GitHub release
tarballs; neither depends on the other.

Workflow changes (.github/workflows/release.yml):

- Trigger is now workflow_dispatch only (maintainer-only, gated by repo write
  access). Inputs: bump dropdown (patch/minor/major) + dry_run checkbox.
- Single job graph orchestrates everything in one run:
  prepare (bump, PR, merge, tag) → build-web/build-cli → build-bundles (5
  platforms) → docker → publish-release → publish-npm + update-homebrew-tap.
- The prepare job inlines version bump, optionalDependencies sync, CHANGELOG
  generation, PR create + squash-merge, and tag push. Replaces what
  release-pr.sh used to do locally.
- Tag-push trigger removed; everything runs from the dispatch flow.

New scripts (called by the workflow):

- package-cli.sh: builds + esbuild-bundles the CLI for inclusion in release
  bundles (cli/bin/cli.js + cli/dist/cli.bundle.js + package.json).
- package-npm-runtime.sh: generates per-platform @kdlbs/runtime-* npm
  packages from release bundles. Sets npm os/cpu fields so npm 7+ skips
  non-matching platforms during npx kandev install.
- publish-npm.sh: verifies GitHub assets exist, downloads them, repackages,
  publishes all 5 @kdlbs/runtime-* packages + main kandev@X.Y.Z.
- update-homebrew-tap.sh: clones kdlbs/homebrew-kandev via SSH using the
  HOMEBREW_TAP_DEPLOY_KEY repo secret, generates Formula/kandev.rb pointing
  at the GitHub release assets, pushes directly to main.

Removed scripts:

- release.sh and release-pr.sh — both are redundant with the new workflow.

Required CI secrets:
- NPM_TOKEN: granular access token with publish access to kandev + @kdlbs/*
- HOMEBREW_TAP_DEPLOY_KEY: SSH private key for kdlbs/homebrew-kandev

* docs: brew install, runtime resolution, and GHA-driven release flow

- README.md: add Homebrew quick start (brew install kdlbs/kandev/kandev),
  update NPX docs to require npm 7+, document the three update paths.
- docs/cli.md: rewrite architecture diagram to show three-step runtime
  resolution. Replace --version <tag> docs with --version (CLI semver) +
  --runtime-version <tag> (advanced/debug). Remove KANDEV_NO_UPDATE_PROMPT.
- apps/cli/README.md: add Homebrew install path; document
  package-manager-owned updates.
- apps/cli/README_internal.md: rewrite to describe the npm package vs
  GitHub bundle artifact-shape distinction and the three-step resolver.
  Document the GHA-driven release UI (Run workflow + bump dropdown).
- AGENTS.md: add Release & Versioning Convention section describing the
  unified single-SemVer flow, the sibling channel model, and the GHA flow.

* fix(release): release-bundle bin/cli.js must require the esbuild bundle

The previous package-cli.sh copied apps/cli/bin/cli.js verbatim into the
release bundle. That file requires `../dist/cli.js` (unbundled), which
only works when node_modules is present alongside it.

In the GitHub release bundle (used by Homebrew and manual installs),
there is no node_modules — `require('tree-kill')` and `require('tar')`
inside dist/cli.js would crash at startup.

Now package-cli.sh writes a release-specific bin/cli.js that requires
`../dist/cli.bundle.js` instead. The bundled file has all Node deps
inlined via esbuild, so it runs standalone in the Cellar.

The npm package keeps its own bin/cli.js (in apps/cli/bin/) requiring
the unbundled dist/cli.js, since npm installs tree-kill etc. normally.

Caught while smoke-testing the release bundle locally with
KANDEV_BUNDLE_DIR — backend + web boot succeeded after this fix.

* feat(release): switch npm publishing to Trusted Publishers (OIDC)

The previous flow required an NPM_TOKEN secret. Local testing with that
token failed with EOTP because the granular access token still required a
2FA OTP on publish despite the account-level setting change. npm now
recommends Trusted Publishers (OIDC) over long-lived tokens.

Workflow change (release.yml):
- publish-npm job declares `permissions: id-token: write` so GitHub Actions
  can mint OIDC tokens.
- Removes NODE_AUTH_TOKEN env var. The npm CLI auto-detects the OIDC
  environment and exchanges the GitHub OIDC token for a short-lived
  npmjs.com publish credential.
- Comment block updated to reflect the new auth model. NPM_TOKEN is no
  longer listed in required secrets (already deleted from repo secrets).

Script change (publish-npm.sh):
- Updates `npm publish` calls to include `--provenance` so each published
  package ships with a signed attestation linking it back to this commit
  and workflow run.
- Header comment explains the OIDC auth model.

Setup required on npmjs.com (per package, before first OIDC publish):
For each of the 6 packages — kandev plus @kdlbs/runtime-{linux-x64,
linux-arm64,darwin-x64,darwin-arm64,win32-x64} — go to the package's
"Settings → Publishing access" and add a Trusted Publisher pointing at
this repo (kdlbs/kandev), workflow filename release.yml, and (optionally)
an environment.

* fix(release): pin optionalDependencies to bootstrap version in committed source

CI was failing because apps/cli/package.json declared optionalDependencies
at 0.16.0 but only 0.0.0-bootstrap exists on npm for those packages. The
lockfile couldn't resolve, and `pnpm install --frozen-lockfile` rejected
the working tree.

Pin optionalDependencies to 0.0.0-bootstrap in the committed source so the
lockfile resolves cleanly. The release workflow now bumps them to the real
version inside publish-npm.sh, just before publishing main kandev — at
which point the matching @kdlbs/runtime-*@VERSION tarballs have already
been published earlier in the same step. This avoids the chicken-and-egg
where the prepare job tried to bump optional deps to a version that didn't
yet exist on npm.

Workflow changes:
- prepare job: only bumps the main package version, not optional deps.
- publish-npm.sh: rewrites optionalDependencies to $VERSION right before
  the main `npm publish`, after the 5 runtime packages have been published.

The published kandev@X.Y.Z still has its optionalDependencies pinned to
matching @kdlbs/runtime-*@X.Y.Z. Only the local source uses the bootstrap
pin for development convenience.

* fix: address PR review comments on release flow + runtime resolution

PR reviewers (Greptile, Claude, CodeRabbit) flagged six concrete issues.
Each is addressed below.

Critical:
- publish-npm.sh: previously exited 0 even when runtime packages failed to
  publish, which would leave kandev@VERSION on the registry pointing at
  @kdlbs/runtime-*@VERSION that never got published. Now: capture full npm
  output on failure, distinguish "already published" (idempotent skip)
  from real failures, abort before publishing main kandev if any runtime
  fails.
- release.yml: build-bundles referenced needs.prepare.outputs.tag without
  declaring prepare in its needs array. Static analysis flagged this.
  Added prepare to the needs list.

Major:
- update-homebrew-tap.sh: the formula's write_env_script only injected
  KANDEV_BUNDLE_DIR. run.ts:174 reads KANDEV_VERSION to display the
  running version in startup logs; without it Homebrew users would see
  "release: (env)" instead of "release: 0.17.0". Pass KANDEV_VERSION:
  version.to_s through the wrapper.
- runtime.ts: the catch {} block silently swallowed validateBundle errors,
  hiding "package installed but corrupt" cases behind the generic
  "no runtime found" message. Split the lookup so MODULE_NOT_FOUND falls
  through, but validation errors propagate.
- run.ts: the --runtime-version code path skipped validateBundle, missing
  the file-existence checks that the npm/env paths get. Added it.

Minor:
- release.yml: workflow-level permissions defaulted to write for everyone.
  Tightened to read-only at the workflow level; jobs that need writes
  (prepare, docker, publish-release) declare them explicitly.
- args.test.ts: added missing tests for --runtime-version with no value
  and --runtime-version followed by another flag, parallel to the
  existing --port tests.

Tests: 132 passing (was 130; +2 new).

* fix: address second-round PR review (cleanup traps, host-key pinning, supply chain)

Latest review (Claude + Greptile) flagged three security/cleanup items
on top of the previous fix commit. All three addressed below.

publish-npm.sh:
- Add `trap 'rm -rf "$WORK_DIR"' EXIT` immediately after `mktemp -d` so
  the tmpdir is cleaned up even when `pnpm build` or `npm publish` fails
  partway through (set -e would otherwise abort before the explicit
  rm at the end).
- Remove redundant `pnpm build` before `npm publish` — the `prepublishOnly`
  script in package.json already runs the build.

update-homebrew-tap.sh:
- Combine `cleanup_ssh` + WORK_DIR cleanup into one EXIT trap so `git clone`
  / `git push` failures don't leak the tmpdir.
- Pin GitHub's published SSH host keys (ed25519, ECDSA, RSA) into a temp
  `known_hosts` file instead of using `accept-new` + `/dev/null`. This
  closes the "trust any host key on first connect" gap. The pinned keys
  come from https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints.

release.yml:
- Replace the curl|tar git-cliff install with `orhun/git-cliff-action@v4`
  (already used in publish-release). The action pins to a digest, so we
  no longer need to verify a tarball checksum manually. Removes a
  supply-chain attack surface where a tampered git-cliff binary could run
  during `prepare` (which has contents:write + pull-requests:write).

* revert: keep curl install for git-cliff, add sha512 verification instead

The previous commit (18b2a5c) replaced our `curl | tar` install with
orhun/git-cliff-action@v4 under the banner "supply chain". On reflection
that swap doesn't actually improve anything:

- @v4 is a moving tag, not a digest pin — same trust as a tagged curl URL.
- Both depend on trusting the same maintainer (orhun).
- The action adds a third-party step we don't audit.

The legitimate concern from the review was "no integrity verification on
the downloaded tarball." Address that directly: pin the asset version,
embed its published sha512, and abort if the download doesn't match.
The hash for v2.6.1's x86_64-linux-gnu tarball came from
https://github.com/orhun/git-cliff/releases/download/v2.6.1/<asset>.sha512.

This restores the original setup with a real integrity check and one
fewer external dependency.

* fix: address remaining PR nits (env restore, sha256 download dir)

runtime.test.ts: drop the redundant `delete process.env.KANDEV_BUNDLE_DIR`
in afterEach — `process.env = { ...origEnv }` already restores the
original environment. The redundant delete would silently un-set the var
if a developer had it in their shell, leaking test side effects across
suites.

update-homebrew-tap.sh: fetch_sha256 now downloads into $WORK_DIR instead
of /tmp/. The EXIT trap covers WORK_DIR, so the .sha256 files are cleaned
up automatically. Avoids leaking 5 tmpfiles per release run on long-lived
runners.

* fix: address third-round PR comments

- update-homebrew-tap.sh: Homebrew formula was calling
  `bin.write_env_script` on the bin directory with target `cli/bin/cli.js`,
  which would create the wrapper at `$HOMEBREW_PREFIX/bin/cli.js` (named
  after the target's basename) instead of `$HOMEBREW_PREFIX/bin/kandev`.
  Result: `brew install kandev` would have produced `command not found`.
  Use `(bin/"kandev").write_env_script(...)` to name the wrapper
  explicitly. Caught by Claude as a P0 blocker.

- publish-npm.sh: main `kandev` publish lacked the EPUBLISHCONFLICT
  idempotency handling that the runtime-package loop has. If publish-npm
  was re-run after a partial failure (e.g. the runtime packages succeeded
  but the main package failed and was then manually published), the
  re-run would fail on the main package even though the version was
  already on the registry. Now: capture output, treat
  "already published" as success, fail loudly with full output on real
  errors. Caught by Greptile as P1.

* refactor(release): direct push to main instead of PR-and-merge dance

The prepare job was opening a release branch, creating a PR, and
immediately squash-merging it via gh CLI. That pattern was carried over
from the old release-pr.sh, but in this workflow it earns nothing:

- main has no branch protection, so direct push is allowed.
- The PR was force-merged in the same step (no `--auto`, no waiting for
  required checks), so it provided no pre-merge validation.
- Discoverability is fine without a PR — git tag, GitHub release, workflow
  run, and main commit are all visible.

The PR-and-merge sequence had ~5 GitHub API roundtrips, each a potential
failure point, plus added 30+ lines of YAML and required pull-requests:
write on the job. Replaced with a straight-line commit + tag + push:

  git fetch origin main && git checkout main && git reset --hard origin/main
  ... bump pkg.json, regen CHANGELOG, npm install ...
  git add ... && git commit && git tag -a && git push origin main "$TAG"

Job permissions tightened to contents: write only.

Race condition note: if main advances between fetch and push, the push
fails non-fast-forward — same outcome as the old PR pattern, where the
auto-merge would have failed. For workflow_dispatch releases with the
maintainer actively driving, the race is essentially never going to
happen, and the recovery (re-run the workflow) is the same.

The dry-run path still bumps + regenerates CHANGELOG inside the runner
so the maintainer can verify the computed values look right, just
without committing or pushing anything.

* chore(release): drop verbose comment about direct-push rationale

* docs: drop 'no first-run download' note from user-facing docs

The phrasing only makes sense to readers who knew the previous model
required a first-run download. New users have no baseline to compare
against, so it adds noise. Removed from docs/cli.md and apps/cli/README.md
(which renders on npmjs.com). Kept in apps/cli/README_internal.md as a
design note for contributors.

* Revert "chore: ignore local secret file"

The /secret entry was added defensively after the bootstrap test, but it
clutters .gitignore with a project-specific path that nobody else needs.
Drop it; secrets stay out of the repo by other means (don't commit them).

* fix: address third-pass review (stale workflow comments + missing test)

release.yml:
- The header comment block and dry_run input description still referenced
  the PR-and-merge step that was removed in 53c2e45. Updated both to
  describe the direct-commit flow.

runtime.test.ts:
- The runtime resolver's npm-package branch (step 2 — the primary path
  after npx kandev@latest or npm install -g) had no positive coverage. In
  the test env, require.resolve for @kdlbs/runtime-* throws
  MODULE_NOT_FOUND, so the existing tests only exercised step 1 (env var)
  and step 3 (cache via --runtime-version), plus the no-runtime-found
  fallthrough.

  Added two tests using vi.spyOn on Module._resolveFilename to point at a
  fake bundle inside tmpDir:
    - happy path: installed npm package resolves to source=npm with the
      right bundleDir
    - corrupt-bundle path: validateBundle errors propagate (rather than
      being swallowed and falling through to "no runtime found")

  These cover the real-world scenarios users will hit on either install
  channel.

Tests: 132 → 134.

* fix(release): push commit + tag atomically

Without --atomic, git push can succeed for the tag ref and fail for the
main ref on a non-fast-forward, leaving an orphaned tag at the pre-bump
commit. The orphan then trips the 'Tag already exists on origin' guard
on the next re-run, requiring manual tag deletion to unblock.

--atomic makes the multi-ref push succeed-or-fail as a unit.

Caught by Greptile as P1.

* refactor(cli): drop runtime.ts step 3 — cache fallback was unreachable

resolveRuntime's runtimeVersion parameter and cache-fallback step were
dead code from production's perspective. The --runtime-version path is
handled entirely in run.ts (findCachedRelease + downloadRuntimeVersion +
findBundleRoot + validateBundle), and run.ts only ever called
resolveRuntime() with no argument. The parameter and step 3 only existed
because tests exercised them.

Two parallel "compute cache dir" implementations (runtime.ts:65 and
run.ts:157) were a drift hazard if the cache layout ever changes.

Changes:
- Drop the runtimeVersion parameter from resolveRuntime.
- Drop the cache step from runtime.ts entirely; remove the unused
  CACHE_DIR + findBundleRoot imports.
- Narrow RuntimeSource from "env" | "npm" | "cache" to "env" | "npm",
  and drop the now-unused tag field from ResolvedRuntime.
- Remove the three "cache fallback" tests from runtime.test.ts. The
  --runtime-version cache lookup is still covered by run.test.ts via
  findCachedRelease tests.

Tests: 134 → 131 (three deleted tests are obsolete, the production
behavior they were verifying is now covered by run.test.ts).

* chore(test): drop dead mock setup left over from runtime.ts step 3 removal

After feb7c5a removed the cache fallback from runtime.ts, the test file
had two dangling artifacts:

- The vi.mock("./constants", ...) block + the mockCacheDir holder + the
  mockCacheDir.value = tmpDir assignment in beforeEach. runtime.ts no
  longer imports anything from ./constants, so the mock was a no-op
  that would mislead readers tracing why constants are mocked here.
- The PLATFORM = "macos-arm64" constant was unused — platform
  determinism is already enforced by the vi.mock("./platform", ...)
  block one section above.

Caught by Claude and the github-code-quality bot.
2026-05-05 00:43:34 +01:00
Carlos Florêncio b6a274183b release: app v0.39, cli 0.17.0
release / build-web (push) Has been cancelled
release / docker (push) Has been cancelled
release / build-bundles (aarch64-linux-gnu-gcc, arm64, linux, ubuntu-latest, linux-arm64) (push) Has been cancelled
release / build-bundles (amd64, darwin, macos-14, macos-x64) (push) Has been cancelled
release / build-bundles (amd64, linux, ubuntu-latest, linux-x64) (push) Has been cancelled
release / build-bundles (arm64, darwin, macos-14, macos-arm64) (push) Has been cancelled
release / build-bundles (x86_64-w64-mingw32-gcc, amd64, windows, ubuntu-latest, windows-x64) (push) Has been cancelled
release / publish-release (push) Has been cancelled
v0.39
2026-05-04 22:24:54 +01:00
José Almeida a4e0fc0452 feat: attribute cross-task agent messages with a sender badge (#819)
* feat(orchestrator): carry sender_task metadata through user message paths

Add WithSenderTask builder to UserMessageMeta and a metadata-aware
QueueMessageWithMetadata variant on the message queue. The drain path
in event_handlers_agent merges queued metadata into the recorded user
message so attribution survives the queue → DB transition.

* feat(mcp): attribute message_task_kandev calls to the sending agent

The MCP server inside agentctl now injects sender_task_id and
sender_session_id from its own server context. The backend handler
validates the sender (rejecting missing IDs, self-messages, and unknown
tasks), looks up the sender title, wraps the prompt in a <kandev-system>
attribution block, and propagates structured metadata across all three
delivery paths (queue, created-session, record+prompt). The wrapped
content lets the receiving agent identify the peer both live and on ACP
session resume; the existing sysprompt strip pipeline hides the wrapper
from the UI.

* feat(web): render sender-task badge on cross-task agent messages

User messages whose metadata carries sender_task_id now render a
clickable purple badge above the bubble, linking to the source task.
The badge live-resolves the sender's title from the kanban store and
falls back to a greyed snapshot when the task isn't loaded
(cross-workspace, deleted, etc.). Adds a non-subscribing useTaskById
selector so badges don't fan out WS subscriptions per message.

* test(e2e): cover cross-task agent message attribution

Eight scenarios driven through the mock-agent's MCP script directive:
queue path, prompt path, self-message rejection, unknown-target error,
badge link target, live title re-resolution after rename, kandev-system
wrapper preservation in raw_content, and prompt bodies containing their
own kandev-system tags. Adds an updateTaskTitle helper to ApiClient.

* fix: address CodeRabbit + Greptile P1 findings on PR #819

- requeueMessage now forwards queuedMsg.Metadata via QueueMessageWithMetadata
  so sender attribution survives transient delivery failures and retries.
- CREATED-session branch in handleMessageTask records the user message AFTER
  StartCreatedSession succeeds, so a launch failure no longer leaves an
  orphaned attributed chat row.
- SenderTaskBadge: collapse identical displayTitle/fullTitle locals.
- E2E: extract waitForTargetIdle helper; replace the 1.5s raw sleep in the
  collision-check test with the same poll the rest of the suite uses.

* fix: address Claude review suggestions on PR #819

- wrapAgentMessage strips </kandev-system> from the embedded sender title
  before formatting. Without this, a title containing the closing tag
  would short-circuit the non-greedy strip regex and leak the attribution
  tail into the visible UI bubble. Metadata snapshot keeps the original
  title so the badge still displays it.
- Add a regression test covering the malicious-title case.
- Document the deliberate cross-workspace messaging policy on the sender
  lookup so future readers don't add a workspace-scope check (Q13 of the
  feature plan locked this as intentional).
2026-05-04 19:30:10 +01:00
Carlos Florêncio cb0feea650 fix(web): dedup topbar PR button against auto-shown PR panel (#812) 2026-05-04 19:20:37 +01:00
Carlos Florêncio c042050469 fix: stabilize task switch flow and session recovery (#818) 2026-05-04 18:53:33 +01:00
Carlos Florêncio 39b9369ae1 fix: suppress spurious task-failed toasts on resume and reconnect (#814) 2026-05-04 17:58:59 +01:00
João Salavisa 5c5e7bf6a7 fix(changes-panel): scope commits/diff to live branch divergence; flatten single-repo (#816)
* fix(changes-panel): scope commits/diff to live branch divergence; flatten single-repo

Two bugs in the COMMITS panel made it surface commits and file changes
that were already on main:

1. The commit list and the cumulative diff both anchored to a stale base.
   Commit list used `git merge-base HEAD <local-branch>` and the file diff
   used the session's stored base SHA captured once at session start. On
   long-lived worktrees the local main ref lags far behind origin/main, so
   the merge-base lands on an old SHA; once the agent merges main back in,
   the stored base is also stale. Both end up sweeping in dozens of main
   commits as if they were the branch's work.

2. `git log <base>..HEAD` follows both parents of a merge commit by
   default, surfacing main commits brought in via merges from main.

Fixes:
- agentctl computes merge-base against `origin/<target_branch>` (with a
  local-ref fallback for unfetched/local-only branches), and uses that
  for both the commit log and the cumulative diff. Mirrors GitHub's
  three-dot PR diff semantics — anchor to live divergence with the
  upstream, not a session-start snapshot.
- `git log` now passes `--first-parent` so only the branch's own line of
  work plus its merge commits show up; commits brought in via merges from
  main are excluded.

Frontend: drop the per-repo "REPOSITORY" sub-header in the COMMITS panel
for single-repo workspaces. CommitsRepoGroup gains a `showHeader` prop;
when the workspace has one untagged group the section renders flat with
the per-repo Push / PR (and Stage all / Commit / Unstage all) buttons
lifted into the section header. Multi-repo rendering unchanged.

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

* fix: address PR review feedback

- Scope --first-parent to the divergence-range path only (Greptile P1).
  The flag is wrong for open-ended history calls — future activity
  widgets etc. need the full graph.
- Log empty merge-base case in cumulative diff (Greptile P2). Silent
  fallback to stored base was invisible during diagnostics.
- Rename TestRunGitCumulativeDiffForRepo_PrefersOriginRef →
  TestComputeMergeBase_CorrectAnchorForCumulativeDiff (Claude). Test
  exercises computeMergeBase, not the runGitCumulativeDiffForRepo
  conditional; new name reflects what it actually proves.
- Add TestGetLog_NoBaseReturnsFullGraph to lock in the --first-parent
  scoping.

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

* fix: address PR review round 2

- Drop dead ActionButtonsSection from changes-panel-timeline.tsx (unused
  export, no consumers anywhere). Brings the file from 640 → 516 lines,
  comfortably under the 600-line TS limit Claude flagged.
- Extract isSingleRepoGroup helper into lib/group-by-repo.ts and use it
  in all three sites (CommitsSection, FileListBody, FileListSection) so
  single-repo detection has one source of truth.

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-04 17:28:04 +01:00
João Salavisa b30933240b fix: sanitize multi-repo worktree dirs and polish task-create chip dropdown (#815)
* fix: sanitize multi-repo worktree dirs and polish task-create chip dropdown

Backend: org-prefixed Repository.Name like "owner/repo" was used verbatim
as the worktree subdirectory under the task root, nesting one level too
deep and breaking agentctl's sibling-based multi-repo detection in
scanRepositorySubdirs. Sanitize to a single path-safe segment so all
worktrees land as siblings of the task root.

Web: the multi-repo chip dropdown built its own option list and dropped
the path Badge plus search filtering that the legacy header dropdown
shipped. Restore parity (name + path), widen the popover (288 → 360 px),
stack name and full path on two lines so neither has to truncate
aggressively, hide the Badge for workspace repos without a local clone,
and use a path-aware scorer that floors weak fuzzy matches so unrelated
paths stop surfacing for short queries.

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

* fix: address PR review feedback

- Add ErrInvalidRepoName sentinel and use it in createInTaskDir when
  RepoName sanitizes to empty, replacing the misleading reuse of
  ErrTaskDirRequired (Claude/Greptile).
- Reuse repoDirHyphenRun in SanitizeForBranch instead of recompiling the
  regexp per call (CodeRabbit nitpick).
- Document the SanitizeRepoDirName collision edge case in the doc
  comment (Greptile).
- Extract scoreRepo to lib/utils/repo-filter.ts and add unit tests
  pinning the 0.4 fuzzy-match threshold (Claude).

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-04 17:22:28 +01:00
João Salavisa 96c68a0af9 fix(backend): return mcp message_task once dispatched, not after target turn ends (#817)
* fix(backend): return mcp message_task once dispatched, not after target turn ends

The MCP message_task_kandev tool was synchronously waiting for the target
session's entire turn to complete before returning, even though its
description advertises a fast dispatch status. For idle target sessions,
the call would hang for the full duration of the agent's response (with
no upper bound — waitForPromptDone has no timeout).

Threads a dispatchOnly flag from the MCP handler down through
PromptTask → executor.Prompt → PromptAgent → SendPrompt. When set,
SendPrompt returns once agentctl.Prompt accepts the prompt instead of
blocking on the agent's complete event. Stale completion signals from
prior dispatch-only prompts are drained at the start of SendPrompt so
they don't poison the next waiting call.

* fix: address PR review feedback

- Replace time.Sleep with channel-based wait for WS connection in new
  SendPrompt tests, per CLAUDE.md (channel sync over time.Sleep for
  non-subprocess tests).
- Drop redundant Warn that logged the remapped sentinel after the
  original error was already logged by the preceding Warn.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-04 17:17:45 +01:00
Carlos Florêncio 22c8baf015 fix(backend): correct task_environments migration order for older DBs (#811) 2026-05-04 09:34:17 +01:00
Carlos Florêncio b01e6abc06 fix: retry CLI passthrough launch without resume flag after fast-fail (#810) 2026-05-04 08:45:20 +01:00
Carlos Florêncio d4f6d89e3f refactor(web): move Configuration Chat Agent to utility agents page (#809) 2026-05-04 07:47:35 +01:00
Carlos Florêncio 7ce2e24150 feat(backend): add 10 ACP agents, set_config_option, auth_required flow (#807) 2026-05-04 07:46:56 +01:00
João Salavisa a77df053a6 refactor(web): drop redundant VCS split button from task top bar (#804)
* refactor(web): drop redundant VCS split button from task top bar

All git operations (commit, push, pull, rebase, merge, create PR,
force push) are reachable from the Changes panel — its timeline
exposes stage/commit and the per-section action row provides
push/force-push/create-PR, while the panel header carries the
pull/rebase/merge dropdown. The session command palette mirrors
the same set for keyboard users. The expanded review dialog keeps
its own VcsSplitButton because the changes timeline is hidden
behind the modal there.

Also removes the now-orphaned 'required' overflow flag (the VCS
item was its only caller) and the e2e helper + spec that targeted
the removed primary-action button.

* test(e2e): drop task-topbar-overflow spec relying on removed VCS button

The 1100px viewport test forced overflow by counting on the VCS button's
width; with VcsSplitButton gone the scenario no longer holds. Overflow
priority logic is already covered by topbar-action-overflow.test.ts.

Co-authored-by: João Salavisa <jcfs@users.noreply.github.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: João Salavisa <jcfs@users.noreply.github.com>
2026-05-04 00:53:21 +01:00
Carlos Florêncio 2732c101d9 fix(web): close tooltips on popover close and refine branch chip UX (#808) 2026-05-03 22:45:52 +01:00
Carlos Florêncio cc934adb85 fix: make executors_running the single source of truth for agent_execution_id (#799) 2026-05-03 22:17:23 +01:00
João Salavisa a59909ca5a fix(jira): use shared prompt template with placeholder autocomplete (#801)
* fix(jira): use shared prompt template with placeholder autocomplete

Default prompt for the JIRA watcher now lives in
config/prompts/jira-issue-watch-default.md (loaded via promptcfg.Get),
matching how the GitHub issue/PR-review watchers source their defaults.
The watch dialog swaps the plain Textarea for the ScriptEditor used by
the GitHub dialog so users get {{...}} autocomplete, and the inline
hardcoded default string is gone from both backend and frontend.

* fix(jira): treat whitespace-only stored prompt as empty on hydrate

CodeRabbit caught that w.prompt || DEFAULT keeps a stored "   " value,
which canSave then rejects — dialog reopens in an unsavable state. Fall
back to the default whenever the trimmed value is empty.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-03 20:48:10 +01:00
José Almeida b2dcd29818 fix(web): tab session bugs — primary star drift + tab close re-creation (#800)
* fix(web): preserve primarySessionId across kanban.update broadcasts

The kanban.update WS handler rebuilt kanban.tasks without
primarySessionId / primarySessionState, wiping values set by
task.updated. After any board refresh the primary star vanished and
selectTaskWithLayout fell into the slower async fallback path. Move
task building inside setState so existing values are preserved in both
single and multi snapshots.

* fix(web): prevent deleted session panel from being re-created

handleDelete called removeTaskSession before containerApi.removePanel,
which let useAutoSessionTab re-run with effectiveSessionId still
pointing at the deleted session and re-create its panel. The
setupChatPanelSafetyNet had a matching gap — it re-added a panel for
activeSessionId without checking the session still existed.

Switch the active session (or clear it) before removeTaskSession so
effectiveSessionId updates first. Add guards to useAutoSessionTab and
the safety net so neither creates a panel for a session that is no
longer in the store.

* test(web): add session tab management regression suite

Cover the three bugs fixed in this branch end-to-end: deleting a
non-active session keeps it gone, deleting the active session switches
focus to the remainder, deleting then immediately switching tasks does
not resurrect the tab, and the primary star survives both a
kanban.update broadcast (triggered via apiClient.moveTask) and a
task-switch round trip.

* fix(web): hand off deletion to newest remaining session, document multi-snapshot fallback

- session-tab.tsx: sort remaining sessions by started_at DESC and
  pick the newest, instead of relying on the unspecified store ordering.
- kanban.ts: comment the multi-snapshot primarySessionId fallback so
  the double lookup does not look like redundancy.

Both per Claude review feedback on #800.

* fix(web): preserve explicit-null primary, abort delete on WS failure

- kanban.ts: switch the multi-snapshot fallback from `??` to an
  explicit `=== undefined` check. An explicitly-cleared null primary
  must NOT be replaced by a stale snapshot value, only an absent key.
- session-tab.tsx: wsAction now returns a boolean; handleDelete bails
  out before mutating the store / dockview when the backend
  session.delete request fails. Prevents client/server desync from a
  transient WS failure.
- kanban.test.ts: add regression covering the null-vs-undefined merge.

Per CodeRabbit and Greptile review on #800.

* style(web): drop redundant .slice() in session deletion sort chain

filter() already returns a fresh array, so the subsequent sort() does
not mutate shared store state. Per Greptile review on #800.
2026-05-03 17:32:29 +01:00
Carlos Florêncio baaf7d593a feat(web): polish workbench topbars and task-create dialog (#792) 2026-05-03 16:15:28 +01:00
João Salavisa e9a7869463 refactor(web): drop dead taskPRs loading state and unused removeTaskPR (#791)
* refactor(web): drop dead taskPRs loading state and unused removeTaskPR

The taskPRs.loaded/loading fields were written but never read — useWorkspacePRs
uses its own fetchedRef for fetch-once gating instead. removeTaskPR was defined
but never called. Removing all three avoids a footgun in multi-repo tasks where
removeTaskPR would have wiped every repo's PR state at once.

* refactor(web): use plain deepMerge for taskPRs hydration

taskPRs no longer carries loading/loaded fields, so the mergeWithLoading helper has nothing to preserve. Switching to deepMerge makes the intent explicit.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-03 12:00:22 +01:00
João Salavisa 526039d1c1 docs: add integrations banner to README (#790)
docs: add integrations banner section to README

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-03 10:45:05 +01:00
João Salavisa bb36cb9e01 refactor: move integrations to top-level settings with install-wide configs (#787)
* refactor: move integrations to top-level settings with install-wide configs

Jira and Linear configurations are now install-wide singletons rather than
per-workspace duplicates, and the GitHub/Jira/Linear settings pages live
under /settings/integrations instead of being nested inside each workspace.
Issue and PR watchers stay per-workspace via a workspace switcher inside
each integration page. Backend ships one-shot migrations that promote the
most-recently-updated row and copy its secret onto the new global key.

* fix: address review feedback on integrations refactor

Fix migration crash on installs whose jira_configs predate the auth-health
columns by selecting only guaranteed-present legacy columns and falling back
to defaults for the rest. Cover the empty-legacy-table and pre-health-columns
upgrade paths with new store tests.

On the frontend, refactor useIntegrationEnabled to take string parameters
instead of an inline options object so getSnapshot stays referentially stable
across renders, and stop dispatching a misleading no-op sync event when
localStorage.setItem fails in private mode.

* fix: hydrate workspace list on integration settings pages

The integration pages wrapped their content in a fresh StateProvider, which
created a nested store scope with an empty initial state and shadowed the
settings layout's hydrated workspace list. WorkspaceScopedSection then saw
zero workspaces and rendered the "Create a workspace to configure this
integration" empty state even when the user had workspaces.

Drop the redundant StateProvider from the jira and linear pages so they share
the layout's store. The github page switches to StateHydrator so it can still
seed the GitHub OAuth status without resetting the rest of the store.

* refactor(integrations): flatten watcher tables, pick workspace in create dialog

Hiding watchers behind a workspace switcher made the list invisible at a
glance — a user with multiple workspaces had to flip between each one to
see what was configured. Replace the switcher with a flat table that lists
every watch across every workspace, with a Workspace column for context, and
move workspace selection into the create dialog so the user picks once when
the watcher is born.

Backend: jira list-issue-watches and github list-review-watches /
list-issue-watches accept the workspace_id query param as optional; when
omitted, the corresponding store ListAll* method returns rows across every
workspace. Per-row mutations still require workspace_id as the IDOR guard.

Frontend: useReviewWatches / useIssueWatches / useJiraIssueWatches gain a
three-state contract — string for one workspace, undefined for all
workspaces, null to skip fetching. Watch tables grow an optional
showWorkspace column. Watch dialogs accept an optional workspaceId prop;
when absent, the dialog renders a workspace dropdown for the create flow
(disabled when editing existing rows so refs aren't orphaned). Github
review-watch-dialog crossed the 600-line lint cap so the prompt editor
moved to review-watch-prompt-field.tsx.

* fix(integrations): make watcher step dropdown reactive across workspace switches

Switching to a workspace whose workflows had to be fetched left the workflow
step dropdown stuck — the user could pick a workflow but the step Select
either showed the previous workflow's steps or appeared inert. The cause was
the per-dialog useWorkflowSteps hook deferring its empty-state reset via
Promise.resolve().then(() => setSteps([])) to dodge a setState-in-effect
lint rule, which let stale steps survive into the next render and gave Radix
nothing to anchor the popover to during the in-flight fetch.

Hoist the hook into a shared useWorkflowSteps that resets via React's
official setState-during-render pattern, exposes a loading flag, and returns
a stepPlaceholder helper so the Select can render "Loading steps…" or "No
steps in this workflow" instead of an empty popover. The Step Select is now
also disabled while loading or when there are no steps, making the state of
the dropdown unambiguous.

* fix: address PR review feedback on integrations refactor

Backend:
- linear migration: add column-presence guard mirroring the Jira fix so
  installs that upgraded from the original Linear schema (without org_slug
  / last_checked_at / last_ok / last_error) don't crash startup with
  "no such column"; add TestStore_MigrateLegacyPerWorkspaceTable_PreHealthColumns
- jira/handlers.go: drop the now-unused errMsgWorkspaceIDRequired constant
  that was failing golangci-lint
- jira/mock_controller_test.go (new): cover setAuthHealth happy-path and
  invalid-JSON-rejection so the singleton-shaped payload is locked in

Frontend:
- useIntegrationAvailable: gate the auth-health probe on loaded && enabled
  so disabled integrations don't poll /config every 90s
- use-workflow-steps: initialize loading to !!workflowId so edit-mode opens
  show "Loading steps…" instead of "No steps in this workflow" before the
  first fetch lands
- use-workflow-steps.test.ts (new): cover the empty/non-empty workflowId,
  workflow switch, fetch error, and stepPlaceholder branches
- use-linear-enabled.test: tighten the legacy-key migration assertion to
  pin the migrated value rather than just verifying key cleanup

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-03 10:22:57 +01:00
João Salavisa 9e8e9d7dde fix(web): retry session commits fetch when workspace not ready (#789)
* fix(web): retry session commits fetch when workspace not ready

The COMMITS section dropped commits to "+0 -0" when the initial
session.git.commits fetch landed before agentctl was recovered: the
backend returned ready:false with an empty list, the hook stored [],
and never refetched — leaving mergeCommits to fall back to PR data
(which has stats=null from /pulls/{n}/commits).

* fix(web): address review feedback on commits retry

- Keep loading:true while a retry is scheduled (Greptile/Claude): the
  finally block was unconditionally resetting loading to false, leaving
  consumers seeing { loading: false, commits: [] } during the retry
  window — exactly the misleading state this hook avoids.
- Cancel the pending retry on disconnect (CodeRabbit): added
  connectionStatus to the cleanup effect deps so a queued retry
  doesn't fire against a disconnected WS client.
- Added a regression test for the loading-stays-true behavior.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-03 09:38:54 +01:00
João Salavisa 5b7760e797 fix: focus task name on create dialog open (#788)
* fix: focus task name on create dialog open

* fix: guard task-name focus effect to first truthy transition

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-02 23:47:19 +01:00
José Almeida 32f098a6fc feat: show question icon only for pending input (#782)
* fix: show question icon only for pending input

* fix: address pending input review feedback

* fix: reduce pending input sidebar complexity

* fix: address clarification review comments

* test: cover pending clarification hook
2026-05-02 23:01:21 +01:00
João Salavisa eee547d891 refactor(handlers): use GetOrEnsureExecution for workspace ops (#786)
* refactor(handlers): use GetOrEnsureExecution for workspace ops

Per CLAUDE.md, workspace-oriented handlers should use GetOrEnsureExecution
so they survive backend restarts. Two git ops in this file (wsGitCommits,
wsCumulativeDiff) already followed this pattern; the shared helper and the
shell.subscribe handler did not.

Changes:
- git_handlers.getAgentCtlClient: now takes ctx and uses GetOrEnsureExecution.
  Propagates to all 14 git ops routing through the helper (pull, push, rebase,
  merge, abort, commit, stage, unstage, discard, createPR, revertCommit,
  renameBranch, reset, commitDiff).
- shell_handlers.wsShellSubscribe: matches wsShellStatus in the same file.

Left alone (intentional):
- shell_handlers.wsShellInput: the 5s workspace-stream wait is too short to
  absorb a cold-start of agentctl, so we still require an existing execution.
- passthrough_handlers: stdin/resize require a live agent process per the rule.
- git_handlers post-success/failure callbacks: just look up TaskID; ensuring
  would be wasteful.

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

* test(handlers): cover wsShellSubscribe no-instance path

Mirrors TestWsShellInput_NoInstanceFound. Closes a coverage gap flagged in
PR review — the handler was switched to GetOrEnsureExecution but had no
direct tests for the lookup-failure path.

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-02 22:57:13 +01:00
João Salavisa 58fb9ffb0f fix: dedupe cancel-turn clicks to stop "turn cancelled" cascade (#784)
* fix: dedupe cancel-turn clicks to stop "turn cancelled" cascade

The cancel button had no in-flight feedback, so impatient users clicked
it repeatedly while the agent was tearing down a slow turn (e.g. a
Claude Monitor tool). Each click reached the backend and emitted its
own "Turn cancelled by user" message, with the second-and-later calls
also lazily creating phantom turns to host those messages.

Fix on both sides: SubmitButton now tracks isCancelling locally and
disables itself with a spinner while the request is in flight; the
orchestrator deduplicates concurrent CancelAgent calls per session via
a sync.Map guard so duplicates that slip through return immediately.

* fix: address PR review feedback

- Test: replace sleep-based polling in cancel-dedupe test with channel
  synchronization (cancelAgentEntered) per project convention.
- UI: switch the cancel re-entrancy guard from state to a ref so
  isCancelling no longer thrashes the useCallback dep array.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-02 22:49:19 +01:00
João Salavisa d8a9bb79d5 fix(github): heal legacy PR watches so single-repo tasks don't dupe PRs (#785)
After the multi-repo migration, pre-existing github_pr_watches rows kept
repository_id='', so the orchestrator's reconciler (keyed on
(session_id, repository_id)) inserted a second watch under the resolved
id. Both watches polled independently and each created its own
github_task_prs row, surfacing as a "+2 PR" badge on legacy single-repo
tasks. Add a startup backfill mirroring backfillTaskPRsRepositoryID:
dedup the legacy '' rows where a per-repo row exists, then stamp the
remainder from task_repositories.

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-02 22:36:58 +01:00
José Almeida 1394b7103f feat: add recent task switcher (#779)
* feat: add recent task switcher

* fix: address task switcher review feedback

* test: cover recent task cleanup

* perf: reduce recent task switcher storage reads
2026-05-02 22:25:40 +01:00
João Salavisa b4512e5158 fix: add border to task name input in create dialog (#783)
* fix: add border to task name input in create dialog

* fix: restore focus-visible indicator on task name input

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-02 22:21:16 +01:00
João Salavisa c853044f1d feat(ui): collapse commits and PR changes by default in changes panel (#781)
* feat(ui): collapse commits and PR changes by default in changes panel

* fix(e2e): re-expand commits section after remount in squash and focus tests

CommitsSection unmounts mid-transition (when both hasStaged and hasCommits
are briefly false), so it remounts with defaultCollapsed=true and loses
the user's expanded state. Re-expand before assertions that follow such
remounts.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-02 21:54:28 +01:00
João Salavisa a510b46e4e feat(multi-repo): support tasks spanning multiple repositories (#767)
* feat(task): add task_environment_repos schema and model for multi-repo support

Phase 0 of multi-repository task support: introduces the per-repository
child table and model alongside legacy single-repo fields (dual-write,
no behavior change). Lays the foundation for the orchestrator/lifecycle
refactor in subsequent phases.

- New task_environment_repos table with FK CASCADE on task_environments.
- New task_dir_name column on task_environments (idempotent ALTER).
- TaskEnvironmentRepo model + Repos slice + RepoFor helper on TaskEnvironment.
- CRUD methods + interface extension; env getters preload Repos.
- Idempotent backfill from legacy single-repo task_environments rows.
- Tests cover round-trip, CRUD, preload ordering, embedded create, cascade
  delete, and backfill from a legacy-shaped row.

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

* feat(lifecycle): add Repositories list to LaunchRequest and EnvPrepareRequest

Phase 1.1 of multi-repository task support: extends the lifecycle types
with explicit per-repo lists, while keeping the legacy single-repo
top-level fields as the synthesized fallback. No caller behavior changes
yet — preparers still see length-1 specs for single-repo launches.

- LaunchRequest.Repositories []RepoLaunchSpec + RepoSpecs() helper.
- EnvPrepareRequest.Repositories []RepoPrepareSpec + RepoSpecs() helper.
- EnvPrepareResult.Worktrees []RepoWorktreeResult for per-repo outcomes.
- runEnvironmentPreparer forwards req.Repositories into the prepare
  request, inheriting the request-level RepoSetupScript when each
  per-repo entry has none.
- Tests cover explicit-list precedence, synthesized fallback, and
  repo-less requests.

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

* feat(worktree,lifecycle): support multiple worktrees per session

Phases 1.2 and 1.3 of multi-repository task support. The pieces are
intertwined so they ship together — the preparer's per-repo loop
depends on the manager being able to hold one worktree per
(session, repository) pair instead of one per session.

Worktree manager:
- In-memory cache key changes from sessionID to (sessionID|repositoryID).
- New MultiRepoStore optional capability + SQLite implementation:
  GetWorktreesBySessionID and GetWorktreeBySessionAndRepository.
- New Manager methods: GetAllBySessionID, GetBySessionAndRepo. Existing
  GetBySessionID returns the first match (single-repo callers unchanged).
- Manager.Create's "already exists" check is now repo-scoped so the
  second repo's create no longer returns the first repo's worktree.
- All cache write/delete sites updated to the composite key.

WorktreePreparer:
- New prepareMultiRepo path activated when EnvPrepareRequest.Repositories
  has >=2 entries; single-repo and repo-less behavior is byte-identical.
- prepareOneRepo runs validate -> sync -> create -> fetch-PR -> per-repo
  setup-script for each spec; rolls back already-created worktrees on
  any failure.
- Workspace path becomes the task root (parent of any repo subdir);
  legacy WorktreeID/WorktreeBranch/MainRepoGitDir mirror Worktrees[0]
  for downstream code that hasn't been migrated yet.
- Per-repo setup script runs verbatim (no script-engine resolution
  yet — the per-repo placeholder namespace lands in a follow-up).

Tests:
- Manager: GetAllBySessionID, GetBySessionAndRepo (hit + miss),
  GetBySessionID single-repo compat, cache key separation.
- Preparer: multi-repo creates one worktree per repo; rollback removes
  active worktrees on partial failure; per-repo setup script runs in
  each worktree directory and emits its own step.

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

* feat(orchestrator): resolve all task repos and persist per-repo rows on launch

Phase 1.4 of multi-repository task support: the orchestrator now reads
every repository linked to a task, forwards the full list through the
adapter into the lifecycle layer, and persists one TaskEnvironmentRepo
plus one TaskSessionWorktree row per repo when the launch is multi-repo.
Single-repo and repo-less tasks keep their previous code path verbatim
(dual-write — legacy single-repo fields stay populated from the primary).

- New resolveAllRepoInfo / resolveTaskRepoInfo on the executor; primary
  is the first by Position.
- buildLaunchAgentRequest takes both the primary repoInfo and the full
  list, populating req.Repositories []RepoSpec only when length > 1.
- New RepoSpec / RepoWorktreeResult on the orchestrator's executor
  package mirror the lifecycle types so the adapter can translate
  between them without leaking lifecycle types into the orchestrator
  public API.
- Adapter (cmd/kandev/adapters.go) forwards req.Repositories into
  lifecycle.LaunchRequest and surfaces per-repo prepare results back
  on LaunchAgentResponse.Worktrees.
- persistTaskEnvironment writes env.Repos in the same create
  transaction; persistTaskEnvironmentRepos handles the existing-env
  reuse path. TaskEnvironment.TaskDirName is now persisted.
- persistWorktreeAssociation loops over resp.Worktrees in multi-repo,
  inserting one row per repo with its own RepositoryID.
- ResumeSession now also populates req.Repositories from task repos
  and stamps the existing TaskDirName so the preparer reuses the same
  task root.
- repoStore / executorStore interfaces extended with the new repo and
  env-repo CRUD methods; mocks updated accordingly.

Tests:
- LaunchPreparedSession with two task repositories populates
  req.Repositories in order and keeps legacy single-repo top-level
  fields filled from the primary.
- The same launch persists one TaskEnvironment + 2 TaskEnvironmentRepo
  + 2 TaskSessionWorktree rows.
- Single-repo launch still produces zero entries in req.Repositories
  and exercises only the legacy fields.

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

* feat(agentctl): git endpoints accept optional repo subpath for multi-repo

Phase 2 of multi-repository task support: every per-call git endpoint
gains an optional `repo` field (form param for GET, JSON for POST) that
selects a sub-directory of the workspace. Empty `repo` = workspace root,
preserving single-repo behavior verbatim.

- Manager.GitOperatorFor(subpath) returns a per-subpath GitOperator
  (cached). Validates the subpath against path traversal, absolute
  paths, and missing directories.
- New api server helper gitOpForRepo() emits a 400 with a per-operation
  GitOperationResult on invalid subpaths.
- Repo field added to: pull, push, rebase, merge, abort, commit,
  rename-branch, stage, unstage, discard, create-pr, revert-commit,
  show-commit, reset, log, cumulative-diff. (git/status still reads
  from the workspace tracker — that endpoint will gain multi-repo
  support when the tracker itself is split per repo.)
- Tests cover empty subpath, valid subpath caching, traversal
  rejection, and missing-directory rejection.

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

* feat(web/comments): scope diff comments by repository for multi-repo tasks

Phase 3 of multi-repository task support: comments now carry an
optional repositoryId so two repos with the same file path render
their own comment threads instead of bleeding together.

- CommentBase.repositoryId (optional, backwards compatible).
- getCommentsForFile gains an optional repositoryId arg; legacy
  comments without a repositoryId match any repo filter so persisted
  data keeps showing.
- Diff store interface in lib/diff/types.ts mirrors the new arg.
- Tests cover per-repo filter, omitted-arg fallback, and legacy data.

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

* feat(github): per-repo PR association on task PRs and watches

Phase 4 of multi-repository task support: github_task_prs and
github_pr_watches gain a repository_id column so multi-repo tasks can
have one PR per repo without colliding on (task_id) uniqueness.

- Idempotent ALTER TABLE adds repository_id to both tables.
- TaskPR.RepositoryID and PRWatch.RepositoryID model fields.
- New GetTaskPRByRepository and ListTaskPRsByTask lookups; existing
  GetTaskPR keeps single-PR semantics for callers not yet migrated.
- ReplaceTaskPR's delete is scoped by repository_id when set so a
  multi-repo task replacing one repo's PR no longer wipes the other.
- Tests cover per-repo storage and scoped replace.

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

* feat(web): foundations for multi-repo task UI

Phase 5 of multi-repository task support: primitives the upcoming UI
work needs without changing any visible behavior yet.

- TaskRepository.checkout_branch surfaces the optional PR head branch
  field that the backend already exposes.
- primaryTaskRepository(repos) picks by lowest Position so consumers
  match the backend's "primary" semantics instead of `[0]`.
- New useTaskRepositories(taskId) / useTaskPrimaryRepository(taskId)
  hooks read the live kanban task and return its repos sorted by
  position. Future kanban/diff/UI consumers should use these instead
  of poking task.repositories directly.
- Tests cover lowest-position selection and empty/single-repo edge cases.

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

* feat(web): kanban card shows multi-repo "+N" chip and hydrates full repo list

Phase 6 (subset) of multi-repository task support. The kanban now
exposes the per-task repository list to the UI and renders a compact
"+N" badge on cards whose tasks span more than one repository.

- KanbanState.tasks[].repositories slim shape (id, repository_id,
  base_branch, checkout_branch, position).
- SSR mapper hydrates the full list and uses primaryTaskRepository()
  to pick the position-aware primary instead of [0].
- useKanbanData passes repositories through to the card props.
- KanbanCard renders the primary repo name with a small "+N" chip
  when len(repositories) > 1; tooltip names the count.
- useTaskRepositories / useTaskPrimaryRepository hooks return the
  slim KanbanTaskRepository shape so multi-repo consumers share one
  read path.

Larger UI surfaces (task-create dialog, diff view, file browser,
mobile sheets) still target the primary repo only — they will be
ported as the multi-repo task creation flow lands. No visible change
for single-repo tasks.

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

* feat(task): reject duplicate repositories on multi-repo task create

Phase 8 of multi-repository task support: surface duplicate-repository
input as a clean validation error instead of letting the unique
(task_id, repository_id) constraint surface mid-loop with some rows
already inserted.

- createTaskRepositories tracks seen repository IDs and returns
  "repository <id> listed more than once for the task" before any
  CreateTaskRepository call.
- Tests cover the rejection path and confirm two distinct repos still
  succeed with both rows persisted in Position order.

Repository discovery and per-repo cloning were already covered by
Phase 1.4 (resolveAllRepoInfo loops ensureRepoCloned) and the
existing repository_discovery service is repo-list aware by design.

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

* feat(web/task-create): repeatable repository rows for multi-repo task creation

Users can now actually create a multi-repo task: a "+ Add repository"
button below the primary repo + branch selectors expands the form with
additional (repository, base-branch) rows. Each extra row picks from a
filtered repository list that excludes the primary and any other already-
chosen extras, so duplicates are impossible to enter.

- ExtraRepositoryRow type + form-state hook (extraRepositories, add /
  remove / update / reset). Lives in its own file so the main state hook
  stays under the file-length lint cap.
- ExtraRepositoryRows component renders the rows and the "+ Add" button;
  per-row branches are loaded on demand via the existing
  useRepositoryBranches hook.
- buildRepositoriesPayload accepts the extras and appends them after the
  primary, dropping rows with empty repository_id silently so an
  unfinished row does not block submit. The backend's duplicate-repo
  validation (Phase 8) catches anything that slips through.
- DialogFormBody is split: CreateModeSelectors (selectors + extra rows)
  and useDialogHandlers move to dedicated files, keeping touched files
  under the lint thresholds.
- Tests cover the multi-repo payload (ordering, drop-empty, no-primary
  recovery, single-repo unchanged) and the existing
  store-multi-repo.test.ts gets named constants to satisfy the
  no-duplicate-string rule.

Verified: pnpm exec tsc --noEmit clean, vitest 608/608 green,
eslint --max-warnings 0 clean.

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

* feat(agentctl): per-repo workspace tracker for multi-repo git/status

The git/status endpoint now accepts an optional ?repo=<subpath> query
param that selects a sub-directory of the workspace, completing the
per-repo plumbing started in the multi-repo phase. Single-repo callers
keep the workspace-root behavior unchanged.

- Manager.GetWorkspaceTrackerFor(subpath) returns a per-subpath
  WorkspaceTracker (lazy + cached). Validation reuses a new
  resolveSubpath helper shared with GitOperatorFor, so both code paths
  reject path traversal / absolute paths / missing dirs the same way.
- Per-subpath trackers are NOT started (no polling goroutines); the
  multi-repo path uses them only for synchronous GetCurrentGitStatus
  queries which fall through to getGitStatus when no cache is present.
  This keeps per-repo cost cheap.
- handleGitStatus reads c.Query("repo") and routes through the new
  resolver, returning a 400 with an error payload on invalid input.
- Tests cover empty subpath (root), valid subpath caching, traversal
  rejection.

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

* feat(web/review): group file tree by repository for multi-repo task changes

The review file tree now renders per-repo top-level nodes when a task's
changes span multiple repositories, so the same file path in two repos
no longer collapses into a single ambiguous entry.

- ReviewFile.repository_id and ReviewFile.repository_name (optional)
  identify which repo each file belongs to. Single-repo callers leave
  them unset and the tree falls back to the existing flat grouping.
- buildFileTree splits into buildMultiRepoTree (when 2+ distinct
  repository_names are present) and buildFlatTree (the original logic).
  Repo roots have isRepoRoot=true and a repositoryId for downstream
  filters; their children are full path subtrees per repo.
- collapse() skips repo roots so a repo with a single changed file
  still shows its repo header.
- ReviewFileTree renders repo roots with a stronger label, a top
  border, and an "N files" count badge; data-testid="repo-root-node"
  for E2E coverage. File-level rendering is unchanged.
- Tests cover the flat-tree fallback (no repo info, single repo),
  multi-repo grouping, repo-root pinning, and same-filename-different-
  repos isolation.

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

* feat(web/task-top-bar): "+N" repo chip on multi-repo task header

The task page top-bar breadcrumb now shows a small "+N" chip next to the
primary repository name when the task spans more than one repository,
matching the kanban-card treatment introduced earlier. Hover surfaces the
exact count via tooltip ("frontend (+2 more repos)").

- resolveTaskProps populates repositoryCount from task.repositories.length.
- TaskTopBar threads repositoryCount through to the new
  RepositoryBreadcrumb subcomponent.
- The chip carries data-testid="topbar-extra-repo-count" for E2E
  selectors.
- TopBarLeft was nearing the function-length / complexity caps; the
  breadcrumb extraction restores headroom for future additions.

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

* fix(web/task-create): disable "Add repository" when no other repos available

When the user only has the primary repository in their workspace,
clicking "+ Add repository" used to insert a row whose dropdown was
empty — looking like a bug ("no other repos show up"). The button now
disables itself when there are no remaining workspace repositories to
choose from, with a tooltip explaining why ("All workspace repositories
are already added"). The previous "primary not selected" guard is also
surfaced via tooltip.

- ExtraRepositoryRows computes remainingCount = repos − used (primary
  + already-added extras) and gates the Add button on it.
- New computeAddButtonHint helper returns a per-state title string for
  the disabled cases.
- Tests cover: dropdown shows the unused workspace repos when opened
  (the click path the user reported wasn't actually broken — the gate
  was just missing); Add button disabled when only the primary exists.

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

* fix(agentctl): workspace tracker falls back to first repo subdir for multi-repo task roots

The "Changes" panel was empty for multi-repo tasks because the
agent's workspace path is the task root — a plain holder directory
that holds one git worktree per repository as siblings. The workspace
tracker tried to run git commands against that bare root and silently
failed, so no git status updates ever reached the UI.

The tracker now detects this at construction: when the configured
workDir isn't itself a git repo, it falls back to the first immediate
child directory that is. The user gets the primary repo's changes in
the panel; cross-repo aggregation is a follow-up.

- preferGitRepoChildIfRootIsBare scans os.ReadDir entries (skipping
  hidden / non-directory entries) and returns the first that has a
  valid git index. Logs an info line when the rewrite happens so it's
  visible in the agentctl log.
- Repo-less tasks (e.g. quick chat) and single-repo tasks keep their
  previous behavior verbatim — the fallback only fires when the root
  itself fails resolveGitIndexPath.
- Tests cover: fallback when the workdir is a multi-repo holder,
  no-fallback for a real git repo, no-fallback when no git child
  exists.

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

* feat(multi-repo): per-repo workspace tracking — Changes panel shows all repos

The agent's workspace tracker is now split per-repository for multi-repo
task roots. Each repo gets its own tracker that polls git independently
and stamps its repository name onto every emitted event. The Changes
panel aggregates files from every repo and groups them under per-repo
headers using the file-tree machinery from Phase 6.

Backend (agentctl):
- GitStatusUpdate / FileListUpdate gain a RepositoryName field. Empty
  for single-repo workspaces (legacy clients see no change).
- WorkspaceTracker carries repositoryName and stamps it onto every
  emitted status/file-list. Two constructors: NewWorkspaceTracker for
  the legacy single-repo path (with the bare-root fallback) and
  NewWorkspaceTrackerForRepo for explicit per-repo trackers.
- Manager scans direct child directories for git repos at construction.
  When 2+ repos are found, builds one tracker per repo subdir on top of
  the root tracker (which stays bound to the bare task root and emits
  nothing useful). Single-repo workspaces are unchanged.
- Manager.SubscribeWorkspaceStream / UnsubscribeWorkspaceStream fan out
  one client subscription across the root + all per-repo trackers via
  AttachWorkspaceStreamSubscriber / DetachWorkspaceStreamSubscriber on
  the tracker. The WS handler switched from the single-tracker subscribe
  to the manager fan-out.
- Tests cover: per-repo trackers spawn for multi-repo task roots,
  single-repo doesn't, both repos emit GitStatusUpdates tagged with
  RepositoryName.

Frontend:
- GitStatusEntry / GitStatusData carry repository_name (optional).
- session-runtime gitStatus.byEnvironmentRepo new map keyed by env id
  then repository name; setGitStatus routes per-repo updates into it
  while still updating the legacy byEnvironmentId for single-repo
  consumers. clearGitStatus drops both maps.
- migrateEnvKeyedData migrates the new per-repo map alongside the
  existing keys when sessionId resolves to an environmentId.
- WS git-status handler forwards repository_name from event.status.
- New useSessionGitStatusByRepo hook returns sorted [{repo, status}]
  pairs for the active session.
- task-changes-panel mergeReviewFiles iterates statusByRepo when
  available, stamping repository_name onto every uncommitted file so
  the Changes panel groups them under per-repo headers (using the
  ReviewFile.repository_name plumbing from Phase 6).
- Tests: per-repo routing, no overwrite on sibling repo update,
  legacy single-repo fallback, clear-on-cleanup.

Verified: pnpm exec vitest run 623/623, eslint --max-warnings 0 clean,
tsc --noEmit clean, make test (backend) clean, make lint 0 issues.

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

* feat(web/changes-panel): per-repo group headers above each repo's files

The Changes panel now renders a sticky "frontend / N files" header above
the diffs from each repository so the user can visually distinguish
where each change lives. Single-repo tasks render unchanged (no header
shown when there's only one unnamed group).

- ReviewDiffList groups its file list by repository_name (preserving the
  caller's order within each group), then renders one RepoGroupHeader
  per group followed by the existing FileDiffSection list. Header gating
  rule: show when len(groups) > 1 OR the single group has a non-empty
  repository name.
- Group key uses "repo:path" so a file with the same path in two repos
  no longer collides on React's reconciliation.
- groupFilesByRepository + RepoGroupHeader live in a sibling
  review-diff-list-groups.tsx file to keep review-diff-list.tsx under
  the 600-line lint cap.
- Tests cover: no header for plain (no repo_name) files, one header per
  repo for 2+ groups, header shown even for a single named repo, file
  paths land under the right group's section.

Verified: vitest 627/627, eslint clean, tsc clean.

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

* fix(lifecycle): propagate RepositoryName through PublishGitStatus

The agentctl WorkspaceTracker stamps every per-repo GitStatusUpdate
with RepositoryName, but the lifecycle PublishGitStatus translation
into GitEventPayload was dropping that field. The orchestrator then
forwarded a status with empty repository_name, the frontend store
routed everything into the empty-key bucket, and the Changes panel's
multi-repo grouping never triggered — no header, no per-repo split.

- GitStatusData gains RepositoryName (omitempty so single-repo
  payloads stay byte-identical on the wire).
- PublishGitStatus copies update.RepositoryName onto the payload.
- Test asserts the field survives the publish → subscribe round trip
  via the in-memory event bus on the GitEvent.<sessionID> subject.

Restart the agentctl process for any running multi-repo task to pick
up the new field; new launches get it automatically.

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

* feat(web/changes-panel): per-repo group headers in the dockview Changes tab

The Changes tab in the dockview panel (the Files / Changes (N) tab the
user actually interacts with — not the standalone Review dialog) was
still rendering a flat file list, so multi-repo task changes either
collided onto the legacy single-status (showing only one repo's files)
or rendered without grouping.

- FileInfo gains repository_name (optional, single-repo unchanged).
- useSessionGit aggregates files from useSessionGitStatusByRepo when
  multi-repo data is present, stamping each FileInfo with its
  repository_name. Falls back to the legacy single status for
  single-repo workspaces. Aggregation extracted into
  aggregateFilesAcrossRepos to keep useSessionGit under the 100-line
  function lint cap.
- ChangedFile (changes-panel.tsx + changes-panel-timeline.tsx) carries
  repositoryName through to the renderer.
- FileListSection delegates to a new FileListBody that groups rows by
  repositoryName; renders a small per-repo subheader when 2+ repos OR
  any single named repo is present, otherwise falls back to the
  pre-multi-repo flat list (same DOM shape).
- Tests cover: no header for plain (no repo_name) files, headers
  per repo for 2+ groups, single named repo still gets a label.

Restart the backend so the per-repo trackers spawn for in-flight
multi-repo tasks; new launches are unaffected.

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

* feat(multi-repo): per-repo git ops, unified branch endpoint, chip-style task create

Bundles a string of multi-repo fixes and refactors that came up while
testing the feature end-to-end:

- workspace_path stored on multi-repo TaskEnvironment was one level too
  high, so agentctl booted with the wrong WorkDir on cold start; fixed
  in resolveTaskEnvWorkspacePath + GetWorkspaceInfoForSession.
- Stage/Unstage/Discard/Commit/Revert/Reset/Amend now thread `repo`
  through agentctl client → WS handler → frontend hook → SessionGit
  fan-out, so the right git repo is targeted (was running at the task
  root, which isn't a git repo for multi-repo tasks).
- agentctl GitLog is multi-repo aware: when no `repo` is specified and
  per-repo trackers exist, fans out one log per repo and merges sorted
  newest-first with RepositoryName stamped on each commit.
- Per-repo grouping for files (Changes panel) and commits, with
  collapsible group headers; commits section defaults to collapsed.
  Algorithm extracted into one generic groupByRepositoryName helper
  (was copy-pasted three times).
- Task creation dialog rewritten around a unified `fs.repositories[]`
  list — no more "primary vs extras" split. Chip-style row with one
  pill per repo + branch, "+" to add, x to remove, GitHub URL toggle
  inline. Discovered (on-machine) repos appear in any chip's dropdown.
  Removes ~6 fields and 3 helpers from the dialog state.
- Branch listing endpoints collapsed to one:
  GET /workspaces/:id/branches?repository_id=X | path=Y
  Frontend collapses to a single useBranches hook with a tagged-union
  source. Drops two HTTP routes, two service methods, two API client
  funcs, and one whole hook file.

Tests added across the chain: workspace_path resolver, sort-commits-
by-date, manager poll-mode propagation, RepoSubpaths, chip grouping
+ collapse + per-repo isLatest, group-by-repo helper, dialog payload
builder + chip wiring + discovered-repo flow.

* feat(multi-repo): unified per-repo git controls for all VCS operations

Changes panel and top-bar VCS button render per-repo Stage all, Commit,
Unstage all, Push, Pull, Rebase, Merge, and Create PR uniformly across
single-repo and multi-repo workspaces. Operations route to the correct
git repo subpath; fan-outs collect per-repo results and surface partial
success in the toast layer.

Backend:
- Stamp RepositoryName on Reset/BranchSwitch/FileChange notifications
  and forward through orchestrator handlers
- Surface per-repo errors from handleGitLogMultiRepo via PerRepoErrors

Frontend:
- pull/push/rebase/merge/abort/commit fan out via PerRepoOperationResult
- Per-repo group headers always render with action buttons
- Top-bar dropdown lists per-repo Pull/Rebase/Merge entries
- pendingStageFiles keyed per-repo to prevent cross-repo clears
- useRepoDisplayName distinguishes loading from multi-repo
- Commit dialog file summary respects stageAll
- New helpers: changes-panel-helpers.ts, changes-panel-repo-groups.tsx,
  use-repo-display-name.ts

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

* feat(multi-repo): plumb repo through file/commit/diff endpoints; per-repo PRs and review UI

- backend: thread `repo` subpath through pull/push/rebase/merge/abort, file
  content/update, cumulative-diff, and commit-show endpoints; per-repo
  fan-out for log + cumulative-diff with each repo's own merge-base; emit
  full `repositories` array on task.updated WS payload
- github: store/list TaskPRs as []*TaskPR (per-repo); orchestrator/web store
  rekey to `Record<taskId, TaskPR[]>`
- web: aggregate PR icon (count badge + worst-of color, multi-PR tooltip);
  branch hover card renders one row per repo with each repo's task base
  branch; review dialog merges per-repo file maps with composite keys and
  propagates repository_name through diff/expand/revert; commit-detail
  panel scopes to the owning repo
- kanban card: chip row of repo names (up to 2 + "+N" overflow, tooltip
  lists all)
- task-create dialog: gate non-worktree executors to multi-repo only; move
  fresh-branch toggle inline next to the repo chips (icon-only, with
  title/aria-label)

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

* fix(multi-repo): scope PR watches/associations and review UI per repository

Schema: add repository_id to UNIQUE constraints on github_pr_watches and
github_task_prs (with idempotent copy-and-rename migration) so one task
spanning N repos can hold one watch/PR per repo without collisions.

Plumb repository_id through CreatePRWatch/EnsurePRWatch/AssociatePRWithTask
/AssociatePRByURL, fan TriggerPRSync across all per-repo watches, and
disambiguate status sync by (task, owner, repo, pr_number) instead of
"first match". Add Repo to wsCreateFile/Delete/Rename and wsCreatePR/
RenameBranch so file and git ops target the right working tree.

Frontend review dialog: switch reviewedFiles, staleFiles, fileRefs,
selectedFile and comment counts to NUL-separated `${repo}\x00${path}`
keys so same-named files in different repos no longer share state.
useTaskPR consumes the new {prs: TaskPR[]} envelope.

Also: snapshot repoTrackers slice before background refresh in
SetWorkspacePollMode to prevent races with Stop(), and key
mergeCumulativeFiles by NUL-separated (repo, path) to match.

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

* chore: apply prettier formatting

Unblock CI prettier check on files modified earlier on this branch
that pre-date the current prettier config.

* fix: address PR review feedback and unblock E2E

Backend:
- ListWorkspaceTaskPRs background sweep now uses TriggerPRSyncAll so
  multi-repo tasks refresh every per-repo PR (was only the most recently
  updated watch). Caught by claude review on #767.

Frontend (no behaviour change):
- Replace literal NUL byte (0x00) in FILE_KEY_SEP and the inline key
  builder in use-review-dialog with the explicit   escape so the
  source is plain ASCII. The runtime separator is unchanged; this just
  removes a footgun that GitHub's diff renders as a visible space.
- Show the auto-resolved branch as a small read-only pill next to the
  GitHub URL input so the URL-mode dialog surfaces the branch the task
  will run on (previously only the URL was visible).

E2E:
- changes-panel-focus / pr-detection / pr-switcher-changes: expand the
  commits-section before asserting on commit text -- the section starts
  collapsed since the chip-style refactor.
- repository-selector-scroll: open the popover via repo-chip-trigger
  instead of the legacy single repository-selector testid.

* test(e2e): align task-create dialog tests with chip refactor

Updates three more tests that broke when the dialog migrated from a
single repository/branch combobox to per-row repo/branch chips and the
URL-mode toggle relabel:

- create-task.spec.ts (pre-select + remembers-selections): switch
  repository-selector / branch-selector lookups to repo-chip-trigger /
  branch-chip-trigger.
- create-task-github-url.spec.ts (toggle test): the inverse-state label
  is now "use a workspace repository", not the legacy
  "or select a repository".

No code changes — purely test alignment with the existing UI.

* fix(web): re-apply workbench-chrome topbar + restore branch-selector behaviour

Two regressions surfaced by the multi-repo merge into main:

1. task-top-bar.tsx had been resolved in our favour at the workbench-chrome
   merge (#761), losing the TopbarActionOverflow wiring that the new test
   asserts on. Re-applies main's topbar structure (TopbarCluster groups,
   TopbarActionOverflow, IntegrationsMenu, MoreToolsMenu, SettingsButton)
   on top of our multi-repo additions: repositoryCount + RepositoryBreadcrumb
   "+N" chip, gitStatus + isMultiRepo plumbing, and the GitAheadBehindBadges
   suppression for multi-repo. GitAheadBehindBadges moved to its own file to
   stay under the file-length cap.

2. The chip-style task-create dialog dropped the legacy branch-selector
   semantics. Restored:
   - Local-executor branch lock: the per-row branch chip is now disabled
     when isLocalExecutor and fresh-branch is off. The user's checkout
     dictates the branch for local execution; fresh-branch unlocks it.
   - Branch override: when locked, the chip shows currentLocalBranch
     instead of the value the user picked under a different executor
     (so worktree -> local doesn't display a stale "develop" pick).
   - Branch refresh: useBranches now exposes a refresh() callback for
     id-based sources (calls listRepositoryBranches with refresh=true),
     and Pill renders BranchRefreshButton in its popover header when
     onRefresh is wired.
   - URL-mode branch picker: GitHubUrlSection now renders a real
     branch-chip-trigger Pill backed by fs.githubBranches instead of a
     read-only span, restoring the "branch selectable in URL mode"
     behaviour (URL mode is always remote-clone, so the local-executor
     lock does not apply).

E2E spec updated: bulk-rename legacy branch-selector / repository-selector
testids to branch-chip-trigger / repo-chip-trigger.first(). All 13
create-task-branch-selector tests pass locally.

* ci: force workflow re-run

* fix(web): unblock E2E shard 2

Three issues showed up only after the merge with main, which brought back
the E2E shard 2 tests touching git/changes-panel and improve-kandev:

1. Wire the TaskCreateDialog slot props (extraFormSlot, aboveDescriptionSlot,
   bottomSlot, descriptionPlaceholder) through to DialogPromptSection. They
   were declared on the public API but dropped on the floor before this
   change, so Improve Kandev's contributor banner ("@octocat" /
   "@kandev-maint") never rendered. Also gate the "or paste a GitHub URL"
   toggle on lockedFields.repository so the locked-repo dialog hides it
   (matches main's behaviour and the existing test expectation).

2. Revert "commits section starts collapsed" (introduced in 9e8079de). The
   collapsed-by-default tradeoff is genuine, but it broke 14+ E2E tests
   that assert on commit text in the changes panel — the win wasn't worth
   the test churn. Updated the unit test to match.

3. Update the git-changes-panel E2E tests to use the stable
   `[data-testid^="commit-row-"]` selector instead of `commitsList li`.
   The chip-style refactor introduced a per-repo group <li> wrapper, so
   counting all <li> descendants now over-counts (1 wrapper + N commits).
   Same fix in the "distinguishes pushed and unpushed" test which queried
   `li` with text and matched both the wrapper and the commit row.

Locally verified: full shard 2 (45 tests) passes; full unit-test suite
(943 tests) passes; lint + typecheck clean.

* fix: address claude review feedback

Three findings from claude[bot] review on PR #767:

- types.ts: add 13 unit tests for reviewFileKey / splitReviewFileKey
  covering bare paths, composite keys, slashes/spaces in paths, repo
  names containing slashes, and full round-trip. Asks were repeated
  across five review rounds; the round-trip coverage is what catches
  the FILE_KEY_SEP NUL-vs-space class of bug at the type level.

- mergeCumulativeFiles (api/git.go): shallow-copy each per-file payload
  before stamping repository_name + path so the source map isn't
  mutated. The previous code wrote directly into the per-repo result
  map, which would have permanently rewritten the original entry if
  any future caller iterated the same source twice.

- buildRepoSpecs (executor_execute.go / executor_resume.go): drop the
  unused execCfg parameter (and the speculative "reserved for future
  per-repo config" suppression). Per repo overrides do not exist
  today and the speculative scaffolding masked an actual dead arg.

* docs(readme): mention multi-repository task support

* fix(web/topbar): drop standalone ahead/behind badges (duplicate of split button)

The Create PR / Push button already shows the inline ↑N ↓N counts, so
the separate "3 ahead" / "2 behind" badges next to the PR icon were
just visual noise. Removes the GitAheadBehindBadges component (now
unused) and the gitStatus / isMultiRepo prop chain that fed it.

* fix(github): heal legacy repository_id='' rows on github_task_prs

A task that pre-dated the multi-repo schema kept its github_task_prs row
with repository_id=''. After the schema migration, a subsequent sync
would resolve the task's primary repository_id and CreateTaskPR with the
new value -- but GetTaskPRByRepository(task, repo) returned nil because
the legacy row had an empty repository_id, so the new code inserted a
duplicate row instead of updating the legacy one. Net effect: two rows
for the same PR, surfacing as a "+2" PR badge on a single-repo task.

Adds backfillTaskPRsRepositoryID, run on schema init right after
migratePRTablesForMultiRepo:

  1. Dedup pass: when a (task, owner, repo, pr_number) tuple has both a
     legacy (repository_id='') and a per-repo row, drop the legacy one.
  2. Backfill pass: any remaining empty-repo rows get stamped with the
     task's primary repository_id from task_repositories.

The backfill is gated on task_repositories existing -- github-store unit
tests init only this package's schema, and the dedup pass alone is the
load-bearing fix for the symptom.

Tests cover the dedup path, the cross-package-skip path, and idempotency.

* test(github): cover UPDATE backfill path for orphan legacy rows

Adds TestBackfillTaskPRsRepositoryID_BackfillsOrphanRow per claude
review feedback. The two prior tests cover the DELETE dedup path and
the early-exit when task_repositories is absent, but the UPDATE path
that stamps the primary repository_id onto an orphan legacy row had
no coverage -- a wrong column name or off-by-one WHERE would have
slipped through silently.

* feat(web/changes-panel): group PR Changes by repository

Multi-repo tasks now have one TaskPR per repo, but the PR Changes
section was still rendering files flat using only the primary PR.
Adds useActiveTaskPRsWithFiles, which fans out one WS request per
TaskPR and tracks each fetch by (owner/repo/pr_number/last_synced_at)
so a server-side sync invalidates the cache.

Each PR's files are stamped with the resolved repository_name (looked
up from the workspace repos slice), and PRFilesGroupedList groups by
that name -- mirroring how Commits and Changes already render. Single-
repo tasks (one group, empty name) still render flat.

Mechanics:

- PRChangedFile gains an optional repository_name.
- mapPRFilesToChangedFiles takes a repository_name and stamps it.
- New PRFilesGroupedList + PRFilesRepoGroup live in
  changes-panel-pr-files.tsx so changes-panel-timeline.tsx stays
  under the 600-line cap; PRFilesSection delegates to them.
- Hook uses refs (not state) for the in-flight / fetched dedup so
  setState is only called when results arrive.
- Stable EMPTY_PRS sentinel avoids the new-array-each-render trap
  that would re-trigger every effect downstream.
- Workspace repo lookup memoised once via useMemo so the merged file
  list isn't rebuilt on every render.

* fix(web/changes-panel): show per-repo PR header when task is multi-repo

Previous logic only stamped repository_name on PR files when prs.length > 1
(2+ PRs). For a multi-repo task with only ONE PR yet (one repo doesn't
have a branch / hasn't been pushed), no per-repo header rendered, even
though STAGED and COMMITS already grouped under their repo names. Now
gates the stamp on the task itself being multi-repo, matching how the
other sections decide.

* fix(executor): serialise concurrent LaunchPreparedSession per session

Two paths in task_operations.go call LaunchPreparedSession on the same
session_id:

  1. PrepareTaskSession spawns a background goroutine with launchWorkspace=
     true the moment a session is created (so file browsing works before
     the user clicks Start).
  2. StartTaskWithSession runs a foreground launch when the agent is
     actually started (workflow auto-start, user click).

Without serialisation both reach agent_manager.LaunchAgent in parallel.
The fast-path check at the top of LaunchPreparedSession (session.Agent
ExecutionID != "") only kicks in once the first call has *persisted*
its execution id; the second call grabs a stale snapshot, runs the full
env-prep + builds runtime, then loses the executionStore.Add race and
fails with "already has an agent running (race resolved during register)".
Visible in the UI as "Environment setup failed".

Multi-repo amplifies the window because env prep runs sequentially per
repo (~2x the time for two repos), so what was a rare flake on
single-repo became consistent on multi-repo tasks.

Fix: acquire the per-session lock (the same sync.Map used by the resume
path) at the entry of LaunchPreparedSession and re-fetch the session
under the lock so the fast-path check sees the AgentExecutionID the
first holder just persisted. Second caller now takes the existing-
workspace path and starts only the agent subprocess, matching the
intended single-launch semantics.

Adds TestLaunchPreparedSession_SerialisesConcurrentLaunches that fires
two concurrent LaunchPreparedSession calls with the first one blocked
inside LaunchAgent. Without the lock, both reach LaunchAgent and the
test fails with call_count == 2; with the lock only the first does.

* fix(orchestrator): per-repo push detection so each repo's PR gets associated

Multi-repo tasks would only get one PR detected per task: the agent
pushes branches in BOTH repos, but the pushTracker keyed by sessionID
alone meant agentctl's per-repo git status events overwrote each
other's ahead counts. Whichever repo's events interleaved unfavourably
lost its >0 -> 0 transition and silently dropped its push detection.
Net effect: only the first/last repo's PR got an associated TaskPR row;
the other PR existed on GitHub but Kandev never knew about it.

Fix:

- pushTracker is now keyed by "<sessionID>|<repository_name>" so each
  repo's transitions are tracked independently. Empty repository_name
  preserves the legacy single-repo behaviour.
- trackPushAndAssociatePR forwards data.Status.RepositoryName to
  detectPushAndAssociatePR.
- detectPushAndAssociatePR resolves owner/name/repository_id for the
  specific repo via new resolvePushRepo helper (looks up the task's
  task_repository whose repository.Name matches the event), then uses
  GetPRWatchBySessionAndRepo to scope the existing-watch check.
- New associatePRFromPushScoped takes the per-repo repository_id
  directly instead of always resolving the primary one. CheckSessionPR
  (manual "check now") wired through the same scoped helper.

Existing tests pass with the explicit empty repository_name argument.
The user's existing task with the missing kandev PR row needs a manual
push retrigger or DB heal — the migration only deduped legacy empty
rows; this fix prevents the gap from recurring on future tasks.

* feat(web): one PR button per repo in topbar + per-PR detail panels

PRTopbarButton previously rendered just the primary TaskPR via
useActiveTaskPR(), so multi-repo tasks with N PRs only surfaced one.
Switch to useTaskPR(activeTaskId).prs and render one button per PR --
each opens its own dockview panel keyed by owner/repo/pr_number.

Plumbing:

- dockview-store / dockview-panel-actions: addPRPanel(prKey?: string)
  builds id "pr-detail|<key>" when a key is supplied; the legacy
  single-repo "pr-detail" id stays for the auto-add path.
- dockview-desktop-layout: forwards `params` to PRDetailPanelComponent
  so the panel can receive its prKey.
- pr-detail-panel: new prTaskKey helper + the panel looks up the
  matching TaskPR from the per-task list when params.prKey is set,
  falling back to useActiveTaskPR() for legacy panels and tooltips.
- pr-topbar-button: rewritten to render a button per PR, each labelled
  with #pr_number and tooltipped with owner/repo + title; click opens
  the per-PR panel.

* feat(web): collapse multi-PR topbar to a dropdown + show every PR in the + menu

Two follow-ups on top of per-PR panels:

- The dockview "+" panel-add menu still listed only state.pr (the primary
  TaskPR), so a 2-repo task only offered "PR #2" -- never the kandev
  one. Switch to state.prs[] and render one menu item per PR; multi-repo
  rows are labelled "PR #N -- repo" so the user can tell them apart.
  Each item opens its own panel via addPRPanel(prTaskKey(pr)).

- The topbar grew one outline button per PR after the previous commit,
  which doesn't scale (3+ PRs would crowd out other actions). Single PR
  keeps the existing single-button rendering; 2+ collapses to one
  outline button labelled "N PRs" with the aggregated status colour
  (red if any failing, etc.) and a dropdown listing each PR with repo,
  number, title, and per-PR status icon. Click an item -> open that
  PR's panel.

useLeftHeaderState now reads useTaskPR(taskId).prs and forwards the
full list through AddPanelMenuState as `prs`.

* fix(web/changes-panel): PR files arrive after race-cancelled fetch

useActiveTaskPRsWithFiles dropped responses from the previous effect
instance via a `cancelled` flag, but since the dedup tracking refs
(inFlightRef / fetchedRef) carry across renders, the next effect's
early-continue still saw the key in inFlightRef and skipped a fresh
request. The ref then got populated by the cancelled response and
fetchedRef permanently locked the key out of any future fetch.

Net effect: every render after the first prs reference change left
the merged prFiles array empty -- the PR Changes section never showed
up on multi-repo tasks even though both PRs existed and the WS request
would have returned files.

Drop the cancellation flag entirely. Per-key dedup is enough to prevent
duplicate requests, and the .then handlers use functional setState so
they're safe to land after the effect re-runs.

* test: cover review-feedback gaps (mapPRFilesToChangedFiles, push multi-repo, lock test channel-sync)

Three follow-ups from claude review on PR #767:

1. apps/web/components/task/changes-panel-helpers.test.ts: 5 new tests
   for mapPRFilesToChangedFiles. Covers status mapping (added / removed /
   renamed / modified / fallback), forwarding of plus/minus/oldPath, and
   the new repository_name stamping behaviour (multi-repo path stamps
   every row; single-repo path defaults to "" so PRFilesGroupedList
   skips per-repo sub-headers).

2. event_handlers_github_test.go: TestDetectPushAndAssociatePR gains
   two multi-repo cases. resolvePushRepo must scope CreatePRWatch +
   AssociatePRWithTask to the repository_id matching the event's
   repository_name (not silently fall back to primary); unknown
   repository_name must drop the event rather than mis-associate.
   mockGitHubService captures lastCreateWatchRepositoryID /
   lastAssociateRepositoryID so the per-repo scoping is asserted
   directly.

3. executor_test.go: TestLaunchPreparedSession_SerialisesConcurrentLaunches
   replaces the time.Sleep(50ms) coordination with a buffered `entered`
   channel + bounded select wait per CLAUDE.md. The test now waits for
   the first launch to enter LaunchAgent, then asserts no second entry
   arrives within a 100ms window — without the lock the second
   goroutine reaches LaunchAgent in microseconds, so the timeout serves
   as the "didn't race in" oracle, not a synchronisation primitive.

* fix(orchestrator): detect push when first poll lands post-sync

trackPushAndAssociatePR only fired on a >0→0 ahead transition, which
required two distinct status events to be observed. In multi-repo tasks,
any repo whose first agentctl status poll happened to land after the
push had already completed (ahead=0 with remote branch set on the very
first observation) silently dropped the push event — the watch was
never created, the PR never associated. Reproduced on task
4fdff41b-095a-4158-a311-4a1a23abe064 where 2/3 repos pushed but only
one PR appeared.

Now also fire on first observation when the status already reflects a
post-push state (ahead=0 + RemoteBranch set). detectPushAndAssociatePR
is idempotent against an existing watch, so a spurious fire on a
worktree that started from an already-synced remote just costs one
GitHub FindPRByBranch call.

The deferred pushTracker.Delete in detectPushAndAssociatePR is removed:
keeping ahead=0 stored is what suppresses repeated firing on subsequent
status events. Cleanup now happens at session-delete time via a new
pushTrackerForget helper that walks all (session|repo) entries.

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

* fix(web/topbar): restore pr-topbar-button testid for single-PR case

The multi-PR refactor renamed PRSingleButton's testid from
pr-topbar-button to pr-topbar-button-${pr_number}, breaking E2E tests
that relied on the stable selector (task-topbar-overflow.spec.ts and
the prTopbarButton page-object helper used by vcs-button-context).

Restore the canonical testid and expose pr_number via data-pr-number
for any test that needs to discriminate. PRMultiButton already uses
the same testid; with at most one PR-area control rendered at a time,
sharing the testid is unambiguous.

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

* fix(orchestrator): create one PR watch per repo on multi-repo tasks

The orchestrator only ever ensured a watch for a task's PRIMARY
repository. Both call sites that create watches were primary-only:

  - ensureSessionPRWatch (called when a session starts/resumes) used
    resolvePrimaryTaskRepositoryID and made one EnsurePRWatch call.

  - buildTaskBranchList (used by the poller's reconciler) keyed dedup
    by sessionID alone, so as soon as the primary repo got a watch
    the whole session was marked "watched" and the poller skipped
    every other repo.

Result: in a multi-repo task, the secondary repos never got a watch
row, so the periodic GitHub poller never searched for their PRs and
never associated them. Push detection (which fires on >0→0 ahead
transitions vs origin/main) doesn't help here either because Ahead is
measured against the integration branch, not the upstream tracking
branch — pushing doesn't change Ahead.

Reproduced on task a7a59bd8: PRs existed on github for both kandev
and aistats, but only the primary (kandev) was associated.

Refactor:

  - resolveSessionWatchTargets walks task_repositories × session
    worktrees and returns one (repo_id, owner, repo, branch) target
    per repo. Branch priority preserves the legacy precedence
    (checkout_branch > primary fallback > worktree branch) so PR-
    review-style synthetic worktree names don't clobber the real one.

  - ensureSessionPRWatch loops over targets and ensures one watch per
    repo.

  - buildTaskBranchList emits one TaskBranchInfo per (session, repo)
    and dedups against (session_id, repository_id) pairs from
    ListActivePRWatches — replacing the old session-only dedup that
    suppressed non-primary repos.

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

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-02 20:26:42 +01:00
José Almeida ebdce2f956 fix: prevent inline code from rendering diagrams (#773)
* fix: prevent inline code from rendering diagrams

* fix: address markdown renderer review feedback

* fix: remove redundant markdown block detection
2026-05-02 18:53:59 +01:00
José Almeida 7377b0f16b fix: remove settings topbar border (#774) 2026-05-02 17:59:05 +01:00
José Almeida 6fa38cd62c fix(terminal): re-key user-shell RPCs to task_environment_id (#770)
* refactor(backend): re-key user-shell RPCs to task_environment_id

user_shell.list/create/stop now take task_environment_id directly
instead of session_id with a session→env translation. Sessions in the
same task share one shell list, so the env is the natural scope.
HTTP route /api/v1/sessions/:id/terminals → /api/v1/environments/:id/terminals.
shell.status/subscribe/input (agent passthrough) stay session-keyed.

* fix(backend): heal task_sessions.task_environment_id on boot

Sessions created via paths that didn't write the FK left shell ops
broken — every env-keyed user-shell RPC failed to resolve the env and
the frontend silently swallowed the error. The boot heal links each
orphan session to its task's existing env (idempotent, runs after
backfillTaskEnvironments + healDuplicateTaskEnvironments).

* refactor(web): drop session_id from user-shell API, hooks, and slice

createUserShell/stopUserShell/fetchTerminals take environmentId.
useUserShells takes envId directly (no environmentIdBySessionId
translation). useTerminals takes both (env for shell ops, session for
tab UX persistence). Slice actions key writes by env id directly,
removing the silent no-op when the session→env mapping wasn't set yet.

* refactor(web): wire env id through dockview, right-panel, and SSR call sites

Dockview "+" menu, terminal scripts dropdown, dev-preview button,
right-panel "+" button, Ctrl+\` toggle, watermark, and panel-close
cleanup all source the env id from useEnvironmentId() / store and pass
it to createUserShell/stopUserShell. Shell-mode passthrough terminal
no longer blocks on session id — env id is sufficient. SSR resolves
the active session's task_environment_id from the session list and
calls fetchTerminals with the env id.

* test(e2e): cover env-keyed terminal new-tab flows + WS payload guard

New spec exercises the right-panel "+" button and the dockview "+ →
Terminal" menu, asserts the new tab connects, and intercepts outgoing
user_shell.create WS frames to verify the payload carries
task_environment_id and never session_id. A heal-coverage assertion
checks every listed session has task_environment_id populated post-boot.

* fix(e2e): drop right-panel '+' test, dockview is the only '+' path on desktop

The mobile TaskRightPanel SessionTabs aren't rendered at desktop
viewports — the dockview '+' menu is the sole new-tab affordance, so
testing the mobile path on chromium just timed out clicking a button
that never mounted. Consolidate into a single dockview '+ → Terminal'
test that asserts the new panel gets the backend-assigned 'Terminal 2'
label (proving env-shared shell list) plus the WS-payload regression guard.

* fix(e2e): assert dockview terminal-tab count, not 'Terminal 2' label

Dockview hardcodes the panel title to 'Terminal' for every tab — only
the mobile right-panel SessionTabs surface the backend's 'Terminal N'
label. Switch the assertion to count tabs to keep the e2e green.

* test(backend): cover SQL NULL branch of healSessionTaskEnvironmentIDs

Adds insertSessionWithNullEnvID and TestHealSessionTaskEnvironmentIDs_LinksNullOrphans
so the WHERE-clause IS NULL predicate is exercised — the existing tests only
seeded empty-string FKs. Also adds LIMIT 1 to the heal subquery as a
defensive measure: the unique index already guarantees ≤1 row per task at
runtime, but the SQL now reads as deterministic in isolation.

* refactor(web): drop dead taskGateOk on agent terminal WS gate

Agent passthrough routes by sessionId, not taskId — taskId was only used
for logging. Gating the WS effect on taskId forced agent terminals to
wait for useSession() to hydrate, adding a refresh-race window that
didn't guard any real precondition. connectionKey + canConnect already
cover the meaningful preconditions.

* fix(web): stamp env id on terminal panels for accurate cleanup

addTerminalPanel now bakes environmentId into the panel's params at
creation time. The dockview-layout-setup onDidRemovePanel handler
prefers the stamped env over re-deriving from the active session, so
closing a terminal that was opened under a different task no longer
calls stopUserShell with the wrong env (which silently no-ops on the
backend and leaks the shell process until session teardown). Falls back
to the active session's env for legacy panels persisted before the
param existed.

* fix(web): keep task id logging out of terminal reconnect deps
2026-05-02 15:19:02 +01:00
João Salavisa 5936bb6808 test: add e2e coverage and mock backends for jira and linear integrations (#771)
* test: add e2e coverage and mock backends for jira and linear integrations

Adds in-memory MockClient + MockController for both integrations gated by
KANDEV_MOCK_{JIRA,LINEAR}=true, plus apiClient mock helpers and Playwright
specs covering settings and import flows.

Also fixes ValidatedPopover's TriggerButton silently dropping radix Slot's
onClick handler — the popover wouldn't open under any synthetic-click path
(including Playwright). Spreads `...rest` onto the inner Button.

Reworks the integration cleanup hook in test-base as an auto fixture so it
runs for every test using the imported `test` object, not just tests in the
fixture file itself.

* fix: address PR review feedback on jira/linear mocks and e2e specs

- Fix SetAuthResult docstrings: nil simulates an unconfigured state, not the default success.
- Drop unused JSON tags from doneTransitionCall and setStateCall (Go-only test fixtures).
- Track Linear issue insertion order so SearchIssues returns deterministic results instead of map-iteration shuffle.
- Document filterByJQL precedence at the SearchTickets call site so the all-hits-on-no-match fallback is visible.
- Wait for the post-save auth-health probe before forcing a failure in the seeded-failure tests, eliminating a goroutine race.
- Reorder authMethod precedence in setJiraConfig/setLinearConfig to put the spread first so 'caller wins' reads naturally.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-02 14:41:36 +01:00
José Almeida c0ce55ff9d fix: unblock terminals stuck on Connecting and heal task_environments (#769)
* fix(gateway): snapshot agentctl status and env id on session subscribe

Late-subscribing clients (page reload, task switch, WS reconnect) miss
the agentctl_ready and task_environment_id events fired during the
original launch. Without them, the env-routed shell terminal gate stays
stuck and the panel hangs forever on "Connecting terminal...".

- appendSessionStateMessage now carries task_environment_id so the
  frontend can seed environmentIdBySessionId for the active session.
- New appendAgentctlStatusMessage snapshots current agentctl readiness
  via a bounded Health probe and emits session.agentctl_ready /
  _starting to flip the client gate out of `undefined`.
- GetOrEnsureExecutionForEnvironment now publishes AgentctlStarting to
  mirror EnsureWorkspaceExecutionForSession and keep gate transitions
  monotonic.

* fix(web): drop shell-mode agentctl gate to unblock env-routed terminals

The shell terminal gate required agentctlStatus.isReady to flip to ready
before opening the WS, but that event may have fired before the client
subscribed (page reload, task switch, local-executor task switch). The
lazy create-on-terminal-connect path on the backend never fires either,
because the WS never opens — chicken-egg.

Backend env handler already waits for remote workspace readiness
server-side (waitForRemoteExecutionReadyWithTimeout), so the client
just needs the routing keys (env id + session id). Agent-mode terminals
still gate on readiness — the agent process must be wired before
passthrough I/O is meaningful.

Extract computeCanConnect helper to keep PassthroughTerminal under the
complexity ceiling.

* test: cover terminal-hang on subscribe snapshot and env-routed gating

Adds a backend unit test asserting appendSessionStateMessage carries
task_environment_id (the deterministic RED for the env-map seed bug),
plus E2E scenarios for the user-facing repros: cold load, kanban switch,
hard reload, sidebar switch, and a local-executor task switch that used
to poison the terminal for every subsequent task. Adds an
expectTerminalConnected helper to SessionPage to detect the
"Connecting terminal..." overlay.

* fix(repo): heal task_environments on boot and enforce one env per task

Live DB audit on the user's machine surfaced two corrupt-data classes that
manifest as the user-facing "terminal doesn't appear / Failed to fetch
terminals: 503" symptoms:

- 15 worktree-mode envs with worktree_path set but workspace_path empty.
  GetOrEnsureExecutionForEnvironment returns ErrSessionWorkspaceNotReady
  forever, the env terminal handler 503s.
- 3 tasks with two task_environments rows (race in lazy create — pairs
  4-6 s apart, both ready, distinct workspace_path).

healTaskEnvironmentWorkspacePaths backfills workspace_path = worktree_path
on the affected rows, and healDuplicateTaskEnvironments collapses each
duplicated task to its most recently updated env (re-pointing any sessions
still on the loser, then dropping the loser row).

ensureTaskEnvironmentTaskUniqueIndex adds a UNIQUE index on
task_environments(task_id) so a future race fails loud. Order matters:
heal must run first to drop duplicates before the unique index is created.

* fix(repo): reject empty workspace_path on worktree envs

The orchestrator's persistTaskEnvironment update branch previously left
workspace_path untouched, so an env created with empty workspace_path
would stay corrupt forever — terminals 503 with ErrSessionWorkspaceNotReady.

Tighten the repository boundary: CreateTaskEnvironment refuses worktree-mode
inserts without workspace_path, and UpdateTaskEnvironment refuses to clear
it back to empty. A future writer regression now fails loud at the boundary
instead of producing a row that breaks the env terminal handler.

* fix(executor): refresh paths on env update and dedupe by task

The persistTaskEnvironment update branch only mutated AgentExecutionID +
Status, so envs created earlier with an empty workspace_path stayed
permanently broken across launches. Refresh worktree + workspace fields
on update via a shared computeWorkspacePath helper used by both branches.

Concurrent launches for the same task previously raced inside this
function — each saw existingEnv == nil and each called
CreateTaskEnvironment, producing duplicate rows ~4-6 s apart in the live
DB. Hold a per-task mutex (mirroring sessionLocks) and re-fetch the env
inside the critical section so siblings reuse the row the first launch
persisted. The repo's unique index on task_environments(task_id) is the
durable guarantee; the lock just closes the window before the constraint
trips.

* test(repo): cover task_environments heal, validation, unique index

Repository unit tests for the new heal steps and writer guards:
- HealTaskEnvironmentWorkspacePaths_BackfillsEmpty / LeavesPopulatedAlone /
  Idempotent
- HealDuplicateTaskEnvironments_KeepsMostRecent (asserts session re-link to
  winner) / NoOpWhenSingle
- EnsureTaskEnvironmentTaskUniqueIndex_BlocksFutureDuplicates
- CreateTaskEnvironment_RejectsEmptyWorkspaceForWorktree /
  AllowsNonWorktreeWithEmptyWorkspace
- UpdateTaskEnvironment_RejectsClearingWorkspaceForWorktree

Tests live in the sqlite package so they can exercise the unexported
heal* helpers directly, mirroring how the boot path calls them.

* fix: address PR review feedback

- helpers.go: drop the 2 s blocking Health probe in
  appendAgentctlStatusMessage. sendSessionData runs in the WS read loop, so
  the probe was delaying every subscribe/focus ACK by up to 2 s. Use
  GetWorkspaceStream() != nil as the cached readiness signal — the stream
  manager only attaches it after Health succeeds, so its presence is a
  free, non-blocking proxy. Subsequent waitForAgentctlReady events still
  correct the snapshot if it picks the wrong one.

- manager_execution.go: publish AgentctlStarting INSIDE createExecution,
  before spawning waitForAgentctlReady. The previous order published it
  after createExecution returned, which let the goroutine race past on
  fast Health and deliver Ready before Starting. Drop the now-redundant
  publishes in EnsureWorkspaceExecutionForSession and the env lazy-create
  path.

- task_environment.go: replace the local executorTypeWorktree constant
  with models.ExecutorTypeWorktree (canonical) so a future rename of the
  type is caught by the compiler.

- base.go: heal_workspace_path now respects the kandev path layout —
  task-dir-mode envs (.../.kandev/tasks/<name>/<repo>) get
  Dir(worktree_path) as workspace_path, mirroring computeWorkspacePath
  in the orchestrator. Plain worktree mode unchanged.

- heal_test.go: tighten unique-constraint assertion to require a UNIQUE
  error string so the test fails loudly if a different DB error masks
  the constraint violation. Add task-dir-mode heal coverage.
2026-05-02 11:50:53 +01:00
João Salavisa 83e01477df refactor: extract shared shapes between jira and linear integrations (#759)
* refactor: extract shared shapes between jira and linear integrations

Factors out the duplicated logic between internal/jira + internal/linear
(backend) and components/jira + components/linear (frontend) into reusable
shared shapes. Follow-up to PR #736.

Backend:
- New internal/integrations/secretadapter wraps secrets.SecretStore with
  the upsert API both jira.SecretStore and linear.SecretStore expect;
  drops both adapter copies from cmd/kandev/services.go.
- New internal/integrations/healthpoll owns the 90s auth-health loop via
  a Prober interface; linear/poller.go is a thin wrapper, jira/poller.go
  keeps only its (jira-specific) issue-watch loop.
- provideServices split into initGitHubService / initJiraService /
  initLinearService — now 75 lines (was ~125, exceeded the 80-line limit).

Frontend:
- New hooks/domains/integrations/use-integration-availability.ts and
  use-integration-enabled.ts; jira/linear hooks reduce to one-line
  delegates and move from components/<x>/ to hooks/domains/<x>/ per the
  project convention Greptile flagged on PR #736.
- New components/integrations/{auth-status-banner,auth-error-message,
  validated-popover}.tsx; the four link/import-bar wrappers drop from
  ~110 lines to ~35 each, and JiraLinkButton picks up the
  clear-error-on-close behaviour LinearLinkButton already had.

Docs:
- New 'Adding a new third-party integration' section in CLAUDE.md/AGENTS.md
  documenting the shared shapes and intentional Jira/Linear divergence
  (transition vs state, JQL vs filter object, eventBus only on jira).

* fix: address PR #759 review feedback

- validated-popover: outline-with-label trigger now sets type="button" and
  honours triggerDisabled, matching ghost-icon (Greptile, Claude, CodeRabbit).
- jira-link-button / linear-link-button: move updateTask() into the awaited
  fetch path so a failed title update surfaces as the popover's inline error
  instead of an unhandled rejection (CodeRabbit).
- use-integration-availability: monotonic requestId race guard prevents a
  slow earlier probe from overwriting a newer auth result (CodeRabbit).
- use-integration-enabled: drop unnecessary async on synchronous init
  (Claude).
- jira/linear poller smoke tests: wrap in testing/synctest instead of
  time.After(2s) per backend testing convention (CodeRabbit nitpick).

Skipped with reasoning on the threads:
- secretadapter Set TOCTOU — single-process SQLite + single-writer per
  workspace; constraint violation on conflict surfaces as an error to the
  caller, not silent corruption.
- healthpoll SetInterval validation — the function isn't called from
  production code today; a panic on misuse would be a footgun and silent
  ignore would just hide bugs differently.

* fix: address PR #759 round-2 review feedback

- jira-settings / linear-settings: drop the local STATUS_REFRESH_MS = 90_000
  copies and import the shared INTEGRATION_STATUS_REFRESH_MS so changing the
  cadence only touches one file (Claude).
- healthpoll: rename Poller.ProbeAll → probeAll. The only callers are the
  loop and the in-package tests, so widening the public API wasn't buying
  anything (Claude).

* fix: invalidate ValidatedPopover in-flight submits on close

If the user clicked Submit and dismissed the popover before the request
settled, the next time they re-opened it would inherit `loading=true` (the
disabled-while-loading submit button was stuck) and a late rejection from
the previous session could repopulate `error` in the new one.

Track the submit via a `useRef` token, bump it on close, and ignore any
result/rejection whose token no longer matches. Also reset `loading` and
`error` on close so the next open starts clean. Adds a regression test
covering both the late-resolution and late-rejection paths.

Addresses CodeRabbit review on PR #759.

* ci: trigger workflow re-run

GitHub Actions did not dispatch the pull_request workflows on the previous
two pushes (1d869f0e, 0ab6c034); only pull_request_target and CodeQL fired.
Empty commit to nudge synchronize event.

* fix: address PR #759 round-3 review feedback

- jira.Poller.Stop: add nil-receiver guard so callers using the
  defer-Stop-after-NewPoller pattern don't panic when initJiraService
  returned nil (Greptile + Claude). Matches linear.Poller's guard.
- healthpoll TestStart_RunsImmediateProbe + TestStart_IsIdempotent:
  rewrap in testing/synctest with synctest.Wait() instead of
  time.After(2s) wall-clock waits. Drops the now-unused probedAll signal
  channel from fakeProber (Claude).

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-02 11:50:19 +01:00
João Salavisa 91edce7eac fix(lifecycle): prevent orphaned agent subprocesses from concurrent execution creates (#768) 2026-05-02 08:47:04 +01:00
João Salavisa b546767f3c perf(analytics): speed up stats endpoint aggregation (#766) 2026-05-02 00:00:11 +01:00
José Almeida 396325b2c9 feat: allow reordering sidebar views (#764) 2026-05-01 23:50:05 +01:00
João Salavisa 7d93d52c7a fix(ui): restore readable boxed chat hotkey tooltip (#765) 2026-05-01 23:08:03 +01:00
José Almeida 692fdddcc9 fix(web): make mermaid sanitizer quote-aware and detect parens in bracket labels (#763)
* fix(web): make mermaid sanitizer quote-aware and detect parens in bracket labels

Two diagrams failed to render because sanitizeMermaidCode injected nested
quotes into already-quoted labels and missed parens-as-stadium-opener inside
bracket labels. Skip ranges already inside `"..."` (recomputed between
passes) and add `(`/`)` to the bracket-pass trigger set.

* refactor(web): drop dead text.startsWith('"') guards in mermaid sanitizer

The regex character classes [^\]"], [^|"], [^)"] already exclude `"`,
so the guards were unreachable.

* fix(web): stop unterminated quote bleeding across lines in mermaid sanitizer

findQuotedRanges now stops scanning at newline; an unterminated `"` is
discarded rather than paired with a `"` on a later line where it would
silently suppress sanitization of unrelated content. Add tests for the
cross-line guard and for a bracket-with-parens adjacent to a real
stadium node on the same line.
2026-05-01 22:38:06 +01:00
José Almeida 5022469187 fix: refine workbench action button layout (#762) 2026-05-01 22:32:28 +01:00
José Almeida 68c94dfa3a feat: refine workbench chrome (#761)
* docs: define product and design direction

* style: establish restrained workbench primitives

* refactor: declutter board and task topbars

* style: align dockview panel chrome

* fix: align task topbar vcs control sizing

* refactor: surface integrations navigation

* fix: repair integrations and task creation workflow

* refactor: include linear in integrations navigation

* style: restore familiar workbench tones

* fix: add dockview tab breathing room

* fix: show configured integration shortcuts

* fix: hover open integrations menu

* fix: stabilize integrations hover menu

* fix: align home and dockview topbars

* fix: normalize home topbar controls

* fix: compact home topbar height

* fix: simplify home chrome and split buttons

* fix: move integrations to left chrome

* fix: restore home stats shortcut

* fix: add dockview tab breathing room

* fix: border home stats button

* fix: streamline dockview topbar actions

* fix: align task split button seam

* fix: address review feedback

* fix: restore topbar e2e affordances

* fix: stabilize workflow e2e isolation

* fix: add task topbar action overflow

* fix: address PR review feedback
2026-05-01 21:02:41 +01:00
João Salavisa c8fcd6c5aa feat(mcp): add get_task_conversation tool (#756)
* feat(mcp): add get_task_conversation tool

* fix(mcp): correct conversation pagination cursor and limits

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-01 18:20:01 +01:00
Carlos Florêncio e16debeaca fix(preview): server-authoritative session ensure for kanban preview (#760) 2026-05-01 18:01:17 +01:00
Carlos Florêncio 1eae869054 feat: add improve kandev in-app contribution flow (#740) 2026-05-01 15:18:18 +01:00
José Almeida 9d275d3009 refactor: route user terminals by environment (#758)
* refactor: route user terminals by environment

* refactor: remove terminal compatibility shims

* fix: address terminal PR review feedback

* fix: wait for remote shell readiness

* fix: require agent mode for session terminals
2026-05-01 13:27:25 +01:00
Carlos Florêncio 9f1e372967 feat: refresh + smarter filter for new-task branch selector (#750) 2026-05-01 13:24:12 +01:00