Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(orchestrator): Prevent redundant delegated completion turns #5311

Mergedmwolson(GitHub profile, opens in a new tab)merged 5 commits intot3code/codex-turn-mapping fromrefs/pull/5311/headmerged by juliusmarminge View on GitHub

Summary

  • Decision brief: evidence, product tradeoffs, and the final durable-delivery design.
  • Coalesce app-owned delegated child terminals into one durable, queued completion delivery per parent-run cohort, with at most one successor for results that arrive after the first delivery starts.
  • Let a parent acknowledge a terminal result through task_status or an untruncated direct-child read, then cancel its unstarted stale delivery without deleting the result.
  • Hide automatic completion deliveries from web and mobile queue controls while preserving their scheduler priority and allowing their prompt to appear if the delivery enters the conversation.
  • Add durable Stop, task-cancel, Queue Remove, archive, delete, and recovery barriers around server-owned completion delivery.

Problem and Fix

Problem and Why it HappenedFix
#4499 delegated-task-parent-wake deliberately created one real queued parent continuation for every async child terminal. Sibling completions therefore fanned out into repeated parent turns and timeline output.A parent-run cohort reserves one delivery that terminal siblings join before it starts. A late result gets at most one bounded successor instead of recursively re-arming the parent.
A parent could read a result through task_status or its direct child timeline, but the scheduler had no durable observation signal, so its queued completion still ran later.Terminal task_status reads and untruncated direct-child terminal-result reads durably acknowledge the task and remove it from the queued delivery. Status-only waits, prompt-only reads, and truncated results do not acknowledge. When no owned task remains, the queued run is cancelled.
Stop, Queue Remove, archive, and delete cancelled transient work but did not own or dispose future completion delivery.Durable cohort and task-delivery states make these actions replay-safe barriers. Results remain inspectable even when their automatic delivery is disposed.
Server-created completion messages looked like normal queue entries and exposed Edit, Reorder, and Steer controls. In particular, a Grok wake could be converted into interrupt-and-restart steering.Server commands reject those mutations, while web and mobile omit automatic completion entries from visible queue controls. The scheduler still gives every surviving hidden delivery priority over ordinary queued messages, and the prompt remains visible once it enters the conversation.

Defensive Fixes

Problem and Why it HappenedFix
Provider lifecycle updates can persist a full run or subagent row captured before a later acknowledgement or Stop barrier.Projection storage preserves newer delivery state when a stale provider row omits it, and run finalization intentionally excludes its old cohort snapshot.
A continuation offer can survive in memory while a cohort is acknowledged, disposed, archived, deleted, or replaced by a later generation.The worker rereads durable projection ownership immediately before dispatch and drops an offer that is no longer current.

Validation

  • Focused MCP, continuation-worker, projection, Claude allowlist, scheduler-priority, and hidden queue presentation tests pass.
  • Direct-child read coverage proves that only the complete terminal result, rather than t3_thread_wait, a prompt-only page, or a truncated result, acknowledges delivery.
  • Isolated real-provider verification proved one durable delivery for one child, coalescing for two async Grok children, acknowledgement persistence, and durable acknowledgement and retraction before a queued delivery starts.
  • vp check passes with no warnings or lint errors, all 15 typecheck tasks pass, and the desktop production build succeeds.
  • The current source tip was integrated into the v2.1 trial, where focused queue and delegated-completion coverage and guarded Nightly AppImage package verification pass.

Note

High Risk Changes orchestration scheduling, MCP tool semantics, and durable completion-delivery state across server projection, continuation workers, and clients—incorrect acknowledgement or disposal could drop or duplicate parent work.

Overview Stops one parent continuation per async child terminal by coalescing app-owned delegated results into a single durable queued delivery per parent-run cohort, with at most one bounded successor when a terminal arrives after the first delivery has already started.

MCP observation now owns delivery lifecycle: task_status, delegate/wait paths, and an untruncated direct-child t3_thread_read of the terminal assistant result dispatch completion-delivery.acknowledge and cancel the stale queued run when no tasks remain. t3_thread_wait, prompt-only reads, and truncated pages do not acknowledge. task_cancel interrupts the child when possible and disposes automatic delivery (including on already-terminal tasks) without hiding the result. Tool metadata marks task_status and t3_thread_read as non-read-only; Claude’s read-only MCP allowlist drops those tools accordingly.

