#13963·kilocode

Agent Manager stops updating the displayed session when switching worktrees

Author: marius-kilocodeCreated Sep 9, 2026Updated Sep 30, 2026
Labelsbug

Description

Agent Manager entered a state where its UI continued to render, but attempting to switch worktrees no longer updated the displayed session. The report involved only one project in Agent Manager. Multi-project mode was enabled.

This issue records the symptom and a read-only investigation of the selection, project routing, session loading, and connection recovery paths. The exact incident trigger has not been reproduced or confirmed. The findings below distinguish observed evidence, confirmed code behavior, and possible causes. They are not a claim that every identified gap caused this incident.

The strongest match for the previous session remaining selected is a missing or ignored selection acknowledgement, or a view that hides an otherwise successful session change. A server outage can explain loading failures or stale streaming content, but does not by itself explain every cached-session switch leaving the previous session selected.

Expected behavior

  • Selecting a worktree shows its remembered session or the appropriate empty/non-session state.
  • Selection remains recoverable when project state is loading, unavailable, or temporarily inconsistent.
  • A failed switch shows an actionable error instead of silently leaving the previous chat on screen.
  • A backend outage does not prevent switching between already-cached sessions locally.
  • Worktree deletion and session movement do not allow stale refreshes to restore obsolete rows or routes.

Actual behavior

The UI continued to render, but worktree switching stopped updating the displayed session. The report does not establish whether the sidebar selection highlight changed on every failed click, whether History was open, or which selection-protocol messages reached the webview. These distinctions matter for identifying the failing stage.

Kilo version

  • VS Code extension snapshot 7.5.16-snapshot+4e4d87d127 was identified in the affected window's logs.
  • Investigation revision: 718c2b36ac8c4e22e12a7e187dbab2e20f15f322.
  • Comparing those revisions showed no changes in the host Agent Manager, KiloProvider, CLI connection code, or webview context directories relevant to this analysis. There were later Agent Manager icon/button/CSS changes, so this is not a claim that the entire UI bundle was identical.
  • Setting: kilo-code.new.experimental.multiProject: true.
  • Only one project was reported open in Agent Manager. This does not bypass the multi-project selection protocol.

Operating System

macOS. Exact OS and VS Code versions were not collected for this report.

Plugins

Not collected. No plugin has been identified as the cause.

Terminal

Not established as relevant. The affected surface is Agent Manager in the VS Code extension.

Steps to reproduce

No deterministic reproduction is available yet. The reported usage context was:

  1. Use Agent Manager with multi-project mode enabled and one project containing multiple managed worktrees/sessions.
  2. Work in the existing Agent Manager panel and switch between worktrees.
  3. At some point, switching no longer updates the displayed session, although the UI continues to render.

Do not treat these as sufficient steps to reproduce the defect. Controlled scenarios to test are listed below.

Screenshot and/or share link

No screenshot, recording, or shared transcript of the failed state was captured. Raw local logs are not attached because they contain local paths and session data. Relevant observations are summarized below without those details.

Observed evidence

The incident was reported on 2026-09-09 at approximately 10:10 UTC. Logs from the affected main repository window show:

  • Worktree deletion at approximately 09:55:46 UTC.
  • Another worktree deletion at approximately 10:06:25 UTC.
  • Successful creation of a new worktree session at approximately 10:07:02 UTC.
  • Diff activity for another worktree at approximately 10:07:23 UTC.
  • Extension host shutdown at approximately 10:09:24 UTC.

Successful session creation shortly before the report argues against a continuous total backend outage. It does not prove the backend was healthy at the exact time of the failed clicks. Diff activity alone is not a complete CLI health check.

There were earlier Failed to load messages: TypeError: terminated errors, but they occurred before a previous extension-host restart, not during the later host lifetime associated with this report. They must not be treated as proof of the incident cause.

There were also file-watcher event-drop warnings. No causal link between those warnings and session selection was established.

