Skip to content

fix(desktop): preserve retry and background task behavior - #4828

Closed
sailist wants to merge 4 commits into
changeset-release/release/2026-11-12from
bug-349-11-11-foreground-task-events
Closed

sailist wants to merge 4 commits into
changeset-release/release/2026-11-12from
bug-349-11-11-foreground-task-events

Conversation

@sailist

@sailist sailist commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

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 deadlock later background tool calls. This PR restores correct task updates, retry presentation, partial-response history, and concurrent background execution.

Bug Reproduction Steps

  • Configure a subagent model and start a foreground agent: the task card lacks its model name, and foreground task controls do not update.
  • Return an error for the first model request and hold the retry: the UI keeps showing the retry state instead of Requesting…. Stream text before cutting both attempts: the first partial response is missing.
  • Start two background Bash calls in one model step: the second call never starts, so the next model step cannot begin.

Root Cause

  • Live task updates were narrowed to durable start/termination events, so KAP no longer forwarded foreground task changes.
  • Retry state was cleared only at logical step boundaries, while multiple attempts share a step. Failed-attempt messages were also not persisted with independent identities, so later content replaced earlier content during replay.
  • Scheduler leases were released only when 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

  • Restore live task-change notifications from IAgentTaskService and use them for KAP's initial and streaming task states.
  • Reuse llm.sent after a retry to publish TurnStepStarted and clear the projected retry state.
  • Carry failed-attempt messages through llm.retrying, persist them as partial responses, and give each attempt a distinct journal stepUuid so live views and resumes preserve every partial response.
  • Release scheduler leases on snapshot.detached while keeping handlers, output, and terminal task lifecycle alive.
  • Align the test harness with the real llm.sent contract and strengthen existing regression cases without increasing the test count.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Foreground task updates Task cards can omit model metadata and live controls. Foreground Bash and subagents publish live task state; detached tasks still use their existing durable events. Desktop users inspecting or detaching foreground work. Not required; existing task APIs are preserved.
Retry status and partial responses Retry text remains after the next request starts, and partial text from failed attempts is lost or overwritten. The next attempt shows Requesting…; every failed attempt's partial text survives live rendering and resume. Desktop and CLI users recovering from provider errors or interrupted streams. Not required; logical step semantics and public wire contracts are preserved.
Background tool scheduling A detached tool retains its scheduler lease until process exit, blocking conflicting calls. Detach releases the scheduling lease while the process continues in the background. Users starting multiple background tools in one step. Not required; task output, stop, and completion behavior is preserved.

Coverage:

  • Task events: rpc-events.test.ts, taskService.test.ts, sessionEventBroadcaster.test.ts, foreground-persistence.test.ts, and desktop settings-agent-defaults.
  • Retry and conversation replay: loop.test.ts, conversation.test.ts, and desktop lifecycle-model-errors.
  • Detached scheduling: toolExecutor.test.ts, toolScheduler.test.ts, and desktop agents-tasks-todos.
  • Additional verification: focused core/KAP tests, both package typechecks, and the root build pass.

No default is flipped and no existing behavior is removed.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (the reproduction and root cause are included above).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete; no removed behavior or flipped default needs an escape hatch or explicit approval.
  • Ran gen-changesets skill and included a patch changeset for @moonshot-ai/kimi-code.
  • No documentation update is needed for these bug fixes.

- clear retry status on the next attempt and preserve partial responses
- release scheduler leases when tools detach
@changeset-bot

changeset-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: e24a3c4

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T09:11:49.316327Z e24a3c4 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@e24a3c4
npx https://pkg.pr.new/@moonshot-ai/kimi-code@e24a3c4

commit: e24a3c4

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7776938b6e

ℹ️ 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".

