Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(sidebar): reveal nested subagent threads #3861

ClosedPixPMusic(GitHub profile, opens in a new tab)wants to merge 10 commits intot3code/codex-turn-mapping fromrefs/pull/3861/headopened View on GitHub

Summary

  • add an opt-in sidebar setting that nests subagent threads beneath their parent
  • persist per-parent expansion state and keep orphaned or cyclic relationships safe
  • share the thread-tree projection through client runtime for reuse across clients

Validation

  • vp check
  • vp run typecheck
  • vp test apps/web/src/components/Sidebar.logic.test.ts packages/client-runtime/src/state/threadRelationships.test.ts packages/contracts/src/settings.test.ts apps/desktop/src/settings/DesktopClientSettings.test.ts

Stacked on #2829.


Note

High Risk Large orchestration changes to thread lifecycle, event commit guards, and checkpoint deletion affect core concurrency and data cleanup; incorrect guards could drop events or over-delete refs.

Overview Orchestration v2 now treats archive, unarchive, and delete as owned-subagent subtree operations: the orchestrator walks ownedSubagentDescendants, applies lifecycle mutations with coordinated timestamps, cancels in-flight runs/attempts/nodes/subagents/provider turns, detaches sessions, and enqueues terminal, attachment, and checkpoint.cleanup effects on delete. Commands run under a root-graph lock (lineage rootThreadId) alongside per-thread locks; archive/delete cancel process-bound effects across all affected thread IDs. Startup and live thread.created repair (planOwnedSubagentLifecycleRepairs) fixes parent/child lifecycle mismatches. Unarchive blocks when the parent is archived/deleted; archiving a subagent cancels the parent’s active subagent task artifacts.

EventSink writeIfRunCurrent is stricter: target threads must be active (not archived/deleted), expectedStatus can be an array, and allowSupersededAttemptTerminalArtifacts admits late terminal provider-turn / interrupt-result writes from superseded attempts. Routed events into archived child threads are rejected. Provider turn start and run execution detach sessions and gate writes when threads go inactive mid-flight.

New CheckpointCleanupService and deleteScopeRefs (through latest run/checkpoint ordinal) remove checkpoint refs when threads are deleted. getThreadLifecycleRecords keeps deleted thread headers for repair.

Web sidebar logic adds nested subagent tree helpers (flatten, roots, ancestors, expansion merge for deep links, range selection order) wired through client-runtime thread-relationships. Desktop settings tests add default sidebarShowSubagentThreads: false.

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

Note

Reveal nested subagent threads in the sidebar with expand/collapse controls

  • Adds a collapsible nested subagent thread tree to the sidebar, with per-row expand/collapse chevrons, depth indentation, active descendant counts, and a 'Show nested subagents' toggle in the sort menu.
  • Persists expanded branch keys to uiStateStore and auto-expands ancestors of the currently active thread on first paint.
  • Archive, unarchive, and delete operations now cascade over the entire owned-subagent subtree with confirmation dialogs that show descendant and active-work counts; delete also stops sessions and clears terminal/UI state for every subtree member.
  • Introduces CheckpointCleanupServiceV2 that deletes checkpoint refs per scope up to the latest known ordinal, wired into the effect worker as a new checkpoint.cleanup effect type.
  • The orchestrator serializes archive/unarchive/delete dispatch per root thread via a graph-level lock, rejects create/fork when the parent is archived or deleted, and repairs inconsistent owned-subagent lifecycle states on startup.
  • EventSinkV2.write now rejects writes targeting archived/deleted threads and accepts multiple expected run statuses; provider adapter events are only persisted when the root run is current.
  • Risk: archiving no longer hard-blocks on running status at the useThreadActions layer; cascade deletes affect all owned subagent descendants, not just the selected thread.
Macroscope summarized c050552.