The disappearance of syncOnSessionSwitch: panel hidden, skipping log lines is not evidence that session switching stopped at that time. [That log is conditional on the terminal panel being hidden][terminal-sync]. Switching with an open terminal panel can be silent.

No captured trace correlates a failed click with activateSelection, selectionActivated, currentSessionID, and the transcript request. The worktree deletions are possible context, not a proven trigger.

Selection flow

With multi-project mode enabled, an ordinary worktree-row click uses this path even within one project:

ProjectSidebarBody worktree click
  -> AgentManagerApp.activateSelection
  -> agentManager.activateSelection message
  -> host waits for project readiness and validates the target
  -> agentManager.selectionActivated acknowledgement
  -> webview checks catalog-active and applied-project state
  -> selectWorktreeAction
  -> session.selectSession
  -> loadMessages
  -> messagesLoaded

The [webview request function][selection-request] posts a request; it does not optimistically change the current session. The [host selection handler][selection-host] waits for readiness before acknowledging. The [webview acknowledgement handler][selection-apply] can discard an acknowledgement without applying the selection.

In contrast, once execution reaches [SessionProvider.selectSession][session-select], it changes the local currentSessionID before checking connectivity. It then defers the backend fetch while offline and replays it after reconnect. Therefore a cached session should switch locally if this function is reached.

Findings and likely explanations

1. Missing selection acknowledgement during project initialization

Confirmed mechanism; strongest fit for an unchanged previous selection. The incident trigger is unconfirmed.

The [host awaits deps.ready(ctx)][selection-host] before it sends selectionActivated. [Project initialization][project-init] can wait for Git exclude updates, persisted state load/recovery, worktree discovery, and state flushing. [ProjectContext.ensureReady][context-ready] shares the initialization promise.

There is no selection deadline or cancellation around this readiness wait. If initialization does not finish, the click receives no acknowledgement and the old session remains selected.

If an unexpected readiness exception escapes, [the message interceptor logs the rejected hook and returns null][interceptor]. The request can therefore be dropped without a selection-specific response to the webview. A resolved readiness failure has a different path: the host emits a project-not-ready error and returns without a selection acknowledgement.

This is mainly a startup, restoration, or reinitialization scenario. Once a single pinned project is ready and the target exists, the normal host path after readiness is synchronous. It would be incorrect to claim that every ordinary same-project switch performs a slow project initialization.

2. An acknowledgement is ignored because catalog and applied state disagree

Confirmed guard and recovery gap; the state mismatch was not captured in the incident.

The [acknowledgement handler][selection-apply] accepts a target only when both conditions hold:

  • The project is active in the project catalog.
  • That project's state has been applied to the main webview stores.

Otherwise it returns without applying the target. This prevents a delayed acknowledgement from selecting data in the wrong project, but the selection request itself has no timeout, retry, or retained acknowledgement to apply after the missing state arrives. Cold activation relies on a later state restore to recover the intended target.

Repeated clicks within the same active project are not guaranteed to repair an already-inconsistent webview: [the host skips full activation when the project is already active][selection-host], and [catalog hydration skips the active project][hydrate].

One project in the sidebar does not eliminate the distinction between catalog state and applied state. A missing or unapplied state payload can still prevent acknowledgement application. This is a plausible persistent-state trap, not a proven reconstruction of this incident.

3. History remains visible after an otherwise successful worktree switch

Concrete UI-only behavior; relevant only if History was open.

[Ordinary selectWorktree() does not call closeHistory()][worktree-select]. The render path [keeps History visible and hides/inerts the detail stack while history() is true][history-render]. A session can therefore change behind a still-visible history screen.

The nearby focusManagedSession() path does close History, so selecting a specific managed session and selecting its worktree row have different behavior.

This is a better fit when the worktree highlight changes but the visible main content does not. It does not require a backend outage or multiple projects. Remembered terminal and review tabs should also be distinguished from a genuinely unchanged chat session; restoring those non-chat tabs can be intentional.

