Commit Graph

867 Commits

Author SHA1 Message Date
João Salavisa b6c2b5a400 feat(stats): show active time and elapsed span per task (#748)
* feat(stats): show active time and elapsed span per task

* fix(stats): address review feedback on task duration metrics

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-01 00:57:59 +01:00
José Almeida 5d8152ce3f docs: add star history chart (#753) 2026-05-01 00:40:06 +01:00
José Almeida fcc7ceb8b6 fix(approvals): drop stuck pending permission_request messages (#723)
* fix(web): exclude permission_request from turn-complete safety net

The session.turn.completed handler iterated over messages and forced
metadata.status="complete" on anything carrying tool_call_id. Permission
prompts also carry tool_call_id (for FE pairing with their tool_call),
so this loop overwrote the user's "approved" decision on every prompt
in the turn — and the FE component re-rendered the Approve/Deny buttons.

* fix(backend): protect permission_request rows from tool_call sweeps

Three permission_request invariants the prior code violated, mirroring
the FE bug fix:

- CompletePendingToolCallsForTurn: SQL UPDATE filtered by tool_call_id
  presence, also catching permission_request rows. Add type filter so
  the safety net only touches actual tool messages.
- GetMessageByToolCallID: returned the oldest row carrying that
  tool_call_id, which races to the permission_request when timing
  shifts. Exclude permission_request type so a tool_update can never
  land on the user's approve/reject row.
- applyToolCallMessageUpdate: defensive guard that refuses to overwrite
  a permission_request, making the invariant explicit at the layer that
  does the writing.

Adds a regression test for CompletePendingToolCallsForTurn covering
approved/rejected/pending permission rows.

* test(e2e): cover approval-reappear regression with mock-agent scenario

Adds a multi-permission mock-agent scenario (three sequential bash
tools, each requiring approval) and an E2E test that approves all
three and asserts no permission action row remains visible after
the agent's turn ends, and that the resolved state survives a reload.

Supporting test infrastructure:
- data-testid hooks on PermissionActionRow.
- permissionActionRows() / permissionApproveButtons() on SessionPage.
- backend fixture force-disables AGENTCTL_AUTO_APPROVE_PERMISSIONS=false
  so a developer's local AUTO_APPROVE=true env doesn't silently bypass
  the permission UI in tests that exercise the approve/reject flow.

* test(backend): cover GetMessageByToolCallID permission_request exclusion

Addresses claude-review feedback on the approvals fix:
- Adds a regression test that seeds both a permission_request and a
  tool_call with the same tool_call_id (permission_request created
  first, so an ORDER BY created_at ASC sweep without the type filter
  would race to it) and asserts the lookup returns the tool_call row.
- Bumps the applyToolCallMessageUpdate invariant guard from Warn to
  Error: reaching that branch means a caller bug, not a transient
  condition, and Warn would silently swallow the violation.

* fix(e2e): scope auto-approve override to permission-approval test only

The previous fixture force-disabled AGENTCTL_AUTO_APPROVE_PERMISSIONS
globally, which broke session-isolation.spec.ts and other tests that
use scenarios with permission-required tools (e.g. /e2e:read-and-edit)
and rely on auto-approve to let the agent finish without UI clicks.

Default the env to "true" in the fixture; let permission-approval.spec
flip it to "false" via a backend.restart() override in beforeAll, then
restore in afterAll. Adds an envOverrides parameter to backend.restart.
2026-05-01 00:25:51 +01:00
João Salavisa 45a4f0b016 test(web): align workflow-agent-switch e2e tests with PR #743 (#751)
* test(web): align workflow-agent-switch e2e tests with PR #743 behavior

PR #743 split agent.boot_ready from agent.ready and added pinnedSessionId
focus protection, breaking four expectations in workflow-agent-switch.spec.ts:

- on_turn_start no longer fires from StartCreatedSession; it now fires from
  dispatchPromptAsync (user-message path). Test :204 now waits for the
  profileA agent to be ready and sends a message to trigger the transition.
- SSR-load setActiveSession pins the initial primary, so workflow profile
  switches no longer auto-yank the active dockview tab. Tests :420, :490,
  :546, :614 now assert on the primary star marker (which still moves to
  the new session) instead of the active-tab text.

Also fixes primaryStarInTab page-object helper: the IconStar is rendered as
a sibling of .dv-default-tab inside the [data-testid=session-tab-*] wrapper,
so the locator now anchors on the wrapper.

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

* test(web): harden workflow-agent-switch assertions

Add message-visible guard after sendMessage to surface silent failures
early. Align primaryStarInTab timeout with profileBTab (45 s) where the
cascade latency budget was already set at 45 s.

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

* test(web): drive on_turn_start via chat message in kanban-flow test

The HTTP create-with-start_agent path no longer fires on_turn_start; only
WS user messages do (dispatchPromptAsync). Switch the kanban-flow test to
create the task in Backlog and send the initial prompt as a chat message
so on_turn_start triggers. Verifies the same workflow behavior — Backlog
→ In Progress on on_turn_start, invalid step_id in on_turn_complete is
gracefully skipped — without depending on the dialog "Start Agent" 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-01 00:25:08 +01:00
José Almeida 7e8b4bb30e feat(quick-chat): eager-init agent on profile selection (#747)
* feat(quick-chat): eager-init agent on profile selection

Switch quick-chat backend from `IntentPrepare` to `IntentStart` so the
agent process boots immediately when the user picks a profile, instead
of waiting for the first prompt. The ACP `session/new` handshake fires
before the user types anything, so the slash menu, mode dropdown, and
model selector are populated up-front. Fixes the empty-slash-menu UX
in quick chat for ACP agents (OpenCode, Claude, Codex, etc.).

Frontend picker shows a per-card spinner + disables sibling cards
during boot. Rapid profile switches (and other picker-bypassing
actions like opening a new tab, switching tabs, or closing the modal)
supersede the in-flight start via a monotonic request id; the
resolved task is cleaned up via `deleteQuickChatTask` so we never
orphan an ephemeral task or its agent process.

Backend rollback uses a fresh background context so `DeleteTask`
runs even when the request context has already been cancelled by
the client.

`mock-agent` now emits `available_commands_update` from `NewSession`
and `LoadSession` (matching real OpenCode/Claude) so the eager-init
pipeline is exercised in e2e. Existing prompt-time emit kept as an
idempotent fallback.

* test+cleanup(quick-chat): unit tests for useAgentSelection; minor cleanups

- Add 5 unit tests for useAgentSelection covering happy path, rapid-pick
  supersession, reset() during in-flight, and error toast vs silent-on-superseded.
  Exercises the orphan-task cleanup that the eager-init flow depends on.
  (claude bot review)
- Drop redundant isDisabled alias in AgentPickerView. (claude bot review)
- Drop unused ctx parameter from emitAvailableCommandsAfterDelay — it was
  always called with context.Background() so the Done() branch was dead
  code. (claude bot review)
- Re-format with prettier after the rebase.

* fix(quick-chat): use constants.TaskDeleteTimeout for rollback ctx

Match the other DeleteTask call sites in task_http_handlers.go (line 851)
instead of an ad-hoc 10s timeout. (claude bot review)
2026-05-01 00:21:53 +01:00
José Almeida 47f875a61e fix(web): plan panel misses agent updates emitted before WS connects (#749)
* fix(web): plan panel misses agent updates emitted before WS connects

Agent auto-start can write a plan via MCP within ~100 ms of task creation,
faster than the browser opens its WS connection — the `task_plan.created`
broadcast is delivered to zero clients and the Plan tab never appears
because `useTaskPlan` only fetches once the panel is mounted (chicken-egg).

Eagerly fetch the plan from `usePlanPanelAutoOpen` once the WS is
connected so the store is populated regardless of the panel's mount
state. Also acknowledge the plan when the panel is restored from a saved
layout with no `lastSeen` recorded — that's a page-reload hydrate, not a
fresh agent update, so a stale indicator should not flash.

* test(web): cover the new eager-fetch + reload-acknowledge branches

Mock the new store selectors and `getTaskPlan` API in
`use-plan-panel-auto-open.test.ts`, restore the original `panelExists →
return` short-circuit (the previous version slipped through to
`addPlanPanel` on a live update against an open panel), and add three
cases: eager-fetch on cold load, fetch gated on WS connect, and the
page-reload acknowledge.

* fix(web): guard the eager plan fetch against an infinite retry loop

`isLoading` flipping during the fetch was re-triggering the effect via
its own dep update — on persistent failure it would keep firing because
`isLoaded` never flips. Switch to a ref-keyed attempt set so each task
is fetched at most once per WS-connected session, and clear the set on
WS reconnect so transient failures still recover.

Also drop the redundant `activeTaskId` guard inside the auto-open
effect (`plan` is already derived from `activeTaskId`) and clarify the
catch-block comment.

Addresses Greptile P1 + Claude review suggestions on PR #749.

* test(web): cover the disconnect→reconnect retry + tighten code comments

Address Claude review on PR #749:
- attemptedRef comment now reflects what the clear actually does (clears
  all task IDs on WS disconnect, not per-task on navigation).
- Catch comment points at the disconnect/reconnect effect as the actual
  retry trigger instead of the misleading "useTaskPlan retries on panel
  mount" claim.
- Reload-acknowledge comment is honest about the lastSeen ambiguity:
  optimistic suppression of the indicator flash, with live-update path
  re-arming after a post-reload update.
- Added a regression test for the disconnect → reconnect → re-fetch
  path, which the previous test suite did not exercise.

* docs(web): clarify reload-acknowledge comment to match the actual control flow

* test(web): split test file under the 100-line per-function lint cap

The new eager-fetch + reconnect-retry tests pushed the top-level
describe callback to 114 lines, tripping max-lines-per-function. Split
into a sibling describe for the eager-fetch scope.

* fix(web): don't overwrite a WS-delivered plan with a stale null fetch

The HTTP fetch and the WS \`task_plan.created\` event can resolve in
either order on a fast auto-start: when the fetch was issued first
(server didn't have the plan yet, returns null) and the WS event arrives
mid-flight, the unconditional \`setTaskPlan(taskId, null)\` would clobber
the real plan that just landed. Read the live store state inside the
\`then\` and skip the write when null overlaps with a populated plan.

Adds a regression test for the race.

* docs(web): fix the disconnect/reconnect comment wording

Effect fires on disconnect, not reconnect — wording was inverted.

* fix(web): also guard the eager fetch against stale non-null overwrites

CodeRabbit caught a residual race: when a newer plan lands via WS while
the HTTP fetch is in flight, an older non-null HTTP response could
still clobber it (regressing updated_at + content). Compare timestamps
and skip the write when the live store entry is already at-or-newer.

Adds a regression test, splits the test file into a third sibling
describe so each callback stays under the 100-line lint cap.

* style(web): apply prettier formatting
2026-05-01 00:19:50 +01:00
João Salavisa 00a6567402 feat(mcp): add message_task_kandev tool (#745) 2026-04-30 22:53:13 +01:00
José Almeida 89332e1cbb fix: render passthrough terminal in quick chat (#744)
* fix(backend): start agent immediately for passthrough quick-chat sessions

Passthrough profiles need a running PTY for the terminal to attach. When
launchPrepare is called with a passthrough profile, upgrade the request to
launchStart so the PTY exists by the time the frontend renders the terminal.

* fix(web): render passthrough terminal in quick chat for passthrough profiles

Quick chat used MessageList + ChatInputArea unconditionally, so passthrough
profiles showed an empty chat with no agent output (PTY never attached).
Render PassthroughTerminal when the active session is passthrough, mirroring
the task-page branch. Passthrough is detected via session.is_passthrough or,
before WS hydrates, via the agent profile's cli_passthrough flag — looked up
through a new agentProfileId stored on quickChat session entries (set by the
picker on selection and seeded by SSR for restored sessions).

* style(web): apply prettier formatting

* fix(web): address review feedback on quick-chat passthrough rendering

- Narrow `metadata.agent_profile_id` to string at runtime via a
  `readAgentProfileId` helper instead of a blind type cast.
- Collapse `useIsQuickChatPassthrough` into a single `useShallow`
  selector to avoid three separate store subscriptions.

* fix(backend): prevent launchPrepare ↔ launchStart recursion for passthrough

When passthrough quick-chat sessions hit a workflow step that blocks
auto-start, launchStart's downgrade to launchPrepare would have re-upgraded
back into launchStart and looped forever. Skip the passthrough upgrade when
AutoStart=true, since that flag uniquely identifies the downgrade path.

Adds tests for `isPassthroughProfile` and a regression test that runs the
launchStart→launchPrepare path under a deadline so future recursions surface.

* test(web): cover existing agentProfileId preservation on reopen

* style(web): apply prettier formatting

* test(backend): seed task with blocked workflow step in recursion regression

Without persisted task and step, shouldBlockAutoStart short-circuited to
false, the test bypassed the launchStart→launchPrepare downgrade entirely,
and removing the recursion guard would still pass. Seed the task with a
WorkflowStepID mapping to a step lacking auto_start_agent so the guard is
the only thing preventing the bounce. Verified by temporarily removing the
guard — the test now times out as expected.

* test(backend): cover ResolveAgentProfile error path in isPassthroughProfile
2026-04-30 18:36:26 +01:00
João Salavisa 3d2a04e776 feat(orchestrator): deferred task move with hand-off prompt + boot/turn-end event split (#743)
* feat(orchestrator): reuse existing same-profile session on workflow step switch

When a workflow step transition needs a different agent profile, look up
an existing session on the same task that already uses the target profile
and promote it back to primary instead of creating a fresh one. Reuses
COMPLETED and FAILED sessions (CANCELLED stays excluded — explicit user
stops shouldn't be auto-revived).

Backend (event_handlers_workflow.go):
  - findReusableSessionForProfile: most recently updated session matching
    the target profile, skipping CANCELLED.
  - reuseSessionForStep: promotes the session to primary; if terminal,
    revives via reviveReusedSession.
  - reviveReusedSession: distinguishes "previously launched" (has
    executors_running record -> flip to WAITING_FOR_INPUT, lazy-resume via
    ResumeSession with stored token) from "never launched" (no record ->
    flip to CREATED so autoStartStepPrompt routes through
    StartCreatedSession for a full fresh launch). Clears stale
    ErrorMessage/CompletedAt so the UI stops surfacing prior failures.
  - createNewSessionForStep + completeAndStopSession: shared helpers.

Backend (task_operations.go):
  - StartCreatedSession no longer calls processOnTurnStartViaEngine.
    User-initiated messages already fire on_turn_start in
    dispatchPromptAsync. Workflow-driven auto-start prompts arrived
    because the workflow just transitioned us into this step via
    on_turn_complete; firing on_turn_start again cascades the workflow
    back out and the redirect-to-active-session logic delivers the prompt
    to the wrong session's agent.

Frontend (web):
  - task.updated handler follows focus to the new primary when the user
    is viewing the task and was sitting on the previous primary.
  - pinnedSessionId tracks user-initiated session selection
    (setActiveSession sets it; setActiveSessionAuto leaves it alone).
    The terminal-handoff branch in maybeAdoptSessionOnTransition skips
    replacement when the terminating session matches the pin, so manually
    clicking a session no longer yanks focus back to the workflow primary
    each time the pinned session terminates.

Tests:
  - TestSwitchSessionForStep_ReusesExistingProfileSession (never-launched).
  - TestSwitchSessionForStep_ReusesPreviouslyLaunchedSession (launched).
  - TestSwitchSessionForStep_ReusesFailedSession (FAILED reuse + cleanup).
  - tasks.test.ts: focus-follow behavior across 4 scenarios.
  - agent-session.test.ts: pinnedSessionId guard plus migration to
    setActiveSessionAuto for WS-driven adoption.

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

* feat(orchestrator): deferred task move with hand-off prompt + boot/turn-end event split

Adds move_task_kandev MCP tool that lets a workflow agent (e.g. QA at "Review")
move a task to another step with a prompt for the receiving agent. The move is
queued as a PendingMove and applied on the calling agent's turn-end so on_enter
processing doesn't race the still-running turn.

Also splits agent.ready into agent.boot_ready + agent.ready at the lifecycle
layer. Previously both signals shared one event and the orchestrator
disambiguated them via a resumeInProgressSessions flag — which had a race
when the boot signal arrived before persistResumeState wrote state=STARTING,
causing the boot to fire on_turn_complete against the just-revived step and
ping-pong the task forward through the workflow.

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

* fix: address PR #743 review feedback (Greptile + CodeRabbit)

Backend:
- isTransientPromptError no longer treats ErrExecutionNotFound as transient,
  preventing executeQueuedMessage from infinite-requeueing on permanent
  missing-execution errors. autoStartStepPrompt's explicit errors.Is check
  before the transient branch keeps the recovery path working (Greptile P2 #1)
- applyPendingMove drains the orphaned hand-off prompt on ApplyTransition
  failure so it can't be misdelivered to the source step on a future turn
  (Greptile P2 #2)
- handleMoveTask returns errors instead of panicking when messageQueue is
  nil; queueMoveTaskPrompt returns an error so the deferred path fails fast
  if the queue can't accept the prompt (CodeRabbit CR-2)
- handleMoveTask rejects when no primary session exists and a hand-off prompt
  is required, instead of silently dropping it (CodeRabbit CR-3)
- autoStartStepPrompt preserves attachments from queued messages (was: silently
  dropped); attachment-only messages are no longer skipped; the fallback path
  also forwards attachments (CodeRabbit CR-5)
- applyPendingMove reinserts the pending move on early failure paths (config
  missing, task/step load errors) so a future turn-end retries naturally
  (CodeRabbit CR-6)
- registerKanbanTools split into 3 helpers (list/profile/task) to satisfy
  backend function-size lint limits (CodeRabbit CR-1)

Web:
- maybeAdoptSessionOnTransition's auto-adopt path also checks pinnedSessionId
  to handle the reverse-event-ordering race (old COMPLETED arrives before new
  STARTING) — pinned sessions are no longer yanked off the user. Regression
  test added (CodeRabbit CR-7)

Tests:
- mockAgentManager records (executionID, prompt) pairs; new helper
  capturedPromptsForExecution actually filters by exec ID instead of
  returning all captured prompts (CodeRabbit CR-4)

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

* fix(web): respect pinned session in primary-follow-focus path

When the user clicks a session, setActiveSession sets pinnedSessionId. If a
workflow profile switch then updates the task's primarySessionId while the
user happens to still be on the previous primary, the focus-follow block in
tasks.ts was calling setActiveSessionAuto(taskId, newPrimary) and silently
overriding the explicit pin. Add pinnedSessionId !== previousPrimary as a
fifth condition. Regression test in tasks.test.ts covers exactly this
sequence.

Addresses Greptile P1 on PR #743.

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

* fix: address CodeRabbit review on PR #743 (3 new comments)

- handleMoveTask idle path now rolls back the queued hand-off prompt when
  taskSvc.MoveTask fails, so a "you were moved..." message can't be delivered
  on a future turn for a transition that didn't actually happen. Added
  TakeQueued to the MessageQueuer interface to support this.
- lookupSession now returns (*models.TaskSession, error) so callers can
  distinguish a backend lookup failure from a legitimate "no primary session"
  state. handleMoveTask maps the error case to ErrorCodeInternalError instead
  of collapsing it into ErrorCodeValidation.
- queueMoveTaskPrompt returns errors instead of log-and-continue (signature
  change already shipped); existing tests updated to reflect the new contract.
- Refactored TestPendingMove_ReviewToInProgress_OneTransitionOnly: the
  ~280-line monolithic test is now split into a pendingMoveScenario builder
  + assertion helpers, each well under the 80-line / 50-statement lint limit.

All 14 review threads resolved.

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

* fix: relax move_task_kandev prompt requirement; fix CI lint

CI surfaced two issues after rebasing onto main:

- nestif lint warning on autoStartStepPrompt's queued-message merge block.
  Extracted the take-and-merge logic into takeAndMergeHandoffMessage helper,
  flattening the nested conditionals.
- E2E test settings/config-management 'agent can move a task to a different
  step' failed because my CR-3 fix made the move_task_kandev prompt parameter
  required. That broke admin/config-mode moves where there's no agent to
  hand off to. Made prompt optional: when supplied AND the source session
  is mid-turn, the deferred-move flow runs (queue prompt + record
  PendingMove); otherwise just move the task. Refactored handleMoveTask
  into deferMoveTaskWithPrompt and applyMoveTaskImmediate to keep each
  function under the 80-line lint limit.

Tool descriptions in mcp/server/server.go and mcp/server/config_handlers.go
updated to reflect prompt's now-optional status. moveTaskHandler in
config_handlers.go forwards prompt only when set.

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

* fix(mcp): treat 'no primary session' as a not-found, not an internal error

GetPrimarySessionByTaskID returns a plain error string ("no primary session
found for task: <id>") when the repo has no rows. My CR-B refactor was
treating ALL lookup errors as ErrorCodeInternalError, which broke the E2E
test 'agent can move a task to a different step' (config-mode move on a
freshly-created task that has no agent yet).

Match the not-found message and return (nil, nil); only real backend
failures bubble up as InternalError. Distinguishing properly with
errors.Is would require an exported sentinel that doesn't exist; matching
the noRowsErr substring is the pragmatic fix.

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-04-30 18:17:36 +01:00
José Almeida aa70b7dfa4 feat(web): mobile terminal key-bar — Ctrl/Shift modify OS-keyboard input + iOS keyboard fixes (#741)
* feat(web): add mobile terminal key-bar with sticky Ctrl modifier

Mobile software keyboards lack Ctrl, Esc, Tab, arrows, and shell symbols,
so users had no way to interrupt a running command (Ctrl+C), escape an
editor, or navigate the shell. Adds a horizontally scrolling key-bar
above the virtual keyboard — sticky Ctrl modifier, dedicated Ctrl+C /
Ctrl+D buttons, and visualViewport-based docking so the bar tracks the
OS keyboard as it opens and closes.

* test(web): add E2E coverage for mobile terminal key-bar

Nine Playwright tests on the mobile-chrome project cover visibility
gating, key emission verified via captured WS frames, the sticky Ctrl
state machine, dedicated Ctrl+C / Ctrl+D buttons, keyboard-aware
docking, accessibility, and an end-to-end ^C echo to prove the shell
path works. Adds a reusable shell.input frame capture helper and a
small page-object for the key-bar.

* feat(web): shared shell input helpers for the mobile terminal

Introduces a small toolkit the next commit will wire into the mobile
key-bar:

- `refocusXtermTextarea` — re-focuses xterm's hidden textarea after a
  virtual-key tap so iOS Safari doesn't dismiss the soft keyboard.
- `suppressIOSKeyboardAssists` — strips name/autocomplete/data-* hints
  on the textarea so iOS / 1Password / LastPass / Bitwarden skip the
  AutoFill suggestion bar.
- `useShellModifiersStore` (Zustand) — module-level Ctrl/Shift latch
  state with toggle (off → latched → sticky → off) and consume actions.
- `applyShellModifiers` — pure transform: ctrl + a-z → control byte;
  shift + tab → CSI Z (reverse tab); single-char only.
- `sendShellInput` — single entry point that reads the store, applies
  the transform, sends over WS, and consumes latched modifiers.

`useShellKeySender` and the xterm `onData` path in `shell-terminal.tsx`
now route through `sendShellInput` so any future modifier state
propagates uniformly. `suppressIOSKeyboardAssists` is wired into
`useTerminalInit` immediately after `terminal.open()`.

* feat(web): mobile key-bar pivots to OS-keyboard input + pins to keyboard

Reworks the mobile terminal key-bar around two insights:

1. The OS soft keyboard already provides letters — duplicating them
   in-bar was confusing and didn't address the real problem (Ctrl
   couldn't modify what the user typed via the OS keyboard, because
   that input went straight to xterm and bypassed React state).

2. iOS Safari `position: fixed; bottom:` drifts during visual-viewport
   scroll while the keyboard is open. Anchoring via `top` tied to the
   visual viewport's bottom edge stays glued.

Changes:

- `MobileTerminalKeybar` reads Ctrl/Shift state from the shared
  `useShellModifiersStore` and toggles it on tap. The actual chord
  transform now happens in `sendShellInput`, which both the bar and
  xterm's `onData` path call — so a Ctrl latch set from the bar
  modifies the next character typed on the OS keyboard.
- Drops `LETTER_KEYS` and `chordChar` from the bar; adds a Shift
  toggle (Shift+Tab → reverse-tab from the bar; pairs with the
  modifier transform for OS-keyboard taps).
- Latched state now shows the same ring as sticky (with sticky using
  a stronger `ring-primary`), so the first tap is visibly active.
- `touch-action: manipulation` on each button so taps in the
  `overflow-x-auto` row don't get reinterpreted as scroll.
- `useVisualViewportOffset` exports `viewportBottom = offsetTop +
  height`. When the keyboard is open the bar uses `top: viewportBottom
  - KEYBAR_HEIGHT_PX` and `bottom: auto`; closed, it keeps the
  `bottom`-based positioning so it sits above the bottom nav.
- `SessionMobileLayout` computes the terminal panel's
  `paddingBottom` so terminal content's bottom edge sits exactly at
  the bar's top edge whether the keyboard is up or not.

Tests cover the new modifier flow, Shift+Tab, the absence of
in-bar letter buttons, and the `top`-anchored positioning when the
keyboard is reported as open.

* test(web): rewrite mobile key-bar e2e around real user flows

The prior e2e leaned on in-bar letter buttons that no longer exist.
Rewrites the spec around the journeys a mobile user actually performs:
tap ^C to cancel, latch Ctrl + type a letter on the OS keyboard, sticky
Ctrl across multiple chords, Shift+Tab from the bar, history nav with
the arrow button, Esc, symbol keys, and the iOS positioning fixes
(top-anchored when the keyboard opens, tracks visual viewport scroll,
terminal panel reserves space for the bar). Adds a `shift` getter to
the page object.

* style(web): apply prettier formatting

* fix(web): keep modifiers armed on dropped sends + tighten input handler

Addresses bot review on PR #741:

- `sendShellInput` no longer consumes Ctrl/Shift when the WS client
  isn't available — the chord stays armed so the user can retry once
  reconnected instead of seeing the latch silently clear.
- Adds `send-shell-input.test.ts` with the matrix the helper needs:
  empty data, ctrl chord + auto-release, sticky retention, shift+tab
  → CSI Z, shift passthrough on non-tab, and the WS-disconnected
  no-send/no-consume path.
- Removes dead `ctrlChord` export and its tests — the only consumer
  was its own test, and `applyShellModifiers` covers the same
  transform end-to-end.
- Drops the unused `send` parameter from `useShellInputHandler` (the
  effect now goes through `sendShellInput` directly), removing a
  spurious dep that would otherwise re-fire the effect on identity
  changes.
- Documents that `KEY_SEQUENCES.home`/`end` are intentionally readline
  shortcuts (Ctrl+A/E), not VT Home/End sequences, so future readers
  don't mistake it for a bug.

* refactor(web): split mobile key-bar helpers, tighten null-viewport test

Addresses two non-blocking suggestions from PR #741 review:

- Move `KeyDef`, `KEYS`, `ModifierButton`, and `KeybarButton` out of
  `mobile-terminal-keybar.tsx` into a sibling helpers file. The main
  component drops from 213 to 115 lines, comfortably under the 200-line
  component convention.
- Assert `viewportBottom === 0` in the null-viewport branch of
  `use-visual-viewport-offset.test.ts` so all three return-shape fields
  are covered there.
2026-04-30 14:05:35 +01:00
José Almeida 7f0eaf76e2 fix(web): contain kanban card badges within card width (#739) 2026-04-29 23:01:11 +01:00
José Almeida 47ff0804a5 feat(cli): make --port the user-facing port flag (#737)
* feat(cli): add --port flag as the user-facing port knob

Introduces --port (and KANDEV_PORT) as the primary, command-aware port
flag: in start/run it sets the Go backend port (the proxy front door
the browser actually hits), and in dev it sets the Next dev server port.
--backend-port and --web-port still work but emit a one-time stderr
deprecation note pointing at --port and --web-internal-port respectively.

* feat(cli): print labelled "open:" URL on startup

Replaces the ambiguous "[kandev] url:" / "ready at" lines with a
labelled block that always shows the user-facing URL first, plus the
backend (api) and web (internal) URLs when they differ. Each command
now declares its own publicUrl: backend in start/run (where the Go
server reverse-proxies Next.js), web in dev (browser hits Next direct).

* style(cli): apply prettier formatting to args.test.ts

* refactor(cli): tighten arg parsing per review feedback

- Validate value-taking flags (--port, --backend-port, --web-internal-port,
  --web-port, --version) and reject missing/non-numeric values with a clear
  ParseError instead of leaking NaN into the port validator.
- Drop the test-only _resetWarnedFlagsForTest export and the module-level
  warned-flag set; parseArgs now returns deduped deprecatedFlags and cli.ts
  emits warnings command-aware (e.g. --backend-port → KANDEV_BACKEND_PORT
  in dev, where --port maps to web).
- Stop double-printing the "open:" URL: logStartupInfo now lists labelled
  backend (api) / web (internal) URLs only, leaving the post-readiness
  open: line as the single source of truth.
- Fix help text: --web-internal-port works in dev too.
- Drop multi-line JSDoc blocks per CLAUDE.md style guide.

* fix(cli): validate env-var ports and collapse comment to one-liner

Catches non-numeric KANDEV_PORT / KANDEV_BACKEND_PORT / KANDEV_WEB_PORT in
envPort with a clear ParseError instead of letting NaN reach
ensureValidPort. Drops a multi-line comment per CLAUDE.md style.

* fix(cli): reject non-integer port values

Number.isFinite accepts floats like 3000.5 which then fail downstream
in ensureValidPort with a generic message. Tighten parsePort and
envPort to require integers and add float tests for both flag and
env-var paths.

* fix(cli): reject out-of-range port values with flag-named errors

Adds 1-65535 range checks to parsePort and envPort so values like 0,
-1, or 65536 fail with a flag/env-var-named ParseError instead of
reaching ensureValidPort with a generic 'backend port' label.

* test(cli): cover KANDEV_WEB_PORT happy path and range validation

* test(cli): cover KANDEV_WEB_PORT in run/start mode too

* fix(cli): explicit CLI flag wins over env var for port resolution

Previously KANDEV_BACKEND_PORT silently overrode --port because each
process port resolved its own env var before the generic --port
fallback. New precedence per process: explicit CLI flag > generic
--port flag > explicit env var > generic KANDEV_PORT. Also relabel
the startup info from "backend (api)" / "web (internal)" to plain
"backend" / "web" — "internal" was misleading in dev where the web
URL is what users open.

* style(cli): collapse resolvePorts comment to one line

* fix(cli): reject empty --version= and empty port env vars

- --version= (no value after =) now throws ParseError instead of
  silently storing the empty string as the version tag.
- envPort distinguishes unset (undefined) from empty (""); an empty
  KANDEV_PORT / KANDEV_BACKEND_PORT / KANDEV_WEB_PORT is now treated
  as misconfiguration and fails fast.

* refactor(cli): make --port a plain alias for --backend-port

Drops the command-aware split where --port mapped to web in dev and
backend in run/start. --port and --backend-port now both set
options.backendPort regardless of command, and KANDEV_PORT is a plain
fallback for KANDEV_BACKEND_PORT. The whole point of the original
fix was that the *backend port* is the URL users actually open in
run/start (because the Go server reverse-proxies Next.js); a single
flag that always means "the backend port" matches that mental model
without per-command surprises.

Removes deprecationReplacement and the command-aware warning logic
since the two flags are now interchangeable. --web-port → --web-internal-port
deprecation stays.

* test(cli): re-add KANDEV_WEB_PORT run-mode coverage dropped in refactor
2026-04-29 22:25:10 +01:00
Carlos Florêncio 3d93d9e93c fix(mcp): improve create_task_kandev repository and workspace resolution (#733) 2026-04-29 18:10:40 +01:00
Carlos Florêncio 183efad419 feat: expose MCP server to external coding agents (#732) 2026-04-29 10:37:44 +01:00
Carlos Florêncio 8fb2e5ba52 fix(lifecycle): publish agentctl events on workspace restore (#731) 2026-04-29 09:57:16 +01:00
Carlos Florêncio 4277ef495a fix(web): self-recover dockview layout from corrupt persisted state (#729) 2026-04-29 09:56:26 +01:00
João Salavisa c7274e84c1 fix(agentctl): populate diff for renamed-and-modified files in git status (#730)
* fix(agentctl): populate diff for renamed-and-modified files in git status

The numstat output uses notation like `old.txt => new.txt` for renamed
files, but the Files map is keyed only by the new path. Resolve numstat
paths to the new path before map lookup so RM file diffs are populated.

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

* test(agentctl): cover filename-starts-with-brace rename case

Adds a regression test for `{{page => layout}}.svelte` to lock in that
LastIndex on `{` correctly picks git's brace block over the filename's
leading literal `{`.

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-04-29 00:10:17 +01:00
João Salavisa 51cc14d028 refactor(worktree): drop unused flat-layout worktrees/ path (#708)
* refactor(worktree): drop unused flat-layout worktrees/ path

Every worktree creation now routes through the task-dir layout
(~/.kandev/tasks/{title}_{suffix}/{repo}/); the legacy flat layout
under ~/.kandev/worktrees/ has been unreachable since the subtasks
PR populated TaskDirName/RepoName unconditionally. Removes the dead
Config.BasePath, Manager.createWorktree, and the flat reconciler.

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

* refactor(worktree): remove unused Reconcile, add guard regression test

Address PR review feedback:

- Reconcile (and reconcileTasksDir / isOrphanedTaskDir) had no callers
  anywhere in the tree after the flat-layout removal. Deleted rather than
  left dangling; if startup orphan cleanup is wired up later it can return
  alongside its actual call site. Also moots the stale doc comment that
  CodeRabbit flagged.
- Add TestCreate_MissingTaskDirFields_ReturnsErrTaskDirRequired covering
  the three permutations (missing RepoName, missing TaskDirName, both
  missing) so a regression in the ErrTaskDirRequired guard surfaces in
  CI rather than silently.

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-04-28 22:42:54 +01:00
Carlos Florêncio ab16b03fa0 fix(web): preserve chat scroll position when maximizing panel (#728) 2026-04-28 22:31:52 +01:00
Carlos Florêncio 8694de20ea fix(web): prevent crowding in narrow changes panel and dockview tabs (#727) 2026-04-28 22:23:14 +01:00
João Salavisa 2416b8dd49 fix(orchestrator): drain queued message on workflow transition to non-auto-start step (#726)
* fix(orchestrator): drain queued message on workflow transition to non-auto-start step

A workflow transition (e.g. In Progress → Review) made handleAgentReady
early-return before draining the message queue, on the assumption that
the new step's auto_start_agent would handle the next prompt (#677). For
steps without auto_start_agent (Review, etc.) nothing ever drained the
queue and user-queued messages stuck forever.

Add drainQueuedMessageAfterTransition and call it from the two
processOnEnter paths that don't auto-start the agent (no on_enter
actions, and the default switch case). Restores pre-#677 behavior for
non-auto-start transitions while keeping the deadlock fix for
auto-start steps intact.

Includes regression test covering the no-on_enter-actions case.

* fix(orchestrator): address PR review feedback on queue drain

- Log a Warn when drainQueuedMessageAfterTransition discards an empty
  queued message, matching handleAgentReady's behavior. (Claude)
- Fix data race on mockAgentManager.capturedPrompts surfaced by `-race`:
  PromptAgent now appends under the existing mu, and adds an opt-in
  promptDone channel so tests can wait deterministically. (Claude)
- Replace sleep-based polling in the new regression test with a select
  on promptDone — matches the project's no-time.Sleep guideline.
  (Claude, CodeRabbit)
- Drain the queue in the sessionSwitched + step.Prompt error handler
  goroutine in processOnEnter — same orphan-queue class of bug as the
  rest of this PR, just on a different no-auto-start path. (Greptile P1)

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-04-28 15:40:32 +01:00
João Salavisa fbe2410fdb feat(web): hide Jira buttons when disabled or auth failing (#725)
* feat(web): hide Jira buttons when disabled or auth failing

Hide the Jira import button on the task creation dialog and the "Link Jira" button on the task top bar when the workspace toggle is off, no Jira config exists, or the most recent backend auth probe failed. Centralizes the gating logic in a shared useJiraAvailable hook.

* fix(web): address PR review feedback on Jira availability gate

- Gate the auth probe on `loaded` from useJiraEnabled so it never fires when the toggle starts disabled
- Reset cached auth on workspace change so the previous workspace's `true` can't briefly leak into the new one
- JiraTopbarButton now consumes the shared useJiraAvailable hook instead of replicating the two-step gate inline

* fix(web): apply prettier formatting to use-jira-availability.ts

* fix(web): tag Jira auth state with workspaceId to avoid poll-tick flicker

Storing `{workspaceId, authed}` together and filtering at read time invalidates stale auth synchronously when the workspace switches, removing the need for a setAuthed(false) reset that was previously firing on every 90s poll tick. Adds a fake-timer test that asserts no false render slips through across a poll tick while auth stays healthy.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-04-28 11:50:30 +01:00
José Almeida 2e2bd441c6 fix(passthrough): apply profile cli_flags to passthrough command (#722)
* fix(passthrough): apply profile cli_flags to passthrough command

PassthroughOptions had no CLIFlagTokens field, so the passthrough
launch path silently dropped profile-configured cli_flags. Mirror the
ACP launch path: resolve via cliflags.Resolve and append the tokens
through StandardPassthrough.BuildPassthroughCommand.

Fixes #718.

* fix(passthrough): skip auto-restart on fast-fail launch errors

A bad CLI flag, missing binary, or auth failure makes the agent
process exit immediately. The auto-restart loop then thrashed
forever, spamming "[Agent exited. Restarting...]" without ever
recovering.

Track the start time of each passthrough process and short-circuit
the restart path when an exit lands within 2s with a non-zero code.
Surface a one-shot terminal banner pointing the user at the likely
fix instead.

* refactor(passthrough): snapshot start time at call site to avoid race

Claude review on PR #722: handlePassthroughExit ran in a goroutine and
read execution.PassthroughStartedAt while the next launch could
concurrently write it. Snapshot the value synchronously in
handlePassthroughStatus and thread it through; isFastFailExit now
takes the start time directly.

Also extracts attemptPassthroughRestart and notifyFastFailExit to
keep handlePassthroughExit under the funlen limit.

* refactor(passthrough): measure fast-fail uptime from status timestamp

Claude review on PR #722: handlePassthroughExit's uptime measurement
folded in the cleanupDelay sleep (~100 ms), so the logged duration was
systematically inflated and a process that died at, say, 1.95 s would
slip past the 2 s cutoff.

Use status.Timestamp (set when the child actually exited) as the exit
time and pass it through to isFastFailExit. notifyFastFailExit now
receives a pre-computed uptime so the log reflects real child runtime.
2026-04-28 00:08:42 +01:00
José Almeida 5cfcfb437e feat(web): add GitHub dashboard shortcut to command panel (#721) 2026-04-27 22:50:08 +01:00
Carlos Florêncio 6b35b54a51 fix: restore release changelog boundaries (#716) 2026-04-27 21:36:50 +01:00
Carlos Florêncio 7f0fe7de1f release: app v0.38, cli 0.16.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.38
2026-04-27 19:44:04 +01:00
João Salavisa 2a3df653f7 feat(filters): add 'Has PR' task sidebar filter (#713)
Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-04-27 18:28:40 +01:00
Carlos Florêncio d961d1b430 fix(web): scope settings workflow list to current workspace (#714) 2026-04-27 18:28:09 +01:00
João Salavisa 8bf97911d5 fix(orchestrator): plug zombie turn leak pinning sessions to RUNNING (#712)
* fix(orchestrator): plug zombie turn leak pinning sessions to RUNNING

Two independent code paths lazily created turns without sharing state.
service.CreateMessage (DB-based) created a turn for inbound user
messages; PromptTask then unconditionally created another via
startTurnForSession (in-memory + DB). The first turn was never tracked
by the orchestrator, so its completed_at never got set and the session
state machine kept the session pinned to RUNNING forever — the "agent
is processing" spinner that wouldn't clear.

- startTurnForSession is now idempotent: adopts an existing open turn
  from the in-memory map or the DB before creating a new one.
- completeTurnForSession is now DB-authoritative: the in-memory map is
  a hint, the DB is truth. Loops to mop up multiple pre-existing
  zombies with a sanity bound.
- CancelAgent captures the turn ID before agentManager.CancelAgent so
  the cancel message can't race the agent's complete event into a
  phantom turn.
- service.GetActiveTurn returns (nil, nil) for "no active turn" instead
  of leaking sql.ErrNoRows.

Adds five regression tests covering adoption, idempotency, untracked
close, multi-zombie sweep, and double-complete idempotency.

* fix(orchestrator): address PR review feedback on turn lifecycle

- Log DB read errors in startTurnForSession adoption path so transient
  failures aren't silently swallowed (Claude, CodeRabbit, Greptile).
- completeTurnForSession probes once after the iteration cap and only
  warns when a turn is *still* observed — closing exactly maxIterations
  is no longer a false alarm (CodeRabbit).
- Clarify the CompleteTurn-failure log: returning early defers cleanup
  to the next sweep rather than silently dropping zombies (Greptile).
- Route getOrStartTurn through GetActiveTurn so ErrNoRows normalization
  is the single contract (Claude).

Adds TestCompleteTurnRespectsIterationCap to lock the cap behavior.

* fix(orchestrator): align getOrStartTurn observability with adoption path

Log DB read errors in getOrStartTurn before falling through to
StartTurn — same observability contract as the orchestrator's
startTurnForSession (Claude review on the previous fix-up).

Also add a comment in turn_lifecycle_test.go explaining the
hardcoded "task1" TaskID in repoTurnService matches seedSession,
so future test authors reusing the helper know the coupling.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-04-27 17:41:22 +01:00
Carlos Florêncio b805bf796a fix(settings): toggle off default-on curated CLI flags (#711) 2026-04-27 16:42:24 +01:00
José Almeida 12bd5b2cf3 feat: plan checkpointing with rewind UI (#694)
* feat(backend): plan revision history with checkpoint/revert

Persist every plan edit as an immutable TaskPlanRevision with author
attribution (agent vs user) and expose WS actions to list, fetch, and
revert to past revisions. Emits task_plan.revision.created and
task_plan.reverted events so the UI can react in real time.

* feat(web): plan revision history UI with rewind to past versions

Add a rewind button to the plan panel that opens a revisions list
showing each checkpoint with author (agent name or user) and timestamp,
and lets the user restore any past revision as the new head. Plan
state, hooks, and WS handlers are extended to load, cache, and react
to revision-created/reverted events.

* test(web): e2e coverage for plan checkpointing and rewind

Cover the full revision flow: plan edit creates a checkpoint,
the revisions panel lists authors and timestamps, and reverting
restores the selected revision as the new head. Extends session
page object and backend fixtures with revision-related helpers.

* fix(web): stabilize plan revisions state and avoid re-render loop

Zustand selector returned a fresh [] for missing revisions, fanning out
re-renders that tripped React's infinite-loop guard when the plan panel
mounted. Swap to a frozen empty-array sentinel, auto-load revisions on
mount so WS events fired before connect aren't lost, and gate the
popover's on-open fetch so reopening doesn't re-sort rows mid-click.

* test(web): make plan checkpointing e2e resilient to agent auto-layout

Agent-authored plan writes auto-open the plan panel and can push the
chat tab inactive, so the chat idle placeholder isn't always visible
once the agent finishes. Accept either chat or plan panel as the idle
signal, make openPlanPanel and openRewind idempotent, reopen the
popover after a revert cancel (the confirm dialog closes it), and drop
the toast assertion since no Toaster is mounted in the app.

* fix(backend): atomic plan revision write + review polish

- Add `WritePlanRevision(ctx, head, rev, coalesceLatestID)` repository method
  that wraps HEAD upsert + MAX+1 compute + insert/merge in a single write tx,
  closing the TOCTOU race on `revision_number` and partial-failure divergence
  between HEAD and history. `upsertPlan` and `RevertPlan` both route through it.
- Add `ErrRevisionIDRequired`; return it for empty `TargetRevisionID` (was
  previously conflated with `ErrRevisionNotFound`). Handler maps to validation.
- Backfill fallback `author_kind` changed `"user"` → `"agent"` to match
  `CreateTaskPlan` and the column default.
- Extract shared `revisionSelectCols` constant; rename `max` local (shadowed
  Go builtin) and `dto` local (shadowed package name).

* fix(web): address plan-revisions review feedback

- `mcpWrite` uses `JSON.stringify(content).slice(1, -1)` to escape backslashes,
  quotes, and control chars in one pass — closes the CodeQL finding.
- `clearTaskPlan` now evicts `revisionContentCache` entries for the task's
  revisions before dropping the maps, preventing orphaned cache growth.
- `RevertConfirmDialog` wraps `onRevert` in try/catch/finally so rejections
  surface a toast and the dialog always dismisses.
- Hoist `TaskPlanRevision` import in `task-plan-panel.tsx`.
- `RevisionRow` derives relative time from props every render with a 30s tick,
  so prop changes refresh immediately.
- Strengthen author-switch e2e with `.not.toBeEmpty()` to also reject empty or
  truncated renders.

* fix(web): evict revision content cache on coalesced update

Coalesced writes update an existing revision's content on the backend, but
the WS `upsertPlanRevision` payload carries only metadata. Without eviction,
a cached preview of the revision stays stale after the agent re-writes the
plan within the coalesce window.

* fix(web): plan history UI polish from local testing

- Drop the redundant "Plan" title in the panel header bar; the dockview/mobile
  tab already labels the panel.
- Author display: show "You" with the user icon for user-authored revisions,
  and the agent profile name with the AgentLogo (resolved from the active
  session's `agent_profile_snapshot.agent_name`) for agent revisions, matching
  the icon used elsewhere in the app.
- Replace ScrollArea with a plain `max-h-96 overflow-y-auto` div so the
  popover stays bounded when revision counts grow past ~7 rows.
- Drop the em dash from the revert dialog description.

* feat(web): add lineDiff helper for plan revision compare

Tiny wrapper around the `diff` package that classifies each line as add /
remove / context and strips the trailing-newline phantom entry. Also exposes
`diffSummary` for the dialog header counts. Pure functions; backed by Vitest.

* feat(web): plan revision preview + compare state

Adds two task-scoped store keys for the new dialogs:

- `previewRevisionIdByTaskId` — at most one open preview per task; cleared on
  `clearTaskPlan`.
- `comparePairByTaskId` — ordered 2-slot pair. `toggleComparePair` reuses a
  `nextPair` helper that handles unselect (already-picked id), fill (open
  slot), and FIFO eviction (full pair). `clearTaskPlan` resets it too.

* feat(web): plan revision preview + diff dialogs

- `useTaskPlan` exposes `previewRevisionId`, `setPreviewRevision`,
  `comparePair`, `toggleCompareSelection`, `clearComparePair` (extracted into
  `usePreviewCompareState` to keep the surrounding hook within the size cap).
- New `PlanRevisionPreviewDialog`: read-only modal for a single revision with
  Restore + "Compare with current" CTAs. Restore routes through the existing
  RevertConfirmDialog so the confirmation copy stays consistent.
- New `PlanRevisionDiffDialog`: line-level unified diff between two revisions
  with adds/removes highlighted; orders the pair by revision_number so the
  older one is always "before"; Restore targets the older side.
- Popover row split into a clickable body (opens preview), a Compare toggle
  (icon button per row), and the existing Revert button. Compare chips appear
  at the top of the popover with a Diff CTA when both slots are filled.
- Both dialogs are remounted via key on revision/pair change so loader state
  resets without ESLint-flagged setState-in-effect resets.

* test(web): e2e coverage for plan preview and compare-diff dialogs

Extends the SessionPage POM with locators for the new preview and diff
dialogs (chips, compare toggle, restore buttons, body + summary). Adds two
scenarios in plan-checkpointing.spec.ts:

- Click a revision row body → preview shows the right content; the Restore
  CTA opens the existing confirm dialog and the revert lands.
- Toggle compare on two revisions → diff opens with v1 → v2 ordering and
  shows at least one add and one remove line; the Restore CTA targets the
  older side.

* feat(web): render markdown in plan preview + diff dialogs

Adds a shared `PlanReadOnlyMarkdown` Tiptap renderer that reuses the same
StarterKit + tiptap-markdown + tables/tasks/code-block extensions as the live
plan editor (minus interactive bits — slash menu, drag handles, comment
marks). Wired into both dialogs:

- Preview replaces the raw `<pre>` block with the rendered Tiptap view.
- Diff dialog now stacks two rendered sides (Before / After) with red/green
  tinted borders, kept above the existing line-level breakdown so the user
  gets both rendered comparison and an exact textual change list.

Tiptap doesn't ship a free diff/track-changes extension (it's part of Tiptap
Pro), so the side-by-side rendering plus the line-level list together stand
in for that.

* fix(web): plan diff dialog — text-only with unified/split modes

Following local feedback:

- Drop the rendered-markdown side-by-side panes from the diff dialog. Diff
  view is text-only again, like a code review.
- Add a Unified / Split mode toggle. Split mode aligns each remove with the
  adjacent add on the same row (single-line edits stay paired) and stripes
  empty cells where one side has nothing.
- Fix the highlight-truncation bug: long lines used to lose their tinted
  background past the viewport on horizontal scroll because the row width
  was capped to the visible area. Rows now use `min-w-full w-max` so the
  background extends through the full scroll width.

Preview dialog keeps the rendered Tiptap markdown — only the diff reverted
to plain text.

E2E covers both modes and the cell kinds.

* feat(web): formatPreciseTime util for minute-level timestamps

Returns 'just now', 'Xs ago', 'Xm ago' for the first hour, then 'Today, HH:MM',
'Yesterday, HH:MM', or '{Mon} {DD}[, YYYY], HH:MM' for older entries — keeps
exact minute-of-day visible instead of decaying to 'yesterday'/'2d ago'.

* fix(web): render markdown via setContent in plan read-only renderer

The tiptap-markdown extension's parser only fires on `setContent` calls, not
on the initial `content` option. Passing `content: value` to `useEditor` was
treating the markdown source as raw text, so the preview dialog rendered
unparsed markdown.

Drop the `content` option and instead call
`editor.commands.setContent(content, { emitUpdate: false })` from a useEffect
once the editor is created — which is what the live plan editor effectively
relies on through tiptap-markdown's setContent override.

* fix(web): plan history UX — bigger modals, split layout, simpler compare

- Bump dialog widths: preview now `max-w-5xl w-[92vw]`, diff
  `max-w-6xl w-[95vw]`, both with taller max-height. Plenty of room for
  rendered markdown and side-by-side diffs.
- Replace the table-based split layout with a CSS grid (`grid-cols-2 w-max`).
  The table-fixed cells were overflowing into each other when content was
  wider than half the dialog; the grid lets the natural width drive a single
  horizontal scrollbar on the parent and keeps the two columns properly
  separated.
- Switch row timestamps to `formatPreciseTime` so users see minute-of-day
  ("Today, 14:32", "Yesterday, 09:14", "Apr 21, 11:08") instead of decaying
  to "yesterday".
- Simplify the compare flow: drop the per-row Compare toggle, the chip strip
  at the top of the popover, and the standalone "Diff" button. Compare is
  now a side effect of preview — open any version, then click "Compare with
  previous" or "Compare with current". E2E test updated to use the new path.

* test(web): update plan checkpointing e2e for the new compare flow

Drops the locators for the row Compare toggle, chips, and standalone Diff
button (those UI bits are gone). Adds a locator for the new
"Compare with previous" preview button. The compare scenario now opens the
diff via preview → "Compare with current" instead of the old chip flow.

* fix(web): preview renderer reuses live editor's markdown styles

`globals.css` keeps heading sizes / list spacing / code-block padding under
.markdown-body and .tiptap-plan-wrapper, and the live editor opts in by
applying both classes (plus a conditional .dark for theming). The read-only
renderer was using `prose prose-sm` instead, which doesn't actually take
effect on the .ProseMirror node — leaving everything the same size.

Switch the read-only renderer to the same class set, follow the live
editor's `useTheme` -> `dark` pattern, override `!h-auto` so the renderer
sizes to its content, and trim the editor's default 0.75rem padding inside
the dialog body.

* fix(web): split diff has fixed width with synced horizontal scroll

The previous split layout grew the whole dialog wider when content overflowed
which felt wrong. Now:

- The dialog stays at its fixed width.
- Each pane has its own `overflow-x-auto` so each side is capped at half the
  dialog and gets its own horizontal scrollbar.
- A scroll listener keeps both panes' `scrollLeft` in lockstep (with a
  re-entrancy guard so the bounce-back doesn't form a loop) — corresponding
  rows stay aligned visually no matter which side the user scrolls from.
- The diff body's overflow-x is hidden in split mode (the panes own it) and
  only overflow-y stays on the body so vertical scroll covers both panes
  at once.

* feat(backend): resolve agent profile name from session for plan revisions

The MCP-side handlers (handleCreateTaskPlan / handleUpdateTaskPlan) don't
carry the agent's display name in the request, so without a lookup every
agent-authored revision was rendering as the literal "Agent" fallback in
the history UI.

PlanService now looks up the task's session and reads the agent profile
display name from `agent_profile_snapshot` (preferring "label", then
"name", then "agent_display_name") when the request is an agent write
without an explicit author_name. Active session is tried first; falls
back to the most recent session by started_at so plans written between
turns still get the right author name. If no usable session/snapshot
exists, the existing "Agent" fallback applies.

The repo dependency type is widened from `repository.PlanRepository` to a
small private `planRepo` interface that adds the two session lookups —
the SQLite repository (`*sqliterepo.Repository`) already implements both,
so no caller wiring changes.

* fix(web): plan history popover row + restore button polish

- Popover content's default `gap-4` between flex children (from
  @kandev/ui's PopoverContent) was rendering as visible space above the
  top-most row. Override with `gap-0` so the list sits flush against the
  header.
- Switch row layout from `items-start` to `items-center` so the
  Restore button stays vertically centered against the row body even
  when the body grows taller (timestamp + restored-from marker on revert
  rows).
- Rename the per-row "Revert" button to "Restore" and prefix it with
  IconRestore so it matches the dialog wording and the restored-from
  marker icon. The data-testid stays `plan-revision-revert-button` for
  e2e selector stability.

* fix(backend): plan revision review feedback + lint

- `wsGetTaskPlanRevision` now returns a 400 validation error when
  `revision_id` is empty, matching `wsRevertTaskPlan`'s
  `ErrRevisionIDRequired` branch (was silently mapped to 404 via the
  service's lookup miss).
- `agentDisplayNameFromSnapshot` tries `name` first, then `label`, then
  `agent_display_name`. The orchestrator's canonical key wins over any
  stale older `label` that may still be in a session snapshot.
- Add `idx_task_plan_revisions_task_number` on
  `(task_id, revision_number DESC)`. `GetLatestTaskPlanRevision` runs on
  every plan write (coalesce check); the existing `(task_id, created_at)`
  index doesn't help since these queries order by `revision_number`.
- Drop `Deprecated:` from `NextTaskPlanRevisionNumber`'s doc comment so
  staticcheck stops flagging the existing test usage. The TOCTOU caveat
  stays in the prose.

* fix(web): plan revision review feedback, prettier, e2e resilience

- `loadRevisionContent` reads `revisionContentCache` lazily through the
  store API inside the callback, so its identity stays stable. Selecting
  the cache map at the hook level was recreating the callback whenever
  any task's content was cached, retriggering downstream content-fetch
  effects.
- `task.plan.reverted` WS event becomes a no-op handler.
  `task.plan.revision.created` fires for the same row first and already
  upserts; the duplicate handler was double-evicting the
  `revisionContentCache` entry and triggering an extra Zustand update.
- e2e: agent author assertion now uses `not.toHaveText("You")` +
  `not.toBeEmpty()` instead of the literal `"Agent"` (which only
  matched the legacy fallback — agent rows now resolve to the profile
  display name).
- e2e: `openPlanPanel` retries the toggle a few times after a page
  reload — the panel toggle can race hydration and silently no-op,
  which broke the persistence test.
- Apply prettier to the files flagged by the formatting check.

* fix(plan): toast on silent revert failure + revision ownership check

- task-plan-revisions: when `onRevert` (the hook's `revertTo`) swallows
  the error and returns null, the dialog used to close silently with no
  feedback. Add an `else` branch that fires `toast.error("Failed to
  restore plan")`.
- wsGetTaskPlanRevision: accept an optional `task_id` and reject with a
  400 "Revision does not belong to task" when the loaded revision's
  task doesn't match. Mirrors `wsRevertTaskPlan`'s ownership check so a
  WS client can't read content for an arbitrary revision UUID outside
  the tasks it already holds a reference to.
- plan-api `getPlanRevision` takes optional `taskId`; `loadRevisionContent`
  threads the active task id so the check is exercised on the happy path.
2026-04-27 10:22:58 +01:00
João Salavisa 8948ebdb25 fix(acp): flush ScheduleWakeup output via synthetic prompt (#706) 2026-04-26 21:07:22 +01:00
Carlos Florêncio 5644b0ad18 feat(preview): add PR preview environments via Sprites (#707) 2026-04-26 18:14:41 +01:00
José Almeida ec9637c517 feat: opt-in fresh-branch checkout for local executor task creation (#695) 2026-04-25 23:53:43 +01:00
João Salavisa 54b98ed9eb feat(jira): add Jira integration for ticket browsing, import, and task linking (#705)
* feat(jira): add Jira integration for ticket browsing, import, and task linking

Adds a workspace-scoped Atlassian Cloud integration: per-workspace settings
(site URL, email, API token or session cookie), encrypted secret storage,
and a REST client for tickets, projects, search, and transitions. A
background poller probes credentials on a 90s cadence and the keepalive
runs immediately on save so the UI's connected indicator updates without
delay.

The /jira page provides ticket browsing with filter pills, custom JQL,
saved views (including JQL), and configurable task-launch presets that
prefill TaskCreateDialog. JiraLinkButton on the task top bar links an
existing task to a ticket by prepending its key to the title; the ticket
popover surfaces details, transitions, and re-auth prompts on session
expiry. Topbar shows separate icon buttons for GitHub and Jira when each
is configured.

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

* fix(jira): address PR review feedback

- Token-based pagination (pageToken/isLast) replaces broken offset/total pagination
- Race-fix in service.clientFor: re-check cache after acquiring write lock
- sync.Mutex guards poller started/cancel state against concurrent Start/Stop
- Channel-based + atomic.Int32 test sync replaces time.Sleep polling in poller_test
- Async auth probe on SetConfig with detached context.Background goroutine
- Distinguish 4xx vs 5xx in httpSetConfig via ErrInvalidConfig sentinel
- Propagate 4xx APIErrors from ListTransitions in GetTicket
- Distinguish "not found" from real errors in jiraSecretAdapter.Exists
- Log secret Exists errors instead of swallowing
- walkADF: handle softBreak (was only hardBreak despite the doc-comment)
- Consolidate JIRA_KEY_RE in jira-ticket-common; remove duplicates
- ticket-row imports formatRelative/statusBadgeClass from common
- isFilterState type guard validates SavedView.filters shape
- task-presets readStorage preserves user's "cleared all" intent (returns [])
- task-presets-section gates draft sync on `loaded` to avoid wiping in-progress edits
- jira-api: caller `init` no longer overrides method/body via spread order
- jira-settings: disable Test button when no saved/typed secret

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

* fix(jira): record auth probe failure even when probe ctx expires

- RecordAuthHealth now uses a fresh context.Background-derived ctx with a
  5s timeout for the UpdateAuthHealth DB write, so a probe that consumes
  its full 15s deadline still persists the failure (greptile P1).
- SetConfig goroutine drops its redundant outer timeout — RecordAuthHealth
  manages its own probe timeout, so context.Background is enough.
- Add Service.SetProbeHook so tests can synchronize on probe completion;
  service_test waitForAuthProbe now blocks on the hook channel instead of
  time.Sleep polling.

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

* fix(jira): address coderabbit review feedback (round 3)

- url.PathEscape ticketKey in GetTicket/ListTransitions/DoTransition paths
  to harden against malicious keys ('../../foo', 'KEY?override=x').
- factoryHit on the test fixture is now sync/atomic.Int32; the async probe
  goroutine spawned by SetConfig races the test thread under -race.
- GetConfig logs Reveal failures (was silently dropped, leaving the UI to
  show "no expiry info" indistinguishably from a freshly-saved cookie).
- DeleteConfig logs secret-delete errors instead of swallowing them.
- clientFor distinguishes a secret-store failure from "not configured" so
  the UI doesn't render the configure-CTA for transient backend errors.
- Unify ErrNotConfigured wire code: HTTP and WebSocket both return
  "JIRA_NOT_CONFIGURED" via a shared constant.
- JiraLinkButton strips a leading "PROJ-123: " before re-prefixing so
  re-linking a task replaces the prefix instead of stacking it.
- jira-settings clears testResult on save/delete so the alert reflects
  only the currently-saved credentials.

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

* test(jira): cover Reveal error path in clientFor

Reveal-error case is distinct from "no config row" — the former wraps
the underlying error, the latter returns ErrNotConfigured. Without
this test the changed contract has no regression coverage.

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

* fix(jira): route secret adapter Set through Exists

Treating every Get error as "not found" turned a transient DB error on
an existing row into a constraint-violation Create that masked the real
cause. Reuse Exists so the "secret not found:" prefix is the only path
that falls through to Create.

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

* test(jira): cover jiraSecretAdapter.Set branching

Routing Set through Exists changed the contract: a transient DB error
in Get now propagates instead of cascading into a constraint-violation
Create. Add three tests so a future refactor cannot regress this without
CI catching it.

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

* fix(jira): split Reveal errors and guard Save for new configs

- resolveCredentials now mirrors the clientFor split: a Reveal error
  surfaces as `read jira secret: %w` with a warn log instead of
  collapsing into "no token stored — paste one to test".
- disableSave gains the same missing-secret guard as disableTest so a
  brand-new config can no longer POST an empty secret and leave the
  workspace stuck with hasSecret=false.

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-04-25 22:47:45 +01:00
Carlos Florêncio b04967bf70 fix(web): show skeleton in file tree header while workspace path loads (#704) 2026-04-25 21:42:59 +01:00
Carlos Florêncio 7a2160f1f9 feat: show repository scripts in dockview "+" menu (#703) 2026-04-25 18:40:31 +01:00
Carlos Florêncio a79fd85074 fix(sprites): use bash for prepare scripts and fix pnpm install in sprites env (#701) 2026-04-25 18:39:55 +01:00
Carlos Florêncio db5999a618 feat(web): distinguish CI-passed PRs awaiting review from ready-to-merge (#702) 2026-04-25 18:21:59 +01:00
Carlos Florêncio d431688557 feat(web): auto-open plan panel with unseen-changes indicator (#650) 2026-04-25 18:21:33 +01:00
Carlos Florêncio 22ebba30b3 feat(skills): add /spec for writing feature specs (#700) 2026-04-25 17:26:14 +01:00
Carlos Florêncio 74d44bd26b feat(acp): support claude-acp Monitor tool and fix incremental tool_call updates (#698) 2026-04-25 16:26:20 +01:00
Carlos Florêncio 9dc1065010 fix(web): align sidebar filter toolbar height with panel headers (#699) 2026-04-25 15:59:36 +01:00
Carlos Florêncio efd68db15b fix: derive sidebar session state from most active session (#697) 2026-04-25 13:44:06 +01:00
Carlos Florêncio 627b4aee98 fix: auto-resume failed sessions with silent workspace-restore fallback (#696) 2026-04-25 11:31:42 +01:00
Carlos Florêncio 7efca36a2c release: app v0.37
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.37
2026-04-25 10:13:34 +01:00
João Salavisa 75f1732421 feat: add GitHub token injection for remote executors and Docker session resume (#654)
* feat: add GitHub token injection for remote executors and Docker session resume

- Add global GitHub access token configuration (backend + frontend)
- Inject GitHub token into Docker and Sprites executors via env vars and Git credential helper
- Transition Docker executor from host mounting to repository cloning
- Implement Docker session resume (reconnect to existing containers after backend restart)
- Add shell validation using exec.LookPath in agentctl
- Add scriptengine providers for agent install and agentctl placeholders

* fix: format github-status.tsx with prettier

* fix: resolve lint issues (goconst, errcheck, file-length)

* fix: address code review findings

- Fix resolveGHCLIToken to check both GITHUB_TOKEN and GH_TOKEN guards
- Fix credential helper to use \\ fallback
- Change /bin/bash to /bin/sh in credential helper for Alpine compat
- Strip embedded token from .git/config after clone in prepare scripts
- Extract buildLaunchAgentRequest helpers to stay under 80-line limit
- Add tests for GitHubAuthProvider, injectTokenIntoURL, reconnect validation
- Add GH_TOKEN-only test case for resolveGHCLIToken

* refactor(executor): extract GitHub credential resolution to separate file

Move injectGitHubToken, injectGitHubTokenFromCLI, resolveRemoteCredentials,
resolveAuthSecrets, methodIDToEnvVar, resolveGHCLIToken, and detectGHToken
out of executor_execute.go (was 803 logical lines, over the 800-line limit
after merging main) into a new executor_credentials.go file. Also adds the
nil-guard on secretStore in resolveAuthSecrets that was flagged by review.

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

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 22:15:50 +01:00
Carlos Florêncio c092fdeb1c fix: ui polish — unified topbar, selector consistency, quick actions editor improvements (#693) 2026-04-24 21:31:46 +01:00
Carlos Florêncio 1fc3544625 fix: subtask sessions inherit agent profile from parent task (#692) 2026-04-24 21:31:36 +01:00
José Almeida 046ac5c1b6 feat(web): add Ctrl+F search to session, plan, and terminal panels (#686)
* feat(backend): add session-scoped message search endpoint

Adds SearchMessages across repository/service/handler layers and a new
WebSocket action "message.search". Returns lightweight hits with a
60-char snippet around the first match. Session-scoped only: results
never leak across sessions. Uses dialect-aware LIKE/ILIKE so it works
on SQLite today and Postgres later.

* feat(web): add shared panel search bar and Ctrl+F hook

Introduces the reusable PanelSearchBar overlay and usePanelSearch hook
used by the per-panel search features. The hook listens on the window
and fires only when focus is within the panel root, preventDefaults the
browser find-in-page, and wires Esc to close. PanelRoot becomes a
forwardRef so panel components can expose their root element to the
hook. Adds SHORTCUTS.FIND_IN_PANEL plus shared highlight/flash styles.

* feat(web): add Ctrl+F search to terminal panels

Mounts the xterm addon-search on both passthrough and shell terminals,
exposing next/prev plus case-sensitivity and regex toggles. Invalid
regex surfaces an inline error without firing the search. Because xterm
consumes keystrokes before React, the Ctrl/Cmd+F intercept is added to
attachCustomKeyEventHandler so the shortcut opens the bar from inside
the terminal. Results counter comes from onDidChangeResults; decorations
clear on close.

* feat(web): add Ctrl+F search to plan panel

Adds a custom TipTap extension that builds a ProseMirror DecorationSet
over the document and exposes setPlanSearchQuery / planSearchNext /
planSearchPrev / clearPlanSearch commands. The current match gets an
extra class and scrolls into view. Match count is read from the plugin
state via transaction subscription, so edits to the document update the
counter automatically. Find-only — no replace.

* feat(web): add Ctrl+F search to session chat panel

Wires the new backend message.search action into a debounced client
hook and renders a hits dropdown under the search bar, with the query
highlighted in each snippet. Clicking a hit scrolls the message into
view and flashes it. When the target message is older than what is
currently loaded, the hook loops through loadOlder pages until the
message renders, making search work across lazy-loaded history without
needing to scroll-and-wait manually.

* fix(web): lazy-load xterm addon-search to avoid SSR crash

addon-search is published as a UMD bundle that references `self` at
module load. Statically importing it breaks the Next.js static
prerender of /. Deferring the import to an effect keeps the module out
of the SSR graph without changing runtime behaviour.

* fix(web): propagate plan editor via state so plan-search hook re-runs

The plan-search hook subscribed to editor transactions inside a
useEffect that depended on a ref object. Because ref.current changes do
not trigger effect re-runs, if the Editor instance was not yet ready
when the hook first mounted, the transaction handler never attached and
the match counter stayed at 0 / 0. Tracking the editor via state (in
addition to the ref) causes the deps to change when the Editor becomes
available, so the handler attaches and the counter updates.

* feat(web): allow overriding message list renderer via ?renderer= query

Exposes the "native" / "virtuoso" choice at runtime so E2E coverage can
exercise both paths without a redeploy or code change. Defaults to the
existing "native" strategy when no override is present.

* test(web): add Playwright coverage for panel-scoped Ctrl+F search

Adds an e2e/tests/search/ suite with five specs:

- panel-search-shared: cross-panel contract (Ctrl+F opens, autofocus,
  Esc closes, close button, state reset on reopen) parametrised over
  session, plan, and terminal.
- terminal-search: xterm addon-search integration — key intercept
  without leaking "f" to the PTY, case + regex toggles (incl. invalid
  regex error), Esc does not reach the shell, backspace adjusts count.
- plan-search: TipTap plugin — highlight count, exactly one current
  match, counter, Enter / Shift+Enter wrapping, close clears
  decorations, no case/regex toggles in plan bar.
- session-search: WebSocket-backed hits list, "No matches" state,
  click-to-flash, cross-session isolation, close, and virtuoso renderer
  coverage via the new ?renderer= override.
- panel-focus-routing: bar mounts inside the focused panel only.

Three tests capture GIFs for the PR description via prCapture when
CAPTURE_PR_ASSETS is set (one per panel). Helpers live in
e2e/helpers/panel-search.ts and e2e/helpers/seed-session-messages.ts;
SessionPage gains search-bar locators.

* fix(web): prevent plan-search update loop on spurious editor transactions

TipTap fires `transaction` on every cursor move/click. The match-info
handler allocated a fresh `{current, total}` object each time, so React
always saw new identity, re-rendered, and could cascade with downstream
effects (e.g. `rehydrateCommentMarks`) into a "Maximum update depth
exceeded" loop. Use a functional setState with equality bail-out so the
handler only schedules a render when the counter actually changes.

* fix(web): retry terminal search once xterm addon-search finishes loading

The SearchAddon is dynamic-imported and was stored in a ref. The
query→findNext effect called `addonRef.current?.findNext(...)` — a
silent no-op if the addon wasn't loaded yet — and its deps didn't
include addon readiness, so a query typed before the import resolved
was dropped forever. Track the addon via state so the search effect
re-runs when it becomes available (and re-binds cleanly if the terminal
is ever re-created). Also deduplicate match-info updates via functional
setState + equality check.

* fix(web): route Ctrl+F to the last-clicked panel when focus is ambient

The chat panel's message list has no focus-capturing child, so clicking
on a message left `document.activeElement === <body>` and the existing
`isFocusWithin` gate silently fell through to the browser's native find.
Fix with two complementary mechanisms:

- `usePanelSearch`: track the most-recently-clicked panel via a
  window-level pointerdown capture listener. When focus is ambient
  (body/html), that panel claims Ctrl+F. Window-level capture dodges
  any descendant `stopPropagation` that would skip a container-level
  listener.
- Chat panel root: tabIndex=-1 + onMouseDown that focuses the root when
  the click target isn't already focusable. Normal path matches how
  plan/terminal already work (TipTap/xterm capture focus on click).

* feat(web): show agent profile name and logo in session search hits

The hit list showed uppercase "AGENT"/"USER" with vivid blue/green
colors that clashed with the app's muted metadata aesthetic. Replace
with the actual author identity:

- Agent hits render the profile name (falling back to "Agent") with
  the profile's <AgentLogo> inline — same mechanism session tabs use.
- User hits render "You" with a subtle `text-primary/80` tint that
  echoes the user bubble's `bg-primary/30`, keeping a light color
  differentiator without reintroducing loud blue/green.

Added `useSessionAgentIdentity` (plus a `useSessionAgentProfile` helper)
that reads from the store via two primitive selectors — the id, then
the profile — and composes the final object inside `useMemo`. A naive
single selector returning `{label, name}` triggers the "getSnapshot
should be cached" infinite loop in `useSyncExternalStore`.

* style: apply prettier formatting to search files

* fix(web): inline resolveStrategy in useMemo to satisfy react-hooks/use-memo

* fix(backend): escape LIKE metacharacters in message search

User query of `%` previously built LIKE pattern `%%` which matched every
message in the session; `file_name` also matched `filename`, `file name`,
etc. Escape the three LIKE metacharacters (`\`, `%`, `_`) before wrapping
the pattern, and declare `ESCAPE '\'` on the clause. Add regression tests
covering wildcard literals and the literal-percent happy path.

* fix(backend): slice search snippet in rune space to keep UTF-8 valid

`buildSnippet` indexed and sliced on byte offsets, so content containing
multi-byte characters (emoji, CJK, accented letters) could be cut
mid-rune — `encoding/json` then replaced the invalid bytes with `\ufffd`
in the websocket response. Switch to rune slicing and per-rune
case-folding via `unicode.ToLower`; this also avoids the
`strings.ToLower` byte-length-change pitfall (e.g. Turkish İ, German ß).
Add a handler test covering emoji, CJK, and large multi-byte content.

* fix(web): cancel backfill loop when user clicks a newer session hit

`setActiveHit` awaits up to 40 `loadOlder()` iterations when the target
message isn't in the DOM. If the user clicked a second hit while those
awaits were in flight, the in-progress loop kept running and eventually
scrolled to the original target, overriding the user's intent. Gate the
loop on a generation counter so only the most recent call's backfill
drives the scroll.

* fix(web): gate plan-search scroll side-effect on dispatch

TipTap invokes commands with `dispatch === undefined` during `can()`
checks to test applicability (e.g. before enabling a menu item). The
next/prev commands called `scrollToMatch` outside the `if (dispatch)`
guard, so a dry-run invocation would scroll the editor to a match the
user didn't navigate to. Move the scroll inside the dispatch block.

* fix(web): address review nits on search UX

- formatTime now checks Number.isNaN(d.getTime()) before formatting;
  Invalid Date doesn't throw, so the catch branch was unreachable and
  hits with a malformed created_at rendered the literal "Invalid Date".
- prefers-reduced-motion now silences the .search-flash animation
  alongside the other custom keyframe animations.
- planScript escapes `title` symmetrically with `content` so callers
  passing arbitrary strings don't produce malformed JSON.

* fix(web): fold description into opts to keep seedTask under param limit

`seedTask` had 6 parameters, violating the repo's 5-parameter cap and
failing CI lint. Fold `description` into the existing `opts` object and
update all callsites.

* test(web): add unit tests for useSessionSearch + remove redundant ternary

Cover the non-trivial hook logic called out in review: debounced fetch
coalescing, request-ID cancellation for superseded queries, null
sessionId short-circuit, and close() resets. Also simplify the
`matches.length ? 0 : 0` ternary flagged as a dead branch — both sides
were already 0.

* fix(web): exclude PanelRoot (tabindex=-1) from the focus short-circuit

`target.closest("[tabindex]")` was matching PanelRoot itself (which has
`tabIndex={-1}` so it can receive programmatic focus), causing the guard
to early-return and the `panelRef.focus()` call to never fire — defeating
the Ctrl+F focus-routing that this handler was added for.

Narrow the selector to `[tabindex]:not([tabindex='-1'])` so it only
short-circuits on genuinely interactive elements.

* fix(web): read isReadOnlyMode from live ref in shell-terminal key handler

`attachCustomKeyEventHandler` is called once and has no dispose hook, so
the inner handler keeps its initial closure forever. Other values
(sessionId, send, onFindInPanel) are read via `stateRef` so they stay
current, but `isReadOnlyMode` was captured by closure — if the prop ever
toggled mid-session, the Cmd+Arrow→Home/End path would continue firing
against a read-only terminal. Include it in the state ref for
consistency.

* fix(web): flatten doubly-nested seedTask opts in virtuoso spec; drop unused MODIFIER

The regex-based transform in 7152b936 over-nested one call in
session-search.spec.ts — `opts.description` received an object rather
than a string, so the virtuoso renderer test never received a proper
task description. Flatten it.

Also remove MODIFIER imports/declarations in terminal-search.spec.ts and
panel-search-shared.spec.ts that were left dangling behind `void` suppressors.

* fix(web): abort session-search backfill loop on close/unmount

Move reset logic into `close()` so the lifecycle is explicit (and avoids
the set-state-in-effect lint path the previous reset effect triggered).
Bump the `activeHitGenRef` generation counter on both `close()` and
unmount so an in-flight `setActiveHit` backfill can no longer issue
`loadOlder()` calls for a hidden UI.

Also extract `useDebouncedSearch`, `useSetActiveHit`, and a
`focusMessageElement` helper to keep `useSessionSearch` under the
100-line function cap.

* perf(web): skip PanelSearchBar debounce for session search

Session search already debounces the WS call inside `useDebouncedSearch`
(180ms), but the shared bar adds its own 150ms debounce on top — giving
a 330ms keystroke→request latency instead of the intended ~180ms.
Pass `debounceMs={0}` so the bar forwards queries immediately and the
hook-level debounce is the single source of timing truth.
2026-04-24 17:14:03 +01:00