Archiving, unarchiving, or deleting a thread now applies to the subagent subtree it recursively owns, enforced server-side in this PR: the orchestrator walks the owned subtree (OwnedSubagentTree), applies the lifecycle transition to every member with a single timestamp, and cancels active runs and pending attempts. Half-applied cascades are repaired on startup (OwnedSubagentLifecycleRepair) and checkpoints orphaned by deleted threads are cleaned up (CheckpointCleanupService). The web sidebar layers on top: subtree-aware confirmation copy and counts, recovery-root badges, navigation, and client-side draft/terminal cleanup. No mobile code in this PR — the mobile UI for the same behavior follows in #3871.

    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: 6ccd4b0a-5964-4ab9-bde0-6b9f0cdaa263

      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

      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. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      3 blocking correctness issues 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).
    4. @@ -3475,7 +3678,16 @@
      3678+ const hasOverflowingThreads = rootProjectThreads.length > sidebarThreadPreviewCount;
      3679+ const previewRoots =
      34753680 isThreadListExpanded || !hasOverflowingThreads
      3476- ? projectThreads
      3477- : projectThreads.slice(0, sidebarThreadPreviewCount);
      3478- const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
      3479- return renderedThreads.map((thread) =>
      3480- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
      3681+ ? rootProjectThreads
      3682+ : rootProjectThreads.slice(0, sidebarThreadPreviewCount);
      3683+ const visibleRootThreadKeys = new Set(
      3684+ [...previewRoots, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map(
      3685+ sidebarThreadKey,
      3686+ ),
      34813687 );
      3688+ const renderedRoots = pinnedCollapsedThread
      3689+ ? [pinnedCollapsedThread]
      3690+ : rootProjectThreads.filter((thread) =>
      3691+ visibleRootThreadKeys.has(sidebarThreadKey(thread)),
      3692+ );
      3693+ return flattenSidebarSubagentTree({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/Sidebar.tsx:3693

      The sidebar thread preview limit (sidebarThreadPreviewCount) is applied to root threads only, not to the final flattened row list, so a project can render far more visible rows than the configured limit. When subagent branches are expanded, flattenSidebarSubagentTree expands each previewed root into all of its visible descendants, so a project configured to show 3 visible threads can render 3 roots plus every expanded descendant. This breaks the "Visible threads" setting and skews downstream features like jump-hint numbering and sidebar prewarming, which now treat those extra rows as visible. The preview slicing should be applied after flattening (or the flatten result should be truncated to sidebarThreadPreviewCount) so the total visible row count respects the configured limit.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/Sidebar.tsx around line 3693:
      
      The sidebar thread preview limit (`sidebarThreadPreviewCount`) is applied to root threads only, not to the final flattened row list, so a project can render far more visible rows than the configured limit. When subagent branches are expanded, `flattenSidebarSubagentTree` expands each previewed root into all of its visible descendants, so a project configured to show 3 visible threads can render 3 roots plus every expanded descendant. This breaks the "Visible threads" setting and skews downstream features like jump-hint numbering and sidebar prewarming, which now treat those extra rows as visible. The preview slicing should be applied after flattening (or the flatten result should be truncated to `sidebarThreadPreviewCount`) so the total visible row count respects the configured limit.

      This is intentional: the "Visible threads" setting controls how many conversations (root threads) are previewed per project, and subagent children only render when the user explicitly expands a branch — so the extra rows are opt-in rather than a regression of the limit. Truncating the flattened list instead would cut a tree mid-branch, leaving a parent marked expanded with some of its children silently missing. Prewarming and jump hints are independently capped, so expanded rows don't create unbounded work downstream.

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

    5. Note on the failing Macroscope - Effect Service Conventions check: its own agent log concludes this PR is frontend React code and pure helpers with no Effect-service changes to flag, but the run then fails on an output-format conflict inside the check-run agent (JSON schema vs a literal "All clear" reply — the activity log cuts off mid-sentence). The failure is a check-tooling issue on this repo's .macroscope/check-run-agents/effect-service-conventions.md, not a convention violation in this diff. The repository Check job and all other checks are green.

    6. @@ -3468,13 +3791,14 @@
      3791+ }
      3792+ return current;
      3793+ })();
      34683794 const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null;
      34693795 if (!shouldShowThreadPanel) {
      34703796 return [];
      34713797 }
      34723798 const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey);
      3473- const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount;
      3474- const previewThreads =
      3799+ const hasOverflowingThreads = rootProjectThreads.length > sidebarThreadPreviewCount;
      3800+ const previewRoots =
      34753801 isThreadListExpanded || !hasOverflowingThreads
      3476- ? projectThreads
      3477- : projectThreads.slice(0, sidebarThreadPreviewCount);
      3478- const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
      3479- return renderedThreads.map((thread) =>
      3480- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
      3802+ ? rootProjectThreads
      3803+ : rootProjectThreads.slice(0, sidebarThreadPreviewCount);
      3804+ const visibleRootThreadKeys = new Set(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/Sidebar.tsx:3804

      When the current route points at a nested subagent thread inside a collapsed project, pinnedCollapsedThread walks up to the topmost ancestor and only that root key is added to visibleSidebarThreadKeys. The active child thread's own key is missing from the list, so resolveAdjacentThreadId cannot find currentThreadId and thread.previous / thread.next return null from that route. Consider including the active thread key itself (and its ancestor chain) in the visible set when a pinned-collapsed thread is used.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/Sidebar.tsx around line 3804:
      
      When the current route points at a nested subagent thread inside a collapsed project, `pinnedCollapsedThread` walks up to the topmost ancestor and only that root key is added to `visibleSidebarThreadKeys`. The active child thread's own key is missing from the list, so `resolveAdjacentThreadId` cannot find `currentThreadId` and `thread.previous` / `thread.next` return `null` from that route. Consider including the active thread key itself (and its ancestor chain) in the visible set when a pinned-collapsed thread is used.
    7. @@ -37,3 +38,19 @@
      37- override get message(): string {
      38- return "Cannot archive a running thread.";
      38+function readEnvironmentThreads(environmentId: EnvironmentId) {
      39+ const snapshot = appAtomRegistry.get(environmentSnapshotAtom(environmentId));
      40+ if (snapshot !== null) {
      41+ return [...snapshot.threads, ...snapshot.archivedThreads].map((thread) =>
      42+ presentThreadShell(environmentId, thread),
      43+ );
      3944 }
      45+ // The thread refs only track active threads, so merge in any archived
      46+ // shells already loaded — otherwise subtree reads undercount descendants
      47+ // whose parents are archived and skip recursive-action confirmations.
      48+ const active = readEnvironmentThreadRefs(environmentId).flatMap((ref) => {
      49+ const thread = readThreadShell(ref);
      50+ return thread === null ? [] : [thread];
      51+ });
      52+ const activeIds = new Set(active.map((thread) => thread.id));
      53+ const archived = readArchivedThreadShells(environmentId)
      54+ .filter((thread) => !activeIds.has(thread.id))
      55+ .map((thread) => presentThreadShell(environmentId, thread));
      56+ return [...active, ...archived];

      Stale archived cache skews subtree

      Medium Severity

      When the environment shell snapshot is unavailable, readEnvironmentThreads merges archived threads only from readArchivedThreadShells, which returns an empty list until that archived snapshot atom has already succeeded. Subtree reads for delete/archive confirmations and the new per-subtree stopThreadSession / closeTerminal loops can then omit archived owned subagents, so dialogs undercount and client teardown skips them even if the server still removes the tree.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 83f95f5de689b8cfe030783401b5381f221ddf36. Configure [here](https://www.cursor.com/dashboard/bugbot).
    8. @@ -1023,5 +1149,7 @@
      10231149 </SidebarMenuSubItem>
      10241150 ) : null}
      10251151 {shouldShowThreadPanel &&
      1026- renderedThreads.map((thread) => {
      1152+ renderedThreads.map((row) => {
      1153+ const { thread } = row;
      10271154 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
      1155+ const subagentDescendants = getOwnedSubagentDescendants(unarchivedProjectThreads, thread);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/Sidebar.tsx:1155

      getOwnedSubagentDescendants is called with unarchivedProjectThreads, which is scoped to the current sidebar project. Subagent lineage is environment-wide, so a parent thread can own descendants in other projects. This causes subagentDescendantCount to undercount the subtree, but SidebarThreadRow still calls attemptArchiveThread(threadRef, { confirmed: true }) with that count. The Confirm +N UI therefore discloses fewer threads than the archive operation actually affects, so the user can archive more descendant threads than the confirmation message showed. Consider passing the full set of environment-wide thread shells to getOwnedSubagentDescendants so the count matches the archive scope.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/Sidebar.tsx around line 1155:
      
      `getOwnedSubagentDescendants` is called with `unarchivedProjectThreads`, which is scoped to the current sidebar project. Subagent lineage is environment-wide, so a parent thread can own descendants in other projects. This causes `subagentDescendantCount` to undercount the subtree, but `SidebarThreadRow` still calls `attemptArchiveThread(threadRef, { confirmed: true })` with that count. The `Confirm +N` UI therefore discloses fewer threads than the archive operation actually affects, so the user can archive more descendant threads than the confirmation message showed. Consider passing the full set of environment-wide thread shells to `getOwnedSubagentDescendants` so the count matches the archive scope.
    9. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      There are 2 total unresolved issues (including 1 from previous review).

      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 c050552041cc3c9158463cf8edbd56d705de7361. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -781,0 +859,21 @@
      859+ command: Extract<
      860+ OrchestrationV2Command,
      861+ { readonly type: "thread.archive" | "thread.unarchive" | "thread.delete" }
      862+ >,
      863+ rootProjection: OrchestrationV2ThreadProjection,
      864+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
      865+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
      866+ ) {
      867+ const shell = yield* projectionStore.getShellSnapshot().pipe(
      868+ Effect.mapError(
      869+ (cause) =>
      870+ new OrchestratorProjectionError({
      871+ threadId: command.threadId,
      872+ cause,
      873+ }),
      874+ ),
      875+ );
      876+ const descendants = ownedSubagentDescendants(command.threadId, [
      877+ ...shell.threads,
      878+ ...shell.archivedThreads,
      879+ ]);

      Root cascade skips orphan subagents

      Medium Severity

      dispatchOwnedThreadLifecycle builds the owned subtree only from active and archived shell threads via ownedSubagentDescendants. That BFS starts at the command thread and follows subagent parent links present in that list. A descendant whose direct parent was already deleted is not linked from the root, so it is omitted from archive, delete, and related cleanup even when its lineage.rootThreadId still points at the root being mutated.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c050552041cc3c9158463cf8edbd56d705de7361. Configure [here](https://www.cursor.com/dashboard/bugbot).
    10. the sidebar gets flooded fast with this. tried it and it's just not UX with the rate that the current harnesses likes to create subagents

    11. juliusmarminge closed this

    12. the sidebar gets flooded fast with this. tried it and it's just not UX with the rate that the current harnesses likes to create subagents

      By default, I agree

      This is why I gated it behind a toggle, and planned to add a feature to also only show active threads

Sign in to join this conversation.