4. Stale selection and target state after worktree deletion

Confirmed recovery gaps; deletion is only a possible trigger.

[State application][apply-state] updates the sidebar selection when the current session still maps to a worktree. If the session/worktree has disappeared, that branch does not itself select a replacement.

The [worktree deletion UI][sidebar-delete] tries to select a replacement before sending deletion when it believes the deleted worktree is selected. There is no general successful worktreeDeleted selection-repair branch in the main application handler.

[WorktreeStateManager.removeWorktree][remove-worktree] removes the worktree and associated sessions but does not clear its separately persisted active target. The host [falls back to Local for missing worktree/session targets][selection-host] instead of presenting a missing-target error.

The [deletion lifecycle][delete-lifecycle] also does not immediately invalidate the cached project session listing or remove its live-session IDs. A recently removed session can temporarily remain accepted by hasLiveSession().

These paths can explain a stale selected row, obsolete session, or unexpected fallback to Local. They do not, by themselves, prove why every later valid worktree click would fail. The logged deletion was not established as deletion of the active worktree, and no causal connection was proved.

5. Older project-session refreshes can overwrite newer state and routes

Concrete asynchronous ordering risk, especially around deletion or movement.

[pushState starts asynchronous project-session refreshes][push-state]. [collectProjectSessions][project-sessions] captures the root/worktree directories, lists them concurrently, and later registers session directories and routes. pushProjectSessions() then replaces the cached session views and posts them to the webview.

The collection checks project lifecycle/generation, but not a per-refresh sequence. Ordinary worktree deletion or session movement does not advance that lifecycle generation.

An unsafe order is therefore possible:

  1. Refresh A captures the old worktree/session state and begins listing.
  2. A worktree is deleted or a session is moved.
  3. Refresh B captures the new state and completes.
  4. Refresh A completes later and posts older data or re-registers an old directory.

This can restore stale rows or route information. It is a separate risk from losing a selection acknowledgement: ordinary same-project selection does not await this listing, so a list race alone should not prevent every valid cached-session switch.

6. One directory's backend initialization or HTTP request stalls

Strong explanation for stale discovery or a loading stall, weaker for an unchanged cached-session ID.

[Instance middleware loads the requested directory][instance-middleware] before handling its session request. [InstanceStore][instance-store] waits for directory-specific bootstrap. Configuration/plugin initialization, Git, storage, or other bootstrap work are possible sources of a stall; none was identified in the incident.

[Project-session collection uses Promise.all across the root and worktrees][project-sessions]. Rejected directory listings are handled, but one request that does not settle prevents the complete session-list update. The [generic session-list refresh][generic-list] has the same all-directory wait.

There is no application-level deadline for these listings. The [SDK fetch wrapper][sdk-fetch] sets timeout: false for Bun streaming behavior, but that is not evidence that VS Code's Node transport has no default timeout. The relevant gap is the absence of an explicit application deadline and recovery for the operation.

Global health, SSE, and other directories can remain usable while one directory stalls. However, this does not directly block a same-project selection acknowledgement, and selectSession() still changes the local ID before starting a load.

Backend and SSE failure distinctions

