Repository navigation
fix(desktop): preserve retry and background task behavior - #4831
Conversation
- clear retry status on the next attempt and preserve partial responses - release scheduler leases when tools detach
- keep retry state during backoff and avoid duplicate partial responses - release scheduler leases when tools detach - use one desktop changeset for the related fixes
- ignore repeated logical step starts in subagent activity history - carry usage and response metadata through retry events - preserve partial response usage in the test harness
🦋 Changeset detectedLatest commit: 464b3bb The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bf6fe75e0c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| case 'turn.step.started': { | ||
| const key = `${event.agentId}:${event.turnId}:${event.stepId ?? event.step}`; | ||
| if (this.startedSteps.has(key)) return; | ||
| this.startedSteps.add(key); |
There was a problem hiding this comment.
Bound retained step-deduplication keys
In long-lived sessions, every unique step key is added to startedSteps but keys are never removed when old steps are evicted by MAX_SUBAGENT_ACTIVITY_STEPS or when drop() removes a foreground agent. Consequently, the store's advertised retention cap no longer bounds memory usage; the set grows with every step until the entire session is cleared. Remove the corresponding keys during eviction/drop, or use a bounded per-record structure.
Useful? React with 👍 / 👎.
| const step = turn.current?.number ?? turn.gatedSteps; | ||
| turn.retry = undefined; | ||
| void this.options.dispatcher.dispatch(new TurnStepStarted({ |
There was a problem hiding this comment.
Restore the projected step before announcing a retry
When a backoff retry starts, the preceding llm.retrying projection has already set turn.current to undefined, but this branch only emits another TurnStepStarted without recreating the projected step. Subsequent streaming usage, the final assistant message, and tool completions all require turn.current, so a successful retry never emits its matching TurnStepCompleted and drops its final usage and tool metadata from live consumers. Reattach or recreate the step state before dispatching the retry-start event.
Useful? React with 👍 / 👎.
| type: 'step.end', | ||
| uuid: step.uuid, | ||
| turnId: String(requesting.turnId), | ||
| step: requesting.step, |
There was a problem hiding this comment.
Accumulate usage across retried attempts
For a request that reports token usage and then retries, this new step.end records every attempt with a fresh UUID but the same numeric step. applyLoopEvent in conversationFold.ts replaces any existing summary with the same step index before recomputing turn.usage, so the next attempt silently removes the failed attempt's usage and desktop/web receive an undercounted turn total. Preserve distinct attempt summaries or aggregate their usage when sharing the logical step index.
Useful? React with 👍 / 👎.
| switch (event.type) { | ||
| case 'turn.step.started': { | ||
| const key = `${event.agentId}:${event.turnId}:${event.stepId ?? event.step}`; | ||
| if (this.startedSteps.has(key)) return; |
There was a problem hiding this comment.
Clear retry status when a duplicate step start arrives
For a subagent retry, llm.sent intentionally re-emits turn.step.started with the same step ID after turn.step.retrying, so this early return leaves the existing step's retrying field unchanged. The activity viewer therefore continues showing the backoff message while the next request is running and even after it succeeds, until another logical step begins. Treat the duplicate as an attempt-boundary update by clearing retrying and bumping the record before returning.
Useful? React with 👍 / 👎.
| finish: event.finish, | ||
| messageId: event.messageId, | ||
| requestId: event.requestId, | ||
| timing: event.timing, |
There was a problem hiding this comment.
Persist timing metadata for failed retry attempts
When a failed provider attempt supplies timing data and is retried, this field is passed into assistantEntryOf, but that function does not copy timing into AssistantMeta; the retry journal then builds step.end only from the assistant entry and emits none of the supported latency fields. As a result, conversation debug and timing views silently omit every failed attempt's request timing. Store the retry outcome metadata on the journal step or write the timing fields directly when handling llm.retrying.
Useful? React with 👍 / 👎.
Ingest the 15 upstream commits landed after the 2.5.3 release sync and cluster the open backlog into themed batches. Three rows stay unassigned pending a scope decision: prediction (MoonshotAI#4754, six packages), upgrade prompts (MoonshotAI#4756), and the desktop-titled retry fix (MoonshotAI#4831) whose content lives in agent-core-v2/kap-server.
… retry row Port upstream MoonshotAI#4831 (partial). - Report a failed attempt's usage, message id and timing through a new ModelRequestParams.onAttemptFailure callback into the machine retrying event, so the retried step's step.end is populated while the partial content stays in the wire and history without a duplicate assistant message. - Dedupe replayed turn.step.started events in SubagentActivityStore and reuse the failed attempt's row when the retry opens a new step number, clearing the retrying marker on the next start. - Probe the task half as already equivalent: onDidChangeTask pushes every registration, detach and terminal change to SessionTaskFeed, and settle releases the foreground release, handle subscription and timeout. No production change. - Ledger MoonshotAI#4831 stays partial: the upstream loop-core restructure is blocked on unlanded MoonshotAI#4630.
--refresh adds the 148 upstream commits that were missing from the ledger; the true open count is now 149, not 1. The refresh keeps the existing MoonshotAI#4820/MoonshotAI#4831/MoonshotAI#4352 corrections.
Requirement or Bug
Desktop and CLI agent workflows can lose live task metadata, leave the retry indicator stuck after the next request starts, drop text from failed attempts, and block later background tool calls. This PR restores correct task updates, retry presentation, partial-response history, and concurrent background execution.
Supersedes #4828, which was closed without merging to retarget this change from the release branch to
main.Bug Reproduction Steps
Requesting…. Stream text before cutting both attempts: the first partial response is missing.Root Cause
execute()settled. Detached tools acknowledge the loop but continue running in the background, incorrectly retaining their leases.This is a fundamental fix in the existing event, journal, and scheduler paths, not a workaround.
Code Changes
IAgentTaskServiceand use them for KAP's initial and streaming task states.llm.sentafter a retry to publishTurnStepStartedand clear the projected retry state.llm.retrying, persist them as partial responses, and give each attempt a distinct journalstepUuidso live views and resumes preserve every partial response.snapshot.detachedwhile keeping handlers, output, and terminal task lifecycle alive.Behavior Changes and Affected Users
Requesting…; every failed attempt's partial text survives live rendering and resume.Affected modules and coverage:
agent/task,sessionEventBroadcaster.test.ts, and desktopsettings-agent-defaults.loop.test.ts,conversation.test.ts,subagent-activity-store.test.ts, and desktoplifecycle-model-errors.agent/toolExecutorand desktopagents-tasks-todos.main: 17 focused test files, 496 tests passed; full repository typecheck and build passed. Desktop scenarios were validated before the rebase:lifecycle-model-errors2/2 andsettings-agent-defaults + agents-tasks-todos6/6.No default is flipped and no existing behavior is removed.
Checklist
gen-changesetsskill and included apatchchangeset for@moonshot-ai/kimi-code.