Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): settle threads server-side #8600

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 13 commits intomain fromrefs/pull/8600/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

Automatic settlement still ran in clients and used device-local settings. Devices could disagree about whether a thread was settled, and the rules did not run without an open client.

The server now owns PR-based and inactivity-based settlement and stores both settings per environment. Clients render the saved settlement state. The server uses the existing settlement events to stop provider sessions. State checks prevent a delayed automatic decision from overriding new activity or a manual reopen.

Defaults stay at 3 days with settlement on merge enabled. Old device-local settings no longer apply. Changing a rule does not reopen settled threads. No database migration is needed.

Focused tests, scoped typechecks, targeted lint, and formatting passed. The browser check used two independent browser sessions against disposable servers with API-seeded data. No agent sessions were started. Native UI was not tested.

The images show the second browser after the first disabled "Auto-settle merged threads". Before this change, the second browser kept the setting on. After this change, both browsers showed it off, including after reload. Disabling inactivity settlement synced between browsers too.

BeforeAfter
Second browser keeps merge settlement enabledSecond browser receives the disabled merge settlement setting

Changes and PR text by GPT-5.6 Sol in T3 Code with the Codex harness.


Note

High Risk Changes core orchestration settlement, cross-client thread visibility, and git/PR-driven auto-settle decisions; stale or wrong PR identity could mis-classify threads.

Overview Moves automatic thread settlement off clients and onto the server, so settled state stays consistent without an open app and settings apply per environment.

A new ThreadSettlementReactor runs periodic sweeps: it evaluates inactivity and PR state via ThreadSettlementPolicy, deduplicates PR lookups (linked PR detail + GitManager.branchPullRequest for saved branches), and dispatches thread.auto-settle with a snapshot-sequence guard and blocks when background work is live. The engine advertises threadAutoSettlement; sidebarAutoSettleAfterDays / sidebarAutoSettleOnMerge are server settings (desktop client defaults drop the old keys).

Clients render server truth: mobile Thread List v2 partitions on settledOverride only—removed per-row PR streaming, device autoSettleOnMerge, and effectiveSettled inference. Mobile General settings expose per-environment auto-settle-on-merge toggles backed by server settings when the capability is on.

Settle command behavior tightens: blocked manual/auto settle returns OrchestrationThreadSettleBlockedError (persisted rejected receipt); websocket settle no longer chains session stop—ProviderCommandReactor stops the provider on thread.settled with onlyIfSettled. GitManager gains identity-checked PR lookup caching for settlement and branch lookups without changing checkout.

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

Note

Move thread auto-settlement from client to server with ThreadSettlementReactor

  • Adds a server-side ThreadSettlementReactor that periodically sweeps threads and dispatches thread.auto-settle commands based on PR status and inactivity, grouped by PR context to minimize lookups.
  • Introduces shared ThreadSettlementPolicy with shouldAutoSettleThread, isAutoSettlementCandidate, pullRequestSettles, and threadHasQueuedTurnStart; the decider and engine now enforce OrchestrationThreadSettleBlockedError for blocked settles and reject thread.auto-settle when the thread changed or has live background work.
  • Adds GitManager.branchPullRequest to resolve a branch's PR without changing checkout, with caching keyed by branch existence and remote identity.
  • Moves sidebarAutoSettleAfterDays and sidebarAutoSettleOnMerge from ClientSettings to ServerSettings; web/mobile UIs now rely solely on server-projected settledOverride and render per-environment toggles gated by the new threadAutoSettlement capability.
  • Removes client-side effectiveSettled, canSettle, changeRequestAutoSettles, and local PR-state tracking across web/mobile/desktop; clients no longer block settle locally.
  • Risk: ClientSettingsSchema no longer accepts sidebarAutoSettleAfterDays/sidebarAutoSettleOnMerge; clients with legacy persisted values may fail validation unless migrated. ws.ts no longer stops provider sessions or closes terminals on thread.settle (only thread.archive does); session stop now happens via the ProviderCommandReactor thread.settled handler.
