feat(sidebar): reveal nested subagent threads #3861
ClosedPixPMusic(GitHub profile, opens in a new tab)wants to merge 10 commits into
t3code/codex-turn-mapping fromrefs/pull/3861/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/client-runtime/src/state/threadRelationships.ts line 192Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6,0 +56,21 @@56+}57+58+/**59+ * Returns every subagent ancestor needed to reveal `threadKey` in a collapsed60+ * tree. Scoped keys prevent same-named threads in different environments from61+ * being joined. Malformed cycles stop at the first repeated node.62+ */63+export function getSubagentThreadAncestorKeys<Thread extends SubagentThreadTreeInput>(64+ threads: readonly Thread[],65+ threadKey: string | null,66+): ReadonlySet<string> {67+ if (threadKey === null) return new Set();68+69+ const threadByKey = new Map(70+ threads.map((thread) => [subagentThreadKey(thread), thread] as const),71+ );72+ const ancestors = new Set<string>();73+ const visited = new Set<string>([threadKey]);74+ let current = threadByKey.get(threadKey);75+76+ while (current !== undefined) {apps/web/src/components/Sidebar.tsx line 3327OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3171,3 +3324,4 @@31713324 const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<31723325 ReadonlySet<string>31733326 >(() => new Set());3327+ const [expandedSubagentThreadKeys, setExpandedSubagentThreadKeys] = useState<ReadonlySet<string>>(apps/web/src/components/Sidebar.tsx line 3435OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3260,3 +3416,20 @@32603416 ),32613417 [sidebarThreads],32623418 );3419+ useEffect(() => {3420+ if (!sidebarShowSubagentThreads || routeThreadKey === null) {3421+ return;3422+ }3423+ const ancestorKeys = getSidebarSubagentAncestorKeys(sidebarThreads, routeThreadKey);3424+ if (ancestorKeys.size === 0) {3425+ return;3426+ }3427+ setExpandedSubagentThreadKeys((current) => {3428+ const next = new Set(current);3429+ for (const key of ancestorKeys) {3430+ next.add(key);3431+ }3432+ return next.size === current.size ? current : next;3433+ });3434+ }, [routeThreadKey, sidebarShowSubagentThreads, sidebarThreads]);3435+ const toggleSubagentBranch = useCallback((threadKey: string) => {
- apps/web/src/components/Sidebar.tsx line 1404OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1299,12 +1392,13 @@12991392 },13001393 });13011394 };1302- const visibleProjectThreads = sortThreads(1395+ const sortedProjectThreads = sortThreads(13031396 projectThreads.filter((thread) => thread.archivedAt === null),13041397 threadSortOrder,13051398 );1399+ const visibleRootProjectThreads = getSidebarSubagentTreeRoots(sortedProjectThreads);13061400 const projectStatus = resolveProjectStatusIndicator(1307- visibleProjectThreads.map((thread) => resolveProjectThreadStatus(thread)),1401+ sortedProjectThreads.map((thread) => resolveProjectThreadStatus(thread)),13081402 );13091403 return {1310- orderedProjectThreadKeys: visibleProjectThreads.map((thread) =>1404+ orderedProjectThreadKeys: sortedProjectThreads.map((thread) =>apps/web/src/components/Sidebar.tsx line 3444OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3262,0 +3424,21 @@3424+ if (ancestorKeys.size === 0) {3425+ return;3426+ }3427+ setExpandedSubagentThreadKeys((current) => {3428+ const next = new Set(current);3429+ for (const key of ancestorKeys) {3430+ next.add(key);3431+ }3432+ return next.size === current.size ? current : next;3433+ });3434+ }, [routeThreadKey, sidebarShowSubagentThreads, sidebarThreads]);3435+ const toggleSubagentBranch = useCallback((threadKey: string) => {3436+ setExpandedSubagentThreadKeys((current) => {3437+ const next = new Set(current);3438+ if (next.has(threadKey)) {3439+ next.delete(threadKey);3440+ } else {3441+ next.add(threadKey);3442+ }3443+ return next;3444+ });
- @@ -3475,7 +3678,16 @@3678+ const hasOverflowingThreads = rootProjectThreads.length > sidebarThreadPreviewCount;3679+ const previewRoots =34753680 isThreadListExpanded || !hasOverflowingThreads3476- ? projectThreads3477- : projectThreads.slice(0, sidebarThreadPreviewCount);3478- const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;3479- return renderedThreads.map((thread) =>3480- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),3681+ ? rootProjectThreads3682+ : rootProjectThreads.slice(0, sidebarThreadPreviewCount);3683+ const visibleRootThreadKeys = new Set(3684+ [...previewRoots, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map(3685+ sidebarThreadKey,3686+ ),34813687 );3688+ const renderedRoots = pinnedCollapsedThread3689+ ? [pinnedCollapsedThread]3690+ : rootProjectThreads.filter((thread) =>3691+ visibleRootThreadKeys.has(sidebarThreadKey(thread)),3692+ );3693+ return flattenSidebarSubagentTree({apps/web/src/components/Sidebar.tsx lines 3462 to 3469Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3171,3 +3326,7 @@31713326 const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<31723327 ReadonlySet<string>31733328 >(() => new Set());3329+ const expandedSubagentThreadKeys = useMemo<ReadonlySet<string>>(3330+ () => new Set(persistedExpandedSubagentThreadKeys),3331+ [persistedExpandedSubagentThreadKeys],3332+ );
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/hooks/useThreadActions.ts line 327Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -241,9 +300,12 @@241300 return deleteResult;242301 }243302 refreshArchivedThreadsForEnvironment(threadRef.environmentId);244- clearComposerDraftForThread(threadRef);245- clearProjectDraftThreadById(246- scopeProjectRef(threadRef.environmentId, thread.projectId),247- threadRef,248- );249- clearTerminalUiState(threadRef);303+ for (const deletedThread of subtree) {304+ const deletedThreadRef = scopeThreadRef(deletedThread.environmentId, deletedThread.id);305+ clearComposerDraftForThread(deletedThreadRef);306+ clearProjectDraftThreadById(307+ scopeProjectRef(deletedThread.environmentId, deletedThread.projectId),308+ deletedThreadRef,309+ );310+ clearTerminalUiState(deletedThreadRef);311+ }apps/web/src/hooks/useThreadActions.ts line 133Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -130,4 +151,3 @@130151 refreshArchivedThreadsForEnvironment(threadRef.environmentId);131152 return archiveResult;132153 },133- [archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],apps/web/src/hooks/useThreadActions.ts line 133Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -130,4 +151,3 @@130151 refreshArchivedThreadsForEnvironment(threadRef.environmentId);131152 return archiveResult;132153 },133- [archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],
- apps/web/src/hooks/useThreadActions.ts line 139Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -93,15 +123,6 @@93123 const resolved = resolveThreadTarget(target);94124 if (!resolved) return AsyncResult.success(undefined);95125 const { thread, threadRef } = resolved;96- if (thread.runtime?.status === "running" && thread.runtime.activeRunId != null) {97- return AsyncResult.failure(98- Cause.fail(99- new ThreadArchiveBlockedError({100- environmentId: threadRef.environmentId,101- threadId: threadRef.threadId,102- }),103- ),104- );105- }106126107127 const currentRouteThreadRef = getCurrentRouteThreadRef();128+ const subtree = getThreadSubtree(threadRef, thread);@@ -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 || !hasOverflowingThreads3476- ? projectThreads3477- : projectThreads.slice(0, sidebarThreadPreviewCount);3478- const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;3479- return renderedThreads.map((thread) =>3480- scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),3802+ ? rootProjectThreads3803+ : rootProjectThreads.slice(0, sidebarThreadPreviewCount);3804+ const visibleRootThreadKeys = new Set(apps/web/src/hooks/useThreadActions.ts line 42OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -26,14 +31,12 @@2631 import { stackedThreadToast, toastManager } from "../components/ui/toast";2732 import { useClientSettings } from "./useSettings";2833 import { useAtomCommand } from "../state/use-atom-command";293430-export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(31- "ThreadArchiveBlockedError",32- {33- environmentId: EnvironmentId,34- threadId: ThreadId,35- },36-) {37- override get message(): string {38- return "Cannot archive a running thread.";35+function readEnvironmentThreads(environmentId: EnvironmentId) {36+ const snapshot = appAtomRegistry.get(environmentSnapshotAtom(environmentId));37+ if (snapshot !== null) {38+ return [...snapshot.threads, ...snapshot.archivedThreads].map((thread) =>39+ presentThreadShell(environmentId, thread),40+ );3941 }42+ return readEnvironmentThreadRefs(environmentId).flatMap((ref) => {
- @@ -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 archived46+ // shells already loaded — otherwise subtree reads undercount descendants47+ // 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];
- @@ -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);
- apps/web/src/hooks/useThreadActions.ts line 59OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -39 +39,21 @@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 archived46+ // shells already loaded — otherwise subtree reads undercount descendants47+ // 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];57+}58+59+/**apps/web/src/hooks/useThreadActions.ts line 177OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -111,7 +157,21 @@111157 const archiveResult = await archiveThreadMutation({112158 environmentId: threadRef.environmentId,113159 input: { threadId: threadRef.threadId },114160 });115161 if (archiveResult._tag === "Failure") {116162 return archiveResult;117163 }164+ // Archiving a root archives the subagent threads it recursively owns.165+ // Each member gets its own command; attempt the full subtree before166+ // reporting the first failure so one refusal cannot strand the rest.167+ let descendantFailure: Awaited<ReturnType<typeof archiveThreadMutation>> | null = null;168+ for (const entry of subtree.slice(1).filter((entry) => entry.archivedAt === null)) {169+ const result = await archiveThreadMutation({170+ environmentId: threadRef.environmentId,171+ input: { threadId: entry.id },172+ });173+ if (result._tag === "Failure") {174+ descendantFailure ??= result;175+ }176+ }177+ if (descendantFailure !== null) {
- apps/web/src/hooks/useThreadActions.ts line 70OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -39,0 +50,21 @@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];57+}58+59+/**60+ * Client-side approximation of "archived together": the archive cascade61+ * issues one command per subtree member, so `archivedAt` stamps differ by62+ * command latency rather than matching exactly.63+ */64+const ARCHIVED_TOGETHER_TOLERANCE_MS = 60_000;65+66+function wasArchivedWith(rootArchivedAt: string | null, archivedAt: string | null): boolean {67+ if (rootArchivedAt === null || archivedAt === null) return false;68+ return (69+ Math.abs(Date.parse(archivedAt) - Date.parse(rootArchivedAt)) <= ARCHIVED_TOGETHER_TOLERANCE_MS70+ );apps/web/src/hooks/useThreadActions.ts line 180OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -114,4 +160,21 @@114160 });115161 if (archiveResult._tag === "Failure") {116162 return archiveResult;117163 }164+ // Archiving a root archives the subagent threads it recursively owns.165+ // Each member gets its own command; attempt the full subtree before166+ // reporting the first failure so one refusal cannot strand the rest.167+ let descendantFailure: Awaited<ReturnType<typeof archiveThreadMutation>> | null = null;168+ for (const entry of subtree.slice(1).filter((entry) => entry.archivedAt === null)) {169+ const result = await archiveThreadMutation({170+ environmentId: threadRef.environmentId,171+ input: { threadId: entry.id },172+ });173+ if (result._tag === "Failure") {174+ descendantFailure ??= result;175+ }176+ }177+ if (descendantFailure !== null) {178+ refreshArchivedThreadsForEnvironment(threadRef.environmentId);179+ return descendantFailure;180+ }
- @@ -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+ ]);
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
6ccd4b0a-5964-4ab9-bde0-6b9f0cdaa263You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
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