A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): prevent crash when leaving a chat during startup (#2295)
Florian Brandb043f6ef125f
diff --git a/packages/coding-agent/.changes/fix-chat-startup-back-navigation.md b/packages/coding-agent/.changes/fix-chat-startup-back-navigation.mdnew file mode 100644index 0000000000..d4c009c2cb--- /dev/null+++ b/packages/coding-agent/.changes/fix-chat-startup-back-navigation.md@@ -0,0 +1,3 @@+- Fixed a crash when returning to the agents view while a chat is still loading.+- Fixed shutdown being ignored after returning to the agents view during stalled chat startup.+- Removed heartbeat catalog loading from the wait when opening or leaving a chat.diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex f055fd335c..96797f0f59 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -945,6 +945,7 @@ export class InteractiveMode {private keybindings: KeybindingsManager;private version: string;private isInitialized = false;+ private initializationPromise: Promise<void> | undefined;private onInputCallback?: (text: string | undefined) => void;private submittedInputBehavior: "steer" | "followUp" = "steer";private latestEditorPromptStash: PromptStash | undefined;@@ -955,6 +956,7 @@ export class InteractiveMode {private readonly retainedSubmissionGenerations = new WeakMap<PromptStash, number>();private admitPendingStartupPrompts: (() => Promise<StartupPromptBarrierOutcome>) | undefined;private agentsViewRequest: InteractiveModeRunResult["type"] | undefined;+ private isReturningToAgentsView = false;private loadingAnimation: Loader | undefined = undefined;private workingMessage: string | undefined = undefined;private workingVisible = true;@@ -1528,7 +1530,8 @@ export class InteractiveMode {}async run(): Promise<InteractiveModeRunResult> {- await this.init();+ this.initializationPromise = this.init();+ await this.initializationPromise;this.restorePromptStashOnOpen();// Global, environment-scoped notices (app update, extension updates, tmux setup)@@ -1702,14 +1705,16 @@ export class InteractiveMode {}};- await this.runStartupOnboarding();- showDeferredStartupNotifications();- showModelFallbackWarning();- void this.maybeWarnAboutAnthropicSubscriptionAuth();- void deliverStartupPrompts().then(- () => settleStartupPrompts("admitted"),- () => settleStartupPrompts("admitted"),- );+ if (!this.isShuttingDown && !this.isReturningToAgentsView) {+ await this.runStartupOnboarding();+ showDeferredStartupNotifications();+ showModelFallbackWarning();+ void this.maybeWarnAboutAnthropicSubscriptionAuth();+ void deliverStartupPrompts().then(+ () => settleStartupPrompts("admitted"),+ () => settleStartupPrompts("admitted"),+ );+ }// Enter/Alt+Enter submit directly through AgentConnection. Wait for the// lifecycle signal exactly once; a returned editor value has already been@@ -2590,7 +2595,7 @@ export class InteractiveMode {for (let drain = 0; drain <= HEARTBEAT_REFRESH_DRAIN_LIMIT; drain++) {this.heartbeatRefreshRequested = false;const heartbeats = await connection.listHeartbeats();- if (this.agentConnection !== connection) return;+ if (this.isShuttingDown || this.isReturningToAgentsView || this.agentConnection !== connection) return;this.applyHeartbeatCatalog(heartbeats);if (!this.heartbeatRefreshRequested) return;}@@ -2877,7 +2882,8 @@ export class InteractiveMode {}this.refreshQueueSelectionFromState();this.updatePendingMessagesDisplay();- await this.refreshHeartbeatCatalog().catch(() => undefined);+ // Optional tray metadata must not delay opening or leaving a chat.+ void this.refreshHeartbeatCatalog().catch(() => undefined);await this.updateAvailableProviderCount();this.updateEditorBorderColor();this.updateTerminalTitle();@@ -4965,6 +4971,7 @@ export class InteractiveMode {if (submissionOutcome === "lifecycle-cancelled" ||this.isShuttingDown ||+ this.isReturningToAgentsView ||this.agentsViewRequest ||this.promptStashSessionId !== submissionSessionId) {@@ -4987,6 +4994,7 @@ export class InteractiveMode {const rejectedDraft = submittedDraft ?? { text };const canRestore =!this.isShuttingDown &&+ !this.isReturningToAgentsView &&!this.agentsViewRequest &&submissionGeneration === this.inputSubmissionGeneration &&this.editor.getText().length === 0;@@ -5010,7 +5018,7 @@ export class InteractiveMode {this.updatePendingMessagesDisplay();this.ui.requestRender();} finally {- if (this.isShuttingDown || this.agentsViewRequest) {+ if (this.isShuttingDown || this.isReturningToAgentsView || this.agentsViewRequest) {submissionOutcome = "lifecycle-cancelled";}if (@@ -6862,10 +6870,13 @@ export class InteractiveMode {}private async returnToAgentsView(request: InteractiveModeRunResult["type"] = "agents_view"): Promise<void> {- if (this.isShuttingDown || this.agentsViewRequest) return;- this.stashDraftForAgentsView();- this.agentsViewRequest = request;+ if (this.isShuttingDown || this.isReturningToAgentsView) return;+ this.isReturningToAgentsView = true;+ // Keep startup's connection alive without blocking an explicit shutdown.+ await this.initializationPromise?.catch(() => undefined);+ if (this.isShuttingDown) return;this.isShuttingDown = true;+ this.stashDraftForAgentsView();this.unregisterSignalHandlers();await this.teardownSessionUi({ preserveAltScreen: true });@@ -6875,6 +6886,7 @@ export class InteractiveMode {await this.agentConnection.dispose();} finally {await this.options.onShutdown?.();+ this.agentsViewRequest = request;this.onInputCallback?.(undefined);handoffComplete = true;}diff --git a/packages/coding-agent/test/suite/regressions/2295-startup-navigation.test.ts b/packages/coding-agent/test/suite/regressions/2295-startup-navigation.test.tsnew file mode 100644index 0000000000..5aa77d8d99--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/2295-startup-navigation.test.ts@@ -0,0 +1,195 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";+import * as shell from "../../../src/utils/shell.js";+import { createHarness, type Harness } from "../harness.js";++describe("back navigation during chat startup", () => {+ let harness: Harness;+ beforeEach(async () => {+ harness = await createHarness();+ });+ afterEach(() => {+ vi.restoreAllMocks();+ harness.cleanup();+ });++ it("finishes binding the chat without waiting for optional heartbeat metadata", async () => {+ let resolveHeartbeats!: (heartbeats: []) => void;+ const heartbeats = new Promise<[]>((resolve) => {+ resolveHeartbeats = resolve;+ });+ const mode = {+ uiServices: { getThemes: () => [] },+ toolDefinitionCache: new Map(),+ agentConnection: {+ getState: async () => ({ sessionActions: harness.session.getSessionActionSnapshot() }),+ listHeartbeats: vi.fn(() => heartbeats),+ },+ applyRuntimeSettings: vi.fn(),+ refreshConnectionCatalog: vi.fn(async () => {}),+ setupAutocompleteProvider: vi.fn(),+ subscribeToAgent: vi.fn(),+ subscribeToRosterBar: vi.fn(async () => {}),+ patchConnectionState: vi.fn(),+ refreshQueueSelectionFromState: vi.fn(),+ updatePendingMessagesDisplay: vi.fn(),+ updateAvailableProviderCount: vi.fn(async () => {}),+ updateEditorBorderColor: vi.fn(),+ updateTerminalTitle: vi.fn(),+ setGoalAnnouncementBaseline: vi.fn(),+ getGoalState: vi.fn(),+ syncGoalTray: vi.fn(),+ syncWorkingLoader: vi.fn(),+ applyHeartbeatCatalog: vi.fn(),+ isShuttingDown: false,+ };+ Object.setPrototypeOf(mode, InteractiveMode.prototype);+ const binding = Reflect.get(InteractiveMode.prototype, "rebindCurrentSession").call(mode);+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const outcome = await Promise.race([+ binding.then(() => "bound"),+ new Promise<string>((resolve) => {+ timer = setTimeout(() => resolve("blocked"), 1000);+ }),+ ]);+ expect(outcome).toBe("bound");+ expect(mode.agentConnection.listHeartbeats).toHaveBeenCalledOnce();+ mode.isShuttingDown = true;+ resolveHeartbeats([]);+ await Reflect.get(mode, "heartbeatRefreshPromise");+ expect(mode.applyHeartbeatCatalog).not.toHaveBeenCalled();+ } finally {+ clearTimeout(timer);+ resolveHeartbeats([]);+ await binding;+ }+ });++ it.each(["catalog", "snapshot"])("keeps the connection alive while loading the %s", async (phase) => {+ let resume!: () => void;+ const pending = new Promise<void>((resolve) => {+ resume = resolve;+ });+ let loading!: () => void;+ const started = new Promise<void>((resolve) => {+ loading = resolve;+ });+ let connected = true;+ const state = {+ sessionId: harness.session.sessionId,+ cwd: harness.tempDir,+ compactionCount: 0,+ model: harness.getModel(),+ };+ const dispose = vi.fn(async () => {+ connected = false;+ });+ const getInitialSnapshot = vi.fn(async () => {+ if (phase === "snapshot") {+ loading();+ await pending;+ }+ if (!connected) throw new Error("Cannot send get_connection_state: daemon is not connected");+ return { state, messages: harness.session.messages };+ });+ const mode = {+ options: { returnToAgentsView: true, agentsViewOwnsStartupNotices: true },+ init: async () => {+ if (phase === "catalog") {+ loading();+ await pending;+ }+ await InteractiveMode.prototype.renderInitialMessages.call(mode as never);+ },+ agentConnection: { getInitialSnapshot, dispose },+ connectionState: state,+ editor: { getText: () => "" },+ getSessionContextFromConnectionSnapshot: () => harness.session.buildSessionContext(),+ seedSubagentSummary: vi.fn(),+ applyConnectionStateSnapshot: vi.fn(),+ restoreTurnStartFromMessages: vi.fn(),+ renderSessionContext: vi.fn(async () => {}),+ restoreStreamingMessageFromSnapshot: vi.fn(async () => {}),+ showLoadedResources: vi.fn(),+ restorePromptStashOnOpen: vi.fn(),+ modelRegistry: harness.session.modelRegistry,+ runStartupOnboarding: vi.fn(() => new Promise<boolean>(() => {})),+ getModelFallbackWarningAction: () => "suppress",+ maybeWarnAboutAnthropicSubscriptionAuth: vi.fn(),+ getCurrentCwd: () => state.cwd,+ stashDraftForAgentsView: vi.fn(),+ unregisterSignalHandlers: vi.fn(),+ teardownSessionUi: vi.fn(async () => {}),+ };+ Object.setPrototypeOf(mode, InteractiveMode.prototype);+ const run = InteractiveMode.prototype.run.call(mode as never);+ // Observe the rejection immediately so the unfixed race is an assertion failure.+ const result = run.then(+ (value) => value,+ (error: unknown) => error,+ );+ await started;+ const navigate = Reflect.get(InteractiveMode.prototype, "returnToAgentsView");+ const handoff = navigate.call(mode);+ const repeatedHandoff = navigate.call(mode);+ await Promise.resolve();+ await Promise.resolve();+ const disposedDuringStartup = dispose.mock.calls.length;+ resume();+ await Promise.all([handoff, repeatedHandoff]);++ expect(await result).toMatchObject({+ type: "agents_view",+ source: { sessionId: state.sessionId, cwd: state.cwd },+ });+ expect(disposedDuringStartup).toBe(0);+ expect(getInitialSnapshot).toHaveBeenCalledOnce();+ expect(dispose).toHaveBeenCalledOnce();+ expect(mode.teardownSessionUi).toHaveBeenCalledOnce();+ expect(mode.runStartupOnboarding).not.toHaveBeenCalled();+ });++ it.each(["shutdown", "SIGTERM"])("allows %s to interrupt Back while startup is stalled", async (action) => {+ let resume!: () => void;+ const initializationPromise = new Promise<void>((resolve) => {+ resume = resolve;+ });+ const exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);+ vi.spyOn(shell, "killTrackedDetachedChildren").mockImplementation(() => {});+ const mode = {+ initializationPromise,+ isShuttingDown: false,+ signalCleanupHandlers: [] as Array<() => void>,+ agentConnection: {+ getSessionStats: vi.fn(async () => harness.session.getSessionStats()),+ dispose: vi.fn(async () => {}),+ },+ ui: { terminal: { drainInput: vi.fn(async () => {}) } },+ options: { onShutdown: vi.fn(async () => {}) },+ clearCtrlCExitHint: vi.fn(),+ stop: vi.fn(),+ stashDraftForAgentsView: vi.fn(),+ teardownSessionUi: vi.fn(async () => {}),+ onInputCallback: vi.fn(),+ };+ Object.setPrototypeOf(mode, InteractiveMode.prototype);+ Reflect.get(mode, "registerSignalHandlers").call(mode);+ const terminate = process.listeners("SIGTERM")[0]!;+ const handoff = Reflect.get(mode, "returnToAgentsView").call(mode);+ try {+ if (action === "SIGTERM") terminate("SIGTERM");+ else await Reflect.get(mode, "shutdown").call(mode);+ await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0));+ expect(mode.agentConnection.dispose).toHaveBeenCalledOnce();+ expect(mode.options.onShutdown).toHaveBeenCalledOnce();+ } finally {+ resume();+ await handoff;+ Reflect.get(mode, "unregisterSignalHandlers").call(mode);+ }+ expect(mode.agentConnection.dispose).toHaveBeenCalledOnce();+ expect(mode.teardownSessionUi).not.toHaveBeenCalled();+ expect(mode.onInputCallback).not.toHaveBeenCalled();+ });+});