Macroscope summarized 03db756.
    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: 9ee8608e-a3e2-4f90-8b94-d8020cf3611a

      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

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

    3. Reviewed the new ThreadSettlementReactor service and its consumers against the Effect service conventions. One finding: the new service is defined in the legacy Services/ + Layers/ split with a standalone Shape interface and a *Live layer export. Everything else (dependency acquisition from the environment, namespaced effect/* subpath imports, Layer.succeed/Layer.mock only in test harnesses, no ManagedRuntime/runPromise in service code, error construction in GitManager.branchPullRequest) matches the conventions.

      Posted via Macroscope — Effect Service Conventions
    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire13.3 KiB13.4 KiB+159 B (+1.2%)15.1 KiB✅
      CodexThread snapshot wire6.9 KiB6.9 KiB+9 B (+0.1%)7.3 KiB✅
      CodexLive turn WebSocket wire6.4 KiB6.5 KiB+150 B (+2.3%)7.8 KiB✅
      CodexLive turn WebSocket decoded55.6 KiB57.0 KiB+1.4 KiB (+2.6%)66.4 KiB✅
      CodexLive turn messages10100 (0.0%)21✅
      ClaudeTotal thread wire13.5 KiB13.2 KiB−229 B (−1.7%)15.1 KiB✅
      ClaudeThread snapshot wire6.9 KiB6.9 KiB−5 B (−0.1%)7.3 KiB✅
      ClaudeLive turn WebSocket wire6.6 KiB6.3 KiB−224 B (−3.3%)7.8 KiB✅
      ClaudeLive turn WebSocket decoded57.8 KiB56.3 KiB−1.5 KiB (−2.6%)66.4 KiB✅
      ClaudeLive turn messages108−2 (−20.0%)21✅

      Baseline: 0bfb6df · PR result: 03db756 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 109.4 KiB
      • Claude decoded thread snapshot: 110.1 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — The PR introduces server-owned automatic thread settlement that runs without a connected client, including periodic PR lookups, persisted lifecycle changes, and provider-session cleanup. It also changes the scope of the settlement defaults and adds static-analysis suppression directives, so the broader runtime and configuration impact should receive human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Reviewed the new ThreadSettlementReactor service and the touched call sites against the Effect service conventions. The hoist to apps/server/src/orchestration/ThreadSettlementReactor.ts (inline Context.Service interface, exported make, exported layer, ThreadSettlementReactor["Service"] references, namespaced effect/* and local service imports) looks correct, and the old Services//Layers/ modules are gone. One leftover from that migration: the reactor's test file still lives in orchestration/Layers/.

      Posted via Macroscope — Effect Service Conventions
    7. One UI consistency finding on the newly capability-gated auto-settle rows. Everything else in the web scope (settled state now read from settledOverride in Sidebar, ChatView, and the thread action menu, and the mergeEnvironmentSettings precedence flip) is internally consistent.

      Posted via Macroscope — UI Consistency
    8. One finding: removing the client-side settle pre-flight leaves the Settle affordances enabled for ineligible threads, so users now see a raw server invariant string instead of the product-worded blocked message.

      Posted via Macroscope — UI Consistency
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Dropping the canSettle pre-flight here changes what the user sees, because the Settle affordances are still offered for ineligible threads: buildThreadActionMenuItems gates settle on the capability only (isRunning disables Archive, not Settle), and the sidebar row's hover Settle button is gated on settlementSupported alone — unlike Snooze, which is gated by canSnooze. Clicking Settle on a running/starting session or a thread with a pending approval or user-input request now reaches the decider and the failure toast renders the transported message, i.e. Orchestration command invariant failed (thread.settle): thread <id> has an active session and cannot be settled, where it previously read This thread still needs attention. Resolve or interrupt it first, then try again. ThreadSettleBlockedError is now unreferenced while its snooze sibling is still used, so the two lifecycle actions report blocked states inconsistently.

      Keeping a cheap client pre-flight (the server stays authoritative) restores the wording without reintroducing client-side settlement classification:

             const resolved = resolveThreadTarget(target);
      +      if (
      +        resolved &&
      +        (resolved.thread.hasPendingApprovals ||
      +          resolved.thread.hasPendingUserInput ||
      +          resolved.thread.session?.status === "starting" ||
      +          resolved.thread.session?.status === "running")
      +      ) {
      +        return AsyncResult.failure(
      +          Cause.fail(
      +            new ThreadSettleBlockedError({
      +              environmentId: resolved.threadRef.environmentId,
      +              threadId: resolved.threadRef.threadId,
      +            }),
      +          ),
      +        );
      +      }

      Disabling the menu item and hover button for those states instead would work equally well.

      Posted via Macroscope — UI Consistency
    9. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      The server now returns a typed blocked-settlement error with the existing friendly message. Eligibility stays server-owned. The engine preserves that error and records a rejected command receipt. Removed the unused client error class. Focused tests cover all blocked cases, the engine receipt, and the message sent over WebSocket RPC.

    10. Service-convention items from earlier runs are resolved: ThreadSettlementReactor now lives in one canonical module (apps/server/src/orchestration/ThreadSettlementReactor.ts) with an inline Context.Service interface, make, layer, and its test alongside it, and consumers reference ThreadSettlementReactor["Service"].

      The remaining finding is the un-explained diagnostic suppressions added by this PR. Besides the two commented sites, apps/server/src/git/GitManager.test.ts lines 1055, 1115, 1193, and 1245 add the same bare preferSchemaOverJson:off directive and need the same short justification (the repo already does this elsewhere, e.g. bin.test.ts and bootService.test.ts).

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      git/GitManager.test.ts:1004

      New suppression directives should carry an adjacent reason; the directive alone does not explain why the diagnostic must be off here. Consider appending a short justification, as other suppressions in this repo do.

                  // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed `gh` CLI stdout fixture, not a decoded domain payload.

      No longer relevant as of 917f7d810d68e9fadfc3806738c037328edbea91

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

      src/serverSettings.test.ts:289

      Same here: please add an adjacent explanation for the suppression so the reason survives future edits.

              // @effect-diagnostics-next-line preferSchemaOverJson:off - asserts the raw persisted settings file, deliberately bypassing the schema.

      No longer relevant as of 917f7d810d68e9fadfc3806738c037328edbea91

    11. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Fixed. Each new GitManager suppression now has an adjacent reason: the fixture must produce raw JSON stdout because it tests the gh CLI boundary. The diagnostic directive stays immediately above the affected expression.

    12. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Fixed. The suppression now explains that the test inspects the raw persisted JSON before schema decoding can apply defaults. The diagnostic directive stays immediately above JSON.parse.

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

      🟠 High orchestration/ThreadSettlementPolicy.ts:88

      isAutoSettlementCandidate returns true for threads with backgroundLiveness set to working or monitoring, so auto-settlement dispatches a session stop and terminates the provider's still-running background work. Add these liveness states to the early exclusions, matching the session reaper's unsafe-to-stop handling.

        if (
          thread.hasPendingApprovals ||
          thread.hasPendingUserInput ||
          thread.backgroundLiveness === "working" ||
          thread.backgroundLiveness === "monitoring"
        ) return false;
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration/ThreadSettlementPolicy.ts around line 88:
      
      `isAutoSettlementCandidate` returns `true` for threads with `backgroundLiveness` set to `working` or `monitoring`, so auto-settlement dispatches a session stop and terminates the provider's still-running background work. Add these liveness states to the early exclusions, matching the session reaper's unsafe-to-stop handling.
    14. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Automatic settlement now persists a thread.settled event, so it can stop provider work in a way that the old client-only classification could not. I now exclude both working and monitoring background work from automatic settlement. Manual settlement stays unchanged.

    15. 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 30248900955d596d7b36bf762cb1eec3037aaaa6. Configure [here](https://www.cursor.com/dashboard/bugbot).
    16. t3dotgg(GitHub profile, opens in a new tab) changed the title

Sign in to join this conversation.