Race-safety: checkpoint capture and related run finalization omit delegatedCompletion from stale run snapshots so newer cohort state is not overwritten; tests cover acknowledge/dispose idempotency and wake-policy upgrades after delivery settled.

Mobile queue rows gain a Remove control wired to queued-run.cancel, with shared presentation helpers for enablement and command building. Integration tests expand heavily around coalescing, Stop barriers, server-owned queue mutation rejects, late completions, and queue remove.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a60f38e6d39a10455ee192126662e9ae6aaadc6a. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Prevent redundant delegated completion turns by tracking delivery state across runs

  • Adds a delegatedCompletion cohort to runs and completionDelivery to subagents in the contract schema, enabling generation-tracked, durable ownership of delegated task completion delivery.
  • ProviderContinuationService now dispatches delegated completions as server-owned queued messages with capped exponential backoff retries and revalidation before re-offer; drops on archivedAt/deletedAt.
  • ProjectionStore preserves delegatedCompletion on runs and completionDelivery on subagents when newer events omit those fields, both in-memory and in SQL upserts.
  • CheckpointCaptureService and RunExecutionService strip delegatedCompletion from finalized run snapshots to avoid overwriting a newer cohort.
  • MCP tool handlers (readTask, waitForTask, taskStatus, cancelTask, readThread) now dispatch delegated_task.completion-delivery.acknowledge or dispose commands at the appropriate points in the task lifecycle.
  • Automatic completion delivery runs are hidden from the visible queue in both web and mobile clients via deriveThreadQueueWorkflowState and queuedRunsInDeliveryOrder.
  • Risk: ProjectionStore SQL upsert behavior changes for any row that previously stored delegatedCompletion/completionDelivery; stale events no longer overwrite those fields.