Comment on lines +1476 to +1479
if (event.type === 'llm.retrying') {
const entry = assistantEntryOf({ type: 'failed', error: event.error, message: event.message ?? undefined }, step.model);
if (entry !== undefined) {
this.record({ type: 'message.appended', turnId: turn.id, step: turn.step, source: 'partial', entry });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid re-appending a partial when retry cancellation wins

When an attempt produces partial output and enters a backoff retry, this records the failed attempt's message immediately. If the user cancels during that delay, abortedOf() returns the same message in the aborted outcome, and completeRequest() appends it again. The cancelled turn therefore leaves duplicate assistant messages in the live history, so a subsequent prompt can send the duplicated partial to the model. Track that the retry partial was already recorded, or omit it from the aborted outcome.

Useful? React with 👍 / 👎.

Comment thread .changeset/lucky-tools-retry.md Outdated
"@moonshot-ai/kimi-code": patch
---

Fix retry status, partial responses, and task execution updates in agent workflows.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Split and clarify the unrelated changeset entries

This single vague sentence combines three independently user-visible changes—retry state, preservation of failed-attempt partials, and live task updates—while “task execution updates” does not tell users what behavior changed. Split these into one logical change per changeset and describe each concrete outcome so the generated changelog remains actionable.

AGENTS.md reference: AGENTS.md:L108-L108

Useful? React with 👍 / 👎.

Comment on lines +393 to +397
this.writeLoopEvent({
type: 'step.end',
uuid: step.uuid,
turnId: String(requesting.turnId),
step: requesting.step,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve retry state until the next attempt starts

For desktop and web clients consuming the conversation feed, this new step.end is dispatched after TurnStepRetrying because AgentLoopService projects the retry before appending it to the journal. applyLoopEvent() clears turn.retry whenever it folds a step.end, and the feed coalesces both commits in one microtask, so a backoff retry is exposed only as a failed step and the intended retry status is never delivered during the delay. Keep the retry marker through this failed-attempt boundary and clear it only when the following step.begin/TurnStepStarted arrives.

Useful? React with 👍 / 👎.

- keep retry state during backoff and avoid duplicate partial responses
- release scheduler leases when tools detach
- use one desktop changeset for the related fixes
@sailist sailist changed the title fix(agent-core-v2): align retry and detached tool lifecycles fix(desktop): preserve retry and background task behavior Nov 11, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7620127f31

ℹ️ 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".

Comment on lines +525 to +530
void this.options.dispatcher.dispatch(new TurnStepStarted({
agentId: this.options.scopeContext.agentId,
turnId: turn.id,
step,
stepId: turn.current?.uuid ?? turn.stepIds.get(step),
}));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid counting retry attempts as new subagent steps

When a subagent request retries, this emits another TurnStepStarted with the same logical step number. SubagentActivityStore.applyEvent() treats every such event as a distinct step and increments totalSteps, while the activity viewer renders the logical range against that count; one retry in step 1 therefore produces step 1–1 / 2 and can prematurely evict genuine earlier steps from its bounded history. Clear the retry state without re-emitting a logical step-start event, or make this consumer deduplicate repeated starts for the same turn and step.

AGENTS.md reference: AGENTS.md:L102-L105

Useful? React with 👍 / 👎.

Comment on lines 224 to +225
error: result.error,
message: result.message ?? undefined,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve usage metadata for failed retry attempts

When a failed attempt has already emitted provider usage before entering backoff, this new retry event forwards only its message and error. requestProgress() consequently reconstructs an LlmOutcome without usage, so assistantEntryOf() assigns empty usage and the journal's newly persisted failed-attempt step.end reports zero usage; cancelling during the backoff leaves that incorrect usage permanently in the conversation, and completed retry histories likewise under-report the failed request. Carry the failed result's usage and related response metadata through LlmRetrying when persisting the attempt.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 38b6ab1b0f

ℹ️ 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".

switch (event.type) {
case 'turn.step.started': {
const key = `${event.agentId}:${event.turnId}:${event.stepId ?? event.step}`;
if (this.startedSteps.has(key)) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear retry state when deduplicating step starts

When a subagent enters backoff, turn.step.retrying sets step.retrying, and v2 then deliberately emits another turn.step.started with the same step ID when the next attempt begins. This early return prevents the duplicate from incrementing totalSteps, but it also leaves the retry marker untouched, so the activity viewer continues displaying “retrying” throughout the new attempt and even after the subagent completes. Handle the duplicate by clearing the current step's retry marker and bumping the record without appending another step.

Useful? React with 👍 / 👎.


export class SubagentActivityStore {
private readonly records = new Map<string, SubagentActivityRecord>();
private readonly startedSteps = new Set<string>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release deduplication keys when activity records are dropped

In sessions that spawn many foreground-only subagents, every step start adds an entry to this set, but drop(agentId) removes only the activity record and streaming buffers. Because subagent IDs are normally unique and the store lasts for the session, completed foreground agents therefore leave all their deduplication strings resident indefinitely, defeating the explicit pruning path and creating unbounded session-long memory growth. Remove the matching agent's keys when its record is dropped, or scope the deduplication state to the retained record.

Useful? React with 👍 / 👎.

- 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
@sailist
sailist force-pushed the bug-349-11-11-foreground-task-events branch from 38b6ab1 to e24a3c4 Compare November 11, 2026 09:08
@sailist sailist closed this Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant