Skip to content
Source
Sign inSign up
pingdotgg/t3code

Fix turn fold proejctions #3041

Mergedjuliusmarmingemerged 3 commits intomain fromrefs/pull/3041/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

  • Rebrands T3 Cloud surfaces to T3 Connect across web, mobile, desktop, and release workflows.
  • Adds Grok CLI provider support, including ACP integration, provider startup, adapters, and text generation paths.
  • Refactors server-side orchestration, projection, relay diagnostics, and VCS status handling for more predictable session behavior.
  • Polishes the web and mobile UI with updated composer, model picker, diff panel, markdown rendering, settings, and context/status surfaces.
  • Updates marketing and desktop assets, including the Linux icon treatment and bundled fonts.

Testing

  • Not run (PR content generation only).
  • Existing and new tests were added across server, web, mobile, and desktop code paths as part of the change set.
  • Project validation requirements from the repo were not executed here: vp check, vp run typecheck, and relevant lint/test scripts.

Note

Medium Risk Changes core turn/session semantics across orchestration, projections, reducers, and multiple provider adapters; incorrect settlement or steering could affect active sessions and displayed turn durations.

Overview Turn settlement and chat “Worked for …” folds now treat the session leaving running as the real turn end. Interim assistant messages, mid-turn diffs, and checkpoint placeholders no longer mark a turn completed while the session still has that activeTurnId.

Steering is implemented across Claude, Cursor, Grok, and OpenCode: a sendTurn while work is in flight reuses the active turn (no extra turn.started / premature turn.completed). ACP adapters track promptsInFlight so only the last prompt settles the turn. Provider runtime ingestion allows a conflicting turn.started when the server has a pending turn start and the provider already switched to the new turn id.

Projections and client state (ProjectionPipeline, in-memory projector, web store, threadDetailReducer) share settledTurnStateForSessionStatus and settle superseded running turns when a new active turn starts. Timeline fold duration starts from the user message that opened the turn and ends at the later of terminal assistant completion vs trailing work entries; formatDuration rounds sub-10s display sensibly.

Minor: T3_ACP_PROMPT_DELAY_MS on the ACP mock agent for steer tests; @expo/metro-config pinned in workspace overrides for patch stability.

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

Note

Fix turn fold projection durations and steering turn settlement across adapters

  • Adapter layers (ClaudeAdapter, CursorAdapter, GrokAdapter, OpenCodeAdapter) now treat a sendTurn call during an active turn as a steer: reuse the existing activeTurnId, skip emitting turn.started, and merge results into the same turn record.
  • Projection pipeline, projector, client-runtime reducer, and web store all defer settling latestTurn until the session leaves running status, rather than settling on interim assistant messages or mid-turn checkpoints; completedAt is now stamped from session.updatedAt.
  • deriveTurnFolds in MessagesTimeline.logic.ts now starts fold durations at the initiating user message timestamp and ends at whichever is later between the terminal assistant completedAt and the last entry, fixing displayed "Worked for …" durations for steer-superseded turns.
  • ProviderRuntimeIngestion now accepts a conflicting provider turn.started when it matches a pending turn start expected by the server.
  • Behavioral Change: turns that previously settled on assistant message or checkpoint events will now remain running until the session status transitions away from running.
📊 Macroscope summarized 3b80ae3. 4 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    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

      Run ID: 6873bd87-69da-471d-bf73-a22c551f8e48

      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
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `t3code/6dd44ae8`

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

    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Expo continuous deployment is ready!

      • Project → t3-code
      • Platforms → android, ios
      • Scheme → t3code-preview
       🤖 Android🍎 iOS
      Fingerprintae17d94b35f91f9c608a63dadbc3ddd9f4ba056e313e506a7f15a9c3f15b01d787d68a12382432bf
      Build DetailsBuild Permalink
      DetailsDistribution: INTERNAL
      Build profile: preview:dev
      Runtime version: ae17d94b35f91f9c608a63dadbc3ddd9f4ba056e
      App version: 0.1.0
      Git commit: 193dac6f6c3b744311cf92ffa84b73f0a4f311b7
      Build Permalink
      DetailsDistribution: INTERNAL
      Build profile: preview:dev
      Runtime version: 313e506a7f15a9c3f15b01d787d68a12382432bf
      App version: 0.1.0
      Git commit: 193dac6f6c3b744311cf92ffa84b73f0a4f311b7
      Update DetailsUpdate Permalink
      DetailsBranch: pr-3041
      Runtime version: ae17d94b35f91f9c608a63dadbc3ddd9f4ba056e
      Git commit: 193dac6f6c3b744311cf92ffa84b73f0a4f311b7
      Update Permalink
      DetailsBranch: pr-3041
      Runtime version: 313e506a7f15a9c3f15b01d787d68a12382432bf
      Git commit: 193dac6f6c3b744311cf92ffa84b73f0a4f311b7
      Update QR
    4. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Stale pending after in-place steer
        • Added explicit pending turn start deletion in ProviderCommandReactor after sendTurn returns the same turnId as the existing active turn, detecting in-place steers that skip turn.started and would otherwise leave the pending row stale.
      • ✅ Fixed: User boundary overwritten before turn
        • Changed pendingUserBoundary assignment from unconditional = to ??= so the first unconsumed user message boundary is preserved when a steer arrives before any turn-bound entry consumes it.

      Create PR

      Or push these changes by commenting:

      @cursor push 59982bf87f
      Preview (pingdotgg/t3code@59982bf87f)
      diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
      --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
      +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
      @@ -1026,9 +1026,7 @@
                   // Leaving the "running" session status is the turn-end signal:
                   // settle still-running turns so their duration reflects the whole
                   // turn rather than the last assistant message.
      -            const settledTurnState = settledTurnStateForSessionStatus(
      -              event.payload.session.status,
      -            );
      +            const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
                   if (settledTurnState === null) {
                     return;
                   }
      @@ -1062,8 +1060,7 @@
                 });
                 yield* Effect.forEach(
                   otherRunningTurns.filter(
      -              (turn) =>
      -                turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
      +              (turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
                   ),
                   (turn) =>
                     turn.turnId === null
      
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
      @@ -370,6 +370,7 @@
             Layer.provideMerge(ServerSettingsService.layerTest()),
             Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
             Layer.provideMerge(NodeServices.layer),
      +      Layer.provide(SqlitePersistenceMemory),
           );
           runtime = ManagedRuntime.make(layer);
       
      
      diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
      @@ -32,6 +32,8 @@
       import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
       import { ProviderService } from "../../provider/Services/ProviderService.ts";
       import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
      +import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
      +import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
       import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
       import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
       import {
      @@ -182,6 +184,7 @@
         const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
         const providerService = yield* ProviderService;
         const providerRegistry = yield* ProviderRegistry;
      +  const projectionTurnRepository = yield* ProjectionTurnRepository;
         const gitWorkflow = yield* GitWorkflowService;
         const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
         const textGeneration = yield* TextGeneration;
      @@ -845,9 +848,19 @@
             return;
           }
       
      -    yield* providerService
      -      .sendTurn(sendTurnRequest.value)
      -      .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
      +    const existingActiveTurnId = thread.session?.activeTurnId ?? null;
      +
      +    yield* providerService.sendTurn(sendTurnRequest.value).pipe(
      +      Effect.tap((result) =>
      +        existingActiveTurnId !== null && result.turnId === existingActiveTurnId
      +          ? projectionTurnRepository.deletePendingTurnStartByThreadId({
      +              threadId: event.payload.threadId,
      +            })
      +          : Effect.void,
      +      ),
      +      Effect.catchCause(recoverTurnStartFailure),
      +      Effect.forkScoped,
      +    );
         });
       
         const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
      @@ -1075,4 +1088,6 @@
         } satisfies ProviderCommandReactorShape;
       });
       
      -export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);
      +export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make).pipe(
      +  Layer.provide(ProjectionTurnRepositoryLive),
      +);
      
      diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts
      --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts
      +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts
      @@ -943,9 +943,7 @@
       
             const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
             const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
      -      const turnCompletedEvents = runtimeEvents.filter(
      -        (event) => event.type === "turn.completed",
      -      );
      +      const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
       
             // One turn boundary for the whole run: the steer produced no
             // turn.completed/turn.started pair.
      
      diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
      --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
      +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
      @@ -190,7 +190,7 @@
         let pendingUserBoundary: string | null = null;
         for (const entry of input.timelineEntries) {
           if (entry.kind === "message" && entry.message.role === "user") {
      -      pendingUserBoundary = entry.message.createdAt;
      +      pendingUserBoundary ??= entry.message.createdAt;
             continue;
           }
           const turnId =
      You can send follow-ups to the cloud agent here.
    5. juliusmarminge changed the title

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

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. Significant runtime behavior changes to turn lifecycle management across multiple provider adapters, introducing new steering logic and changing when turns are settled. An unresolved high-severity review comment identifies a potential race condition in the GrokAdapter.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    7. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      There are 4 total unresolved issues (including 2 from previous reviews).

      Fix All in Cursor

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Late steer prompt wrong completion
        • Added a promptSequence counter and latestTurnStopReason tracker to both CursorAdapter and GrokAdapter so that turn.completed always uses the stop reason from the most recently started (highest-sequence) prompt, not the superseded prompt that may resolve last.
      • ✅ Fixed: Cursor steer before activeTurnId
        • Moved ctx.activeTurnId assignment to immediately after ctx.promptsInFlight increment, before any async applyRequestedSessionConfiguration work, so a concurrent sendTurn always sees the correct activeTurnId when detecting a steer.

      Create PR

      Or push these changes by commenting:

      @cursor push c8ceceb831
      Preview (pingdotgg/t3code@c8ceceb831)
      diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts
      --- a/apps/server/src/provider/Layers/CursorAdapter.ts
      +++ b/apps/server/src/provider/Layers/CursorAdapter.ts
      @@ -136,6 +136,12 @@
          * >0 means a turn is actively running, so a new sendTurn is a steer that
          * continues it, and only the last remaining prompt settles the turn. */
         promptsInFlight: number;
      +  /** Monotonically increasing counter identifying the most recent prompt. */
      +  promptSequence: number;
      +  /** Stop reason from the highest-sequence prompt that has completed so far
      +   * within the current turn. Used to emit `turn.completed` with the steering
      +   * prompt's result even when a superseded prompt resolves last. */
      +  latestTurnStopReason: { seq: number; stopReason: string | undefined } | undefined;
         stopped: boolean;
       }
       
      @@ -759,6 +765,8 @@
                   lastPlanFingerprint: undefined,
                   activeTurnId: undefined,
                   promptsInFlight: 0,
      +            promptSequence: 0,
      +            latestTurnStopReason: undefined,
                   stopped: false,
                 };
       
      @@ -896,6 +904,14 @@
               // resolving from here on does not settle the turn; the matching
               // decrement is the `ensuring` below.
               ctx.promptsInFlight += 1;
      +        // Set activeTurnId immediately so a concurrent sendTurn observing
      +        // promptsInFlight > 0 also finds the correct activeTurnId for steering.
      +        ctx.activeTurnId = turnId;
      +        const myPromptSeq = ++ctx.promptSequence;
      +        if (steeringTurnId === undefined) {
      +          ctx.lastPlanFingerprint = undefined;
      +          ctx.latestTurnStopReason = undefined;
      +        }
       
               return yield* Effect.gen(function* () {
                 const turnModelSelection =
      @@ -916,10 +932,6 @@
                   mapError: ({ cause, method }) =>
                     mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
                 });
      -          ctx.activeTurnId = turnId;
      -          if (steeringTurnId === undefined) {
      -            ctx.lastPlanFingerprint = undefined;
      -          }
                 ctx.session = {
                   ...ctx.session,
                   activeTurnId: turnId,
      @@ -1004,10 +1016,18 @@
                   model: resolvedModel,
                 };
       
      +          // Record result from the highest-sequence (most recent) prompt so
      +          // the turn.completed event always reflects the steering prompt's
      +          // outcome, not a superseded prompt that resolved later.
      +          if (myPromptSeq >= (ctx.latestTurnStopReason?.seq ?? 0)) {
      +            ctx.latestTurnStopReason = { seq: myPromptSeq, stopReason: result.stopReason };
      +          }
      +
                 // Only the last remaining prompt settles the turn — a steer-
                 // superseded prompt resolving (usually cancelled) while another is
                 // in flight or pending must leave the merged turn running.
                 if (ctx.promptsInFlight === 1) {
      +            const effectiveStopReason = ctx.latestTurnStopReason?.stopReason ?? result.stopReason;
                   yield* offerRuntimeEvent({
                     type: "turn.completed",
                     ...(yield* makeEventStamp()),
      @@ -1015,8 +1035,8 @@
                     threadId: input.threadId,
                     turnId,
                     payload: {
      -                state: result.stopReason === "cancelled" ? "cancelled" : "completed",
      -                stopReason: result.stopReason ?? null,
      +                state: effectiveStopReason === "cancelled" ? "cancelled" : "completed",
      +                stopReason: effectiveStopReason ?? null,
                     },
                   });
                 }
      
      diff --git a/apps/server/src/provider/Layers/GrokAdapter.ts b/apps/server/src/provider/Layers/GrokAdapter.ts
      --- a/apps/server/src/provider/Layers/GrokAdapter.ts
      +++ b/apps/server/src/provider/Layers/GrokAdapter.ts
      @@ -111,6 +111,12 @@
          * >0 means a turn is actively running, so a new sendTurn is a steer that
          * continues it, and only the last remaining prompt settles the turn. */
         promptsInFlight: number;
      +  /** Monotonically increasing counter identifying the most recent prompt. */
      +  promptSequence: number;
      +  /** Stop reason from the highest-sequence prompt that has completed so far
      +   * within the current turn. Used to emit `turn.completed` with the steering
      +   * prompt's result even when a superseded prompt resolves last. */
      +  latestTurnStopReason: { seq: number; stopReason: string | undefined } | undefined;
         currentModelId: string | undefined;
         stopped: boolean;
       }
      @@ -560,6 +566,8 @@
                   lastPlanFingerprint: undefined,
                   activeTurnId: undefined,
                   promptsInFlight: 0,
      +            promptSequence: 0,
      +            latestTurnStopReason: undefined,
                   currentModelId: boundModelId,
                   stopped: false,
                 };
      @@ -678,6 +686,10 @@
                   // resolving from here on does not settle the turn; decremented on
                   // preparation failure here, and after the prompt below otherwise.
                   ctx.promptsInFlight += 1;
      +            const myPromptSeq = ++ctx.promptSequence;
      +            if (steeringTurnId === undefined) {
      +              ctx.latestTurnStopReason = undefined;
      +            }
       
                   return yield* Effect.gen(function* () {
                     const turnModelSelection =
      @@ -774,6 +786,7 @@
                       displayModel,
                       promptParts,
                       turnId,
      +                myPromptSeq,
                     };
                   }).pipe(
                     Effect.tapCause(() =>
      @@ -829,10 +842,22 @@
                       ...(prepared.displayModel ? { model: prepared.displayModel } : {}),
                     };
       
      +              // Record result from the highest-sequence (most recent) prompt so
      +              // the turn.completed event always reflects the steering prompt's
      +              // outcome, not a superseded prompt that resolved later.
      +              if (prepared.myPromptSeq >= (ctx.latestTurnStopReason?.seq ?? 0)) {
      +                ctx.latestTurnStopReason = {
      +                  seq: prepared.myPromptSeq,
      +                  stopReason: result.stopReason,
      +                };
      +              }
      +
                     // Only the last remaining prompt settles the turn — a steer-
                     // superseded prompt resolving (usually cancelled) while another
                     // is in flight or pending must leave the merged turn running.
                     if (ctx.promptsInFlight === 1) {
      +                const effectiveStopReason =
      +                  ctx.latestTurnStopReason?.stopReason ?? result.stopReason;
                       yield* offerRuntimeEvent({
                         type: "turn.completed",
                         ...(yield* makeEventStamp()),
      @@ -840,8 +865,8 @@
                         threadId: input.threadId,
                         turnId: prepared.turnId,
                         payload: {
      -                    state: result.stopReason === "cancelled" ? "cancelled" : "completed",
      -                    stopReason: result.stopReason ?? null,
      +                    state: effectiveStopReason === "cancelled" ? "cancelled" : "completed",
      +                    stopReason: effectiveStopReason ?? null,
                         },
                       });
                     }
      You can send follow-ups to the cloud agent here. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 3b80ae3ebb86ab329a8c6c3c52f5d318919ac4ee. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. @@ -810,0 +835,21 @@
      835+ if (ctx.promptsInFlight === 1) {
      836+ yield* offerRuntimeEvent({
      837+ type: "turn.completed",
      838+ ...(yield* makeEventStamp()),
      839+ provider: PROVIDER,
      840+ threadId: input.threadId,
      841+ turnId: prepared.turnId,
      842+ payload: {
      843+ state: result.stopReason === "cancelled" ? "cancelled" : "completed",
      844+ stopReason: result.stopReason ?? null,
      845+ },
      846+ });
      847+ }
      848+
      849+ return {
      850+ threadId: input.threadId,
      851+ turnId: prepared.turnId,
      852+ resumeCursor: ctx.session.resumeCursor,
      853+ };
      854+ }),
      855+ );

      🟠 High Layers/GrokAdapter.ts:855

      The promptsInFlight decrement in Effect.ensuring (lines 856-864) runs outside the thread lock, but the turn completion check at line 835 and steering detection at line 675 both occur inside the lock. This creates a race where a second sendTurn can acquire the preparation lock after Prompt A completes (but before its Effect.ensuring runs), see promptsInFlight > 0, treat it as steering, and increment to 2. When A's Effect.ensuring then decrements to 1, Prompt B will emit a second turn.completed event for the same turnId, violating the invariant that only the last prompt settles the turn.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/provider/Layers/GrokAdapter.ts around line 855:
      
      The `promptsInFlight` decrement in `Effect.ensuring` (lines 856-864) runs outside the thread lock, but the turn completion check at line 835 and steering detection at line 675 both occur inside the lock. This creates a race where a second `sendTurn` can acquire the preparation lock after Prompt A completes (but before its `Effect.ensuring` runs), see `promptsInFlight > 0`, treat it as steering, and increment to 2. When A's `Effect.ensuring` then decrements to 1, Prompt B will emit a second `turn.completed` event for the same `turnId`, violating the invariant that only the last prompt settles the turn.
      
      Evidence trail:
      apps/server/src/provider/Layers/GrokAdapter.ts lines 239-240 (withThreadLock = semaphore.withPermit), lines 666-786 (sendTurn preparation with steering at line 675 and increment at line 680, inside lock), lines 799-855 (completion logic with turn.completed check at line 835, inside lock), lines 856-864 (promptsInFlight decrement in Effect.ensuring, OUTSIDE lock), pnpm-workspace.yaml line 19 (effect@4.0.0-beta.78)
    9. juliusmarminge merged this57f6bf7

    10. juliusmarminge closed this

Sign in to join this conversation.