Macroscope summarized a60f38e.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 1b7060e3-68e2-4610-bd0a-74c7849c81cf

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. mwolson(GitHub profile, opens in a new tab) changed the title

    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/cfb5bacb1af1eaf72d3b1381e6fb8441d9346e67/apps/mobile/src/features/threads/thread-work-log.tsx#L192-L209

      collapsedWorkLogHeight computes the collapsed group height from every activity row plus a header, but when a group has overflow the component only renders the final MAX_VISIBLE_WORK_LOG_ENTRIES row (1) and an overflow toggle button. The returned height therefore covers all rows while only one row plus the toggle is rendered, so the virtual list gets a fixed size that doesn't match the actual content — causing incorrect scroll offsets and visible jump corrections when the row is measured. The toggle height needs to be included and the row count clamped to match visibleRows.

      -  const rows = visibleWorkLogActivities(activities);
      +  const visibleActivityCount = Math.min(
      +    visibleWorkLogActivities(activities).length,
      +    MAX_VISIBLE_WORK_LOG_ENTRIES,
      +  );
      +  const rows = visibleWorkLogActivities(activities).slice(-visibleActivityCount);
         if (rows.length === 0) {
           return 0;
         }
         const onlyToolRows = rows.every((row) => row.toolLike);
         const headerHeight =
           scaledTypographyLineHeight(MOBILE_TYPOGRAPHY.caption, baseFontSize) + WORK_LOG_HEADER_PADDING;
         return (
           WORK_LOG_BOTTOM_MARGIN +
      -    (onlyToolRows ? 0 : headerHeight) +
      +    (onlyToolRows ? 0 : headerHeight) +
      +    WORK_GROUP_TOGGLE_HEIGHT +
           rows.length * WORK_ROW_HEIGHT +
           (rows.length - 1) * WORK_ROW_GAP
         );
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/thread-work-log.tsx around lines 192-209:
      
      `collapsedWorkLogHeight` computes the collapsed group height from every activity row plus a header, but when a group has overflow the component only renders the final `MAX_VISIBLE_WORK_LOG_ENTRIES` row (1) and an overflow toggle button. The returned height therefore covers all rows while only one row plus the toggle is rendered, so the virtual list gets a fixed size that doesn't match the actual content — causing incorrect scroll offsets and visible jump corrections when the row is measured. The toggle height needs to be included and the row count clamped to match `visibleRows`.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/cfb5bacb1af1eaf72d3b1381e6fb8441d9346e67/apps/mobile/src/features/threads/thread-work-log.tsx#L185

      collapsedWorkLogHeight budgets 32 px per row (WORK_ROW_HEIGHT = 32), but each row's inner View uses min-h-9 (36 px) inside a py-0.5 (2 px top + 2 px bottom) Pressable, making every row at least 40 px tall. ThreadFeed.getFixedItemSize passes this pre-measured height to the list for all collapsed activity groups, so the list underestimates offsets by 8 px per row. Scrolling up through unmeasured groups jumps as each row's actual height is measured and corrects the offset. Update WORK_ROW_HEIGHT from 32 to 40 to match the min-h-9 plus py-0.5 chrome.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/thread-work-log.tsx around line 185:
      
      `collapsedWorkLogHeight` budgets 32 px per row (`WORK_ROW_HEIGHT = 32`), but each row's inner `View` uses `min-h-9` (36 px) inside a `py-0.5` (2 px top + 2 px bottom) `Pressable`, making every row at least 40 px tall. `ThreadFeed.getFixedItemSize` passes this pre-measured height to the list for all collapsed activity groups, so the list underestimates offsets by 8 px per row. Scrolling up through unmeasured groups jumps as each row's actual height is measured and corrects the offset. Update `WORK_ROW_HEIGHT` from 32 to 40 to match the `min-h-9` plus `py-0.5` chrome.
    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. This does not occur in the current feed path. appendPresentedFeedEntry splits an overflowing activity group into one-activity activity-group entries plus a separately sized work-toggle before getFixedItemSize runs. The helper therefore does not receive the multi-row collapsed group described here. The target file is also byte-identical between merge base 9fe804449 and current head 427c765a9, so no change is needed in this branch.

    7. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    8. This is a valid pre-existing sizing mismatch. WORK_ROW_HEIGHT still budgets 32 pixels while the rendered row has a min-h-9 child inside a py-0.5 pressable. However, thread-work-log.tsx is byte-identical between merge base 9fe804449 and current head 427c765a9. This should be repaired together with the prominent-row sizing issue in a separate mobile change.

    9. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    10. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/d1025b8698b4b6f791a006525705db0cdbb60e35/apps/server/src/mcp/OrchestratorMcpService.ts#L1288

      cancelTask can silently leak a completion-delivery subscription: if the task is non-terminal at the first readTask but the child run settles before the child projection is loaded, activeRun is undefined and the function returns task_not_cancellable without ever dispatching disposeCompletionDelivery. The prepared dispose effect is dropped, so the parent's automatic wake/turn stays active even though the caller tried to cancel. Consider dispatching disposeCompletionDelivery on every non-success exit path — including the task_not_cancellable return — so the subscription is always released.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/mcp/OrchestratorMcpService.ts around line 1288:
      
      `cancelTask` can silently leak a completion-delivery subscription: if the task is non-terminal at the first `readTask` but the child run settles before the child projection is loaded, `activeRun` is `undefined` and the function returns `task_not_cancellable` without ever dispatching `disposeCompletionDelivery`. The prepared dispose effect is dropped, so the parent's automatic wake/turn stays active even though the caller tried to cancel. Consider dispatching `disposeCompletionDelivery` on every non-success exit path — including the `task_not_cancellable` return — so the subscription is always released.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderContinuationService.ts:99

      When a delegatedCompletion request reaches the archived/deleted early-return path, clearRetryAttempt is never called. If a prior dispatch failure created a retry entry in retryAttempts, and the thread is then archived or deleted before the retry fires, that entry stays in the map permanently. Repeating this pattern leaks stale entries for the lifetime of the worker.

      The early-return block handles clearIfCurrent/dispatchIfCurrent but skips the retry cleanup that the delegatedCompletion path performs on success (line 129) and on stale delivery (line 106). Consider calling clearRetryAttempt for delegatedCompletion requests in the archived/deleted branch too.

      ✅ Resolved in a60f38e6d39a10455ee192126662e9ae6aaadc6a

    11. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d1025b8698b4b6f791a006525705db0cdbb60e35. Configure [here](https://www.cursor.com/dashboard/bugbot).
    12. This is intentional. A no-active-run result means cancellation did not succeed, and the child may already be settling. Disposing completion delivery on that failure path would suppress the later completion despite returning task_not_cancellable. The current tests assert both no-active-run and interrupt-failure paths leave delivery open so a subsequently settled child can still wake its parent.

    13. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    14. juliusmarminge merged this99c957d

    15. juliusmarminge closed this

Sign in to join this conversation.