A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): keep the working-status elapsed timer across session re-entry (#1605)
Sebastian Müller48b6478e7317
diff --git a/packages/coding-agent/.changes/eng-working-timer.md b/packages/coding-agent/.changes/eng-working-timer.mdnew file mode 100644index 0000000000..82ba1be5b9--- /dev/null+++ b/packages/coding-agent/.changes/eng-working-timer.md@@ -0,0 +1 @@+- Fixed the working-status elapsed timer (e.g. "Waiting · 5s") restarting at 0s after leaving and re-entering a session or re-attaching to it; the timer is now anchored to the in-flight turn's user message and keeps counting.diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.tsindex b2cc572a2d..0599c003c9 100644--- a/packages/coding-agent/src/core/agent-messages.ts+++ b/packages/coding-agent/src/core/agent-messages.ts@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import type { AgentMessage } from "@earendil-works/pi-agent-core";import type { HostRequestHandler } from "./kernel/index.js";import type { CustomMessage } from "./messages.js";+import { HEARTBEAT_PROMPT_CUSTOM_TYPE } from "./messages.js";import { canonicalSessionPath } from "./session-lease.js";export const AGENT_MESSAGE_CUSTOM_TYPE = "agent_message";@@ -437,6 +438,15 @@ export function isAgentSessionMessage(message: AgentMessage): message is AgentSe);}+// A message that starts a new agent run (prompt-turn boundary).+export function startsAgentRun(message: AgentMessage): boolean {+ return (+ message.role === "user" ||+ isAgentSessionMessage(message) ||+ (message.role === "custom" && message.customType === HEARTBEAT_PROMPT_CUSTOM_TYPE)+ );+}+export function createAgentSessionMessageReceipt(payload: AgentSessionMessagePayload,status: AgentSessionMessageDeliveryStatus,diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex b01c929f20..187253a4c8 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -55,6 +55,7 @@ import {isAgentSessionMessage,normalizeAgentSessionMessage,parseAgentSessionMessagePromptId,+ startsAgentRun,} from "./agent-messages.js";import {AGENT_OBSERVE_SKILL_NAME,@@ -3545,7 +3546,7 @@ export class AgentSession {}}- if (event.type === "message_start" && this._isPromptTurnStartMessage(event.message)) {+ if (event.type === "message_start" && startsAgentRun(event.message)) {this._overflowRecovery = "idle";}@@ -3672,14 +3673,6 @@ export class AgentSession {}}- private _isPromptTurnStartMessage(message: AgentMessage): boolean {- return (- message.role === "user" ||- isAgentSessionMessage(message) ||- (message.role === "custom" && message.customType === HEARTBEAT_PROMPT_CUSTOM_TYPE)- );- }-private _resolveRetry(): void {if (this._retryResolve) {this._retryResolve();diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 5b7f74cdef..ba1ec204f1 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -60,7 +60,11 @@ import {SELF_UPDATE_NOT_ATTEMPTED_EXIT_CODE,VERSION,} from "../../config.js";-import { AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL, isAgentSessionMessage } from "../../core/agent-messages.js";+import {+ AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL,+ isAgentSessionMessage,+ startsAgentRun,+} from "../../core/agent-messages.js";import {type AgentTracePreviewResult,type AgentTraceUploadAllResult,@@ -97,7 +101,6 @@ import {bashOutputToText,COMPACTION_OUTCOME_CUSTOM_TYPE,createHeartbeatPromptMessage,- HEARTBEAT_PROMPT_CUSTOM_TYPE,HEARTBEAT_PROMPT_PREVIEW_LABEL,isCompactionOutcomeMessage,isSessionSlashCommandMessage,@@ -888,6 +891,8 @@ export class InteractiveMode {private workingVisible = true;private workingIndicatorOptions: LoaderIndicatorOptions | undefined = undefined;private workingStartedAt: number | undefined = undefined;+ // Start of the in-flight run; survives loader teardown so the elapsed display doesn't reset on re-entry.+ private turnStartedAt: number | undefined = undefined;private workingTimer: NodeJS.Timeout | undefined = undefined;private readonly featureHintDeck = new FeatureHintDeck();private currentFeatureHint: string | undefined;@@ -2891,6 +2896,7 @@ export class InteractiveMode {private async renderResyncedSession(snapshot: AgentConnectionSnapshot): Promise<void> {const bashFinished = this.isBashRunning() && !snapshot.state.isBashRunning;this.applyConnectionStateSnapshot(snapshot.state);+ this.restoreTurnStartFromMessages(this.getSessionContextFromConnectionSnapshot(snapshot).messages);this.streamingComponent = undefined;this.streamingMessage = undefined;this.rlmNodeId = snapshot.parent?.childId;@@ -3179,9 +3185,27 @@ export class InteractiveMode {this.workingTimer.unref?.();}+ // Recover the in-flight run's start from a restored transcript so the elapsed timer survives re-attach.+ private restoreTurnStartFromMessages(messages: readonly AgentMessage[]): void {+ this.turnStartedAt = undefined;+ if (!this.isAgentStreaming()) return;+ for (let i = messages.length - 1; i >= 0; i--) {+ const message = messages[i]!;+ if (startsAgentRun(message)) {+ this.turnStartedAt = message.timestamp;+ } else if (message.role === "assistant" && message.stopReason !== "toolUse") {+ break;+ }+ }+ if (this.turnStartedAt !== undefined && this.workingStartedAt !== undefined) {+ this.workingStartedAt = this.turnStartedAt;+ this.updateWorkingLoaderMessage();+ }+ }+private startWorkingLoader(): void {this.stopWorkingLoader();- this.workingStartedAt = Date.now();+ this.workingStartedAt = this.turnStartedAt ?? Date.now();this.loadingAnimation = this.createWorkingLoader();this.statusContainer.addChild(this.loadingAnimation);this.startWorkingTimer();@@ -3300,11 +3324,7 @@ export class InteractiveMode {this.featureHintRunPending = false;return;}- const startsNewRun =- message.role === "user" ||- isAgentSessionMessage(message) ||- (message.role === "custom" && message.customType === HEARTBEAT_PROMPT_CUSTOM_TYPE);- if (!startsNewRun) return;+ if (!startsAgentRun(message)) return;this.endFeatureHintRun();if (this.shouldShowWorkingLoader()) {@@ -5404,6 +5424,14 @@ export class InteractiveMode {}case "message_start":+ // The run's first starter anchors the elapsed display; mid-turn steering must not restart it.+ if (this.turnStartedAt === undefined && startsAgentRun(event.message)) {+ this.turnStartedAt = event.message.timestamp;+ if (this.workingStartedAt !== undefined) {+ this.workingStartedAt = event.message.timestamp;+ this.updateWorkingLoaderMessage();+ }+ }if (event.message.role === "custom") {this.addMessageToChat(event.message);this.ui.requestRender();@@ -5529,6 +5557,7 @@ export class InteractiveMode {if (this.settingsManager.getShowTerminalProgress()) {this.ui.terminal.setProgress(false);}+ this.turnStartedAt = undefined;// Drops the loader; background subagents are shown by the tree, not the loader.this.syncWorkingLoader();if (this.streamingComponent) {@@ -6488,6 +6517,7 @@ export class InteractiveMode {this.seedSubagentSummary(snapshot.children);this.setSessionHasMessages(context.messages.length > 0);this.applyConnectionStateSnapshot(state);+ this.restoreTurnStartFromMessages(context.messages);await this.renderSessionContext(context, {updateFooter: true,populateHistory: true,diff --git a/packages/coding-agent/test/interactive-mode-status.test.ts b/packages/coding-agent/test/interactive-mode-status.test.tsindex bd9abf5055..be2ae6ed79 100644--- a/packages/coding-agent/test/interactive-mode-status.test.ts+++ b/packages/coding-agent/test/interactive-mode-status.test.ts@@ -682,6 +682,115 @@ function createSubmitHandlerHarness(overrides: Partial<SubmitHandlerHarness> = {return fakeThis;}+describe("InteractiveMode working timer", () => {+ type InitialTimerHarness = {+ turnStartedAt: number | undefined;+ workingStartedAt: number | undefined;+ agentConnection: { getInitialSnapshot(): Promise<AgentConnectionSnapshot> };+ isAgentStreaming(): boolean;+ updateWorkingLoaderMessage: ReturnType<typeof vi.fn>;+ renderInitialMessages(): Promise<void>;+ stopWorkingLoader: ReturnType<typeof vi.fn>;+ createWorkingLoader: ReturnType<typeof vi.fn>;+ statusContainer: { addChild: ReturnType<typeof vi.fn> };+ startWorkingTimer: ReturnType<typeof vi.fn>;+ startFeatureHintPresentation: ReturnType<typeof vi.fn>;+ };++ function createInitialTimerHarness(snapshot: AgentConnectionSnapshot, turnStartedAt = 1): InitialTimerHarness {+ let streaming = false;+ return Object.assign(Object.create(InteractiveMode.prototype), {+ turnStartedAt,+ workingStartedAt: turnStartedAt,+ agentConnection: { getInitialSnapshot: vi.fn(async () => snapshot) },+ getSessionContextFromConnectionSnapshot: vi.fn(() => ({+ messages: snapshot.messages,+ thinkingLevel: "medium",+ serviceTier: "default",+ model: null,+ })),+ seedSubagentSummary: vi.fn(),+ setSessionHasMessages: vi.fn(),+ applyConnectionStateSnapshot: vi.fn((state: AgentConnectionState) => {+ streaming = state.isStreaming;+ }),+ isAgentStreaming: () => streaming,+ updateWorkingLoaderMessage: vi.fn(),+ renderSessionContext: vi.fn(async () => {}),+ restoreStreamingMessageFromSnapshot: vi.fn(async () => {}),+ showStatus: vi.fn(),+ stopWorkingLoader: vi.fn(),+ createWorkingLoader: vi.fn(() => ({})),+ statusContainer: { addChild: vi.fn() },+ startWorkingTimer: vi.fn(),+ startFeatureHintPresentation: vi.fn(),+ });+ }++ function customStarter(customType: "agent_message" | "heartbeat_prompt", timestamp: number): AgentMessage {+ return {+ role: "custom",+ customType,+ content: "Continue.",+ display: true,+ details: customType === "agent_message" ? { id: `agentmsg_${timestamp}`, message: "Continue." } : {},+ timestamp,+ };+ }++ test("restores the first active-run starter instead of a steering message", async () => {+ const harness = createInitialTimerHarness({+ state: createConnectionState({ isStreaming: true }),+ messages: [+ userMessage("Start the task.", 100),+ { ...toolCallMessage("tool-1", "ipython"), timestamp: 200 },+ userMessage("Also check this.", 300),+ ],+ });++ await harness.renderInitialMessages();++ expect(harness.turnStartedAt).toBe(100);+ expect(harness.workingStartedAt).toBe(100);+ expect(harness.updateWorkingLoaderMessage).toHaveBeenCalledOnce();+ });++ test.each([+ ["agent-session", customStarter("agent_message", 100)],+ ["heartbeat", customStarter("heartbeat_prompt", 200)],+ ])("restores a %s run starter", async (_kind, starter) => {+ const harness = createInitialTimerHarness({+ state: createConnectionState({ isStreaming: true }),+ messages: [starter],+ });++ await harness.renderInitialMessages();++ expect(harness.turnStartedAt).toBe(starter.timestamp);+ expect(harness.workingStartedAt).toBe(starter.timestamp);+ });++ test.each([+ ["a non-streaming snapshot", false, [userMessage("Old prompt.", 200)]],+ ["a streaming snapshot without a starter", true, [{ ...toolCallMessage("tool-1", "ipython"), timestamp: 200 }]],+ ])("clears a stale anchor for %s and falls back to the loader start", async (_name, isStreaming, messages) => {+ const harness = createInitialTimerHarness({ state: createConnectionState({ isStreaming }), messages }, 100);++ await harness.renderInitialMessages();+ const now = vi.spyOn(Date, "now").mockReturnValue(500);+ try {+ (+ InteractiveMode.prototype as unknown as { startWorkingLoader(this: InitialTimerHarness): void }+ ).startWorkingLoader.call(harness);+ } finally {+ now.mockRestore();+ }++ expect(harness.turnStartedAt).toBeUndefined();+ expect(harness.workingStartedAt).toBe(500);+ });+});+describe("InteractiveMode submit handling", () => {test.each(["normal Enter", "installed custom editor"])("captures exact rich state for %s", async () => {const image = { type: "image", data: "base64", mimeType: "image/png" };@@ -1368,6 +1477,7 @@ describe("InteractiveMode connection events", () => {applyConnectionStateSnapshot: vi.fn(),renderSessionContext: renderSessionContextMock,restoreStreamingMessageFromSnapshot,+ restoreTurnStartFromMessages: vi.fn(),showStatus: vi.fn(),} as unknown as InteractiveMode;@@ -1545,7 +1655,7 @@ describe("InteractiveMode connection events", () => {} as AgentConnectionSnapshot["streamingMessage"];const snapshot: AgentConnectionSnapshot = {state: createConnectionState({ isCompacting: true, isBashRunning: true, isStreaming: true }),- messages: [],+ messages: [userMessage("Still working", 100)],streamingMessage,};const startAssistantStreamingMessage = vi.fn();@@ -1556,18 +1666,22 @@ describe("InteractiveMode connection events", () => {});const refreshCommandCatalogForCurrentSession = vi.fn(async () => {});const fakeThis = {+ turnStartedAt: 1,+ workingStartedAt: 1,sideQuestionEvent: sideQuestion,activeConnectionExtensionUiRequests: extensionRequests,activeBashComponent,refreshCommandCatalogForCurrentSession,isAgentCompacting: () => true,isBashRunning: () => true,+ isAgentStreaming: () => true,streamingComponent: {},streamingMessage: {},applyConnectionStateSnapshot: vi.fn(),+ updateWorkingLoaderMessage: vi.fn(),replaceSubagentSummary: vi.fn(),getSessionContextFromConnectionSnapshot: vi.fn(() => ({- messages: [],+ messages: snapshot.messages,thinkingLevel: "medium",model: null,})),@@ -1581,6 +1695,7 @@ describe("InteractiveMode connection events", () => {syncWorkingLoader: vi.fn(),getGoalState: () => emptyGoalState(),} as unknown as InteractiveMode;+ Object.setPrototypeOf(fakeThis, InteractiveMode.prototype);await (InteractiveMode.prototype as unknown as {@@ -1597,6 +1712,11 @@ describe("InteractiveMode connection events", () => {(fakeThis as unknown as { renderSessionContext: ReturnType<typeof vi.fn> }).renderSessionContext,).toHaveBeenCalledWith(expect.anything(), { clearChat: true, updateFooter: true });expect(startAssistantStreamingMessage).toHaveBeenCalledWith(streamingMessage);+ expect((fakeThis as unknown as { turnStartedAt: number | undefined }).turnStartedAt).toBe(100);+ expect((fakeThis as unknown as { workingStartedAt: number | undefined }).workingStartedAt).toBe(100);+ expect(+ (fakeThis as unknown as { updateWorkingLoaderMessage: ReturnType<typeof vi.fn> }).updateWorkingLoaderMessage,+ ).toHaveBeenCalledOnce();expect(refreshCommandCatalogForCurrentSession).not.toHaveBeenCalled();});@@ -1614,6 +1734,7 @@ describe("InteractiveMode connection events", () => {isAgentCompacting: () => true,isBashRunning: () => true,applyConnectionStateSnapshot: vi.fn(),+ restoreTurnStartFromMessages: vi.fn(),replaceSubagentSummary: vi.fn(),getSessionContextFromConnectionSnapshot: vi.fn(() => ({messages: [],