Scenario Code behavior and expected symptom Fit for the exact report
CLI child process exits [The connection service invalidates its client and reports an error with Retry][connection-recovery]. The UI has a connection-error banner path. More likely to produce a visible connection failure than silently preserve the previous selection.
CLI remains alive but unresponsive [ServerManager reuses the cached process][server-reuse]. [Health-check failure reconnects SSE][connection-recovery], rather than replacing the process. Can cause prolonged failures, but does not prove a selection-specific defect. Automatic process replacement would affect running agents and needs separate design.
Initial SSE connection never becomes ready [connect waits for the first SSE event before completing and starting health polling][connection-initial]. [The adapter's heartbeat starts after the stream request returns][sse-adapter]. There is no overall initial-connect deadline, and reconnect attempts can continue. Can leave initialization pending. This is a broader connection problem, not normally an isolated cached-session-selection failure.
Established SSE stream disconnects [The global stream supplies live events without transcript replay][global-sse]. [Reconnect handling refreshes status and metadata][provider-reconnect], but does not unconditionally reload the current transcript. Explains missed live content. Selecting a cached session should still change the local ID and reconcile when connectivity permits.
Session metadata or messages fail to load [Message loading posts a generic error][message-load]; [the session context clears loading flags][session-error]. Metadata errors are treated as non-critical warnings. Can leave an empty/stale display without a useful inline load failure. It is not sufficient to explain a click that never changes the local session ID.

There is also an incomplete cancellation path: [refreshSessionDetails accepts an AbortSignal but does not pass it to session.get][session-details]. It checks the signal after the response instead. Cancelling a selection's message-page load therefore does not cancel that metadata HTTP request.

Lower-confidence cross-project risks

Selection acknowledgements do not carry a request sequence or latest-selection epoch. Slow activation of different projects can complete in an order that no longer matches user intent. Other asynchronous callbacks can also resolve against the active project after it changes.

These warrant follow-up coverage, but same-project rapid-click reordering was not demonstrated. For a ready project, readiness resolves immediately; during one initialization, callers share the promise. With no further await in finish(), same-context continuations normally preserve order. The absence of an epoch is not proof that this caused a one-project freeze.

The [AgentManagerApp sessionCreated listener][session-created] also has no source-project guard of its own, while [registration uses the current project qualifier][session-register]. A delayed creation from another project deserves ownership coverage. It is lower priority for this report because no second-project activity was established.

Suggested initial fix scope

Keep the first fix focused on selection recovery rather than attempting a broad backend rewrite:

  1. Give each selection request an ID and ensure it ends with success, an actionable failure, or a bounded timeout.
  2. Convert readiness exceptions into a selection-specific error response instead of a dropped message.
  3. Retain the latest intended selection when an acknowledgement arrives before the required project state. Request/apply that state, then complete selection if the intent is still current.
  4. Ignore stale responses for superseded requests. Add this as defensive protocol behavior, not as a claim that same-project reordering caused this incident.
  5. Keep the previous chat visible while waiting, but show that a switch is pending. On failure, provide Retry so the previous chat is not silently presented as a successful switch.
  6. Close History on ordinary worktree selection, or explicitly define and test why it should remain open.

A separate follow-up can add session-list refresh sequencing, invalidate routes/live caches after deletion or movement, and add directory-request deadlines. Do not start by automatically killing and restarting the shared backend; that has a larger impact on running sessions and is not supported as the first remedy by the available evidence.

Diagnostics needed for the next occurrence

Correlate the following stages with one selection request ID:

activateSelection received
project readiness started/completed/failed
selectionActivated or selectionFailed sent
acknowledgement received/applied/deferred/rejected
currentSessionID changed
loadMessages started/completed/failed/cancelled
messagesLoaded applied or discarded

Record target project/worktree/session IDs, catalog-active project ID, applied project ID, connection state, and routing context in local diagnostics. Avoid logging prompt bodies or message contents, and sanitize local paths before sharing logs publicly.

Useful distinctions:

  • No acknowledgement: inspect readiness and host interception.
  • Acknowledgement received but not applied: inspect project-state gates and recovery.
  • Local session ID changes but content appears fixed: inspect History, terminal, review, and chat visibility.
  • Load starts but never completes: inspect the specific directory's initialization and HTTP request.
  • Old rows/routes return after a newer state update: inspect refresh ordering and deletion/movement invalidation.

Verification performed

The investigation was read-only. No product files were changed, no live Agent Manager state was edited, and the original failure was not reproduced end to end.

Focused commands were run from packages/kilo-vscode/:

bash
bun test tests/unit/agent-project-selection.test.ts tests/unit/agent-project-route.test