From d8d4d31d67b74cd71b80d3d15dec07f438d55715 Mon Sep 17 00:00:00 2001 From: Donald Silveira <9506146+donnes@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:24:37 -0300 Subject: [PATCH 1/3] feat: show delegated threads beneath their parent - Persist parent thread links and include them in thread projections - Nest delegated threads in mobile lists and block nested delegation --- apps/mobile/src/components/AppSymbol.tsx | 8 + apps/mobile/src/features/home/HomeScreen.tsx | 12 + .../threads/ThreadNavigationSidebar.tsx | 15 ++ .../features/threads/thread-list-v2-items.tsx | 120 +++++++++- .../src/features/threads/threadListV2.test.ts | 65 ++++++ .../src/features/threads/threadListV2.ts | 125 ++++++++--- .../orchestrationEngine.integration.test.ts | 2 + .../src/delegation/DelegationService.test.ts | 36 ++- .../src/delegation/DelegationService.ts | 35 +-- .../Layers/ProjectionPipeline.ts | 1 + .../Layers/ProjectionSnapshotQuery.test.ts | 2 + .../Layers/ProjectionSnapshotQuery.ts | 10 + apps/server/src/orchestration/decider.ts | 10 + .../src/orchestration/projector.test.ts | 1 + apps/server/src/orchestration/projector.ts | 1 + .../persistence/Layers/ProjectionThreads.ts | 4 + apps/server/src/persistence/Migrations.ts | 2 + ...56_ProjectionThreadsParentThreadId.test.ts | 59 +++++ .../056_ProjectionThreadsParentThreadId.ts | 34 +++ .../persistence/Services/ProjectionThreads.ts | 1 + apps/web/src/components/Sidebar.tsx | 211 +++++++++++++++++- docs/user/thread-sidebar.md | 8 +- packages/client-runtime/package.json | 4 + .../src/state/threadNesting.test.ts | 64 ++++++ .../client-runtime/src/state/threadNesting.ts | 53 +++++ .../client-runtime/src/state/threadReducer.ts | 1 + packages/contracts/src/orchestration.ts | 8 + 27 files changed, 807 insertions(+), 85 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.test.ts create mode 100644 apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.ts create mode 100644 packages/client-runtime/src/state/threadNesting.test.ts create mode 100644 packages/client-runtime/src/state/threadNesting.ts diff --git a/apps/mobile/src/components/AppSymbol.tsx b/apps/mobile/src/components/AppSymbol.tsx index 72c5f621bc800..9d28e06d5310e 100644 --- a/apps/mobile/src/components/AppSymbol.tsx +++ b/apps/mobile/src/components/AppSymbol.tsx @@ -36,6 +36,7 @@ import IconChevronUp from "@tabler/icons-react-native/IconChevronUp"; import IconCircle from "@tabler/icons-react-native/IconCircle"; import IconCircleFilled from "@tabler/icons-react-native/IconCircleFilled"; import IconCircleCheck from "@tabler/icons-react-native/IconCircleCheck"; +import IconCircleDashed from "@tabler/icons-react-native/IconCircleDashed"; import IconCircleXFilled from "@tabler/icons-react-native/IconCircleXFilled"; import IconTicket from "@tabler/icons-react-native/IconTicket"; import IconClock from "@tabler/icons-react-native/IconClock"; @@ -74,6 +75,7 @@ import IconMicrophone from "@tabler/icons-react-native/IconMicrophone"; import IconLink from "@tabler/icons-react-native/IconLink"; import IconMenu2 from "@tabler/icons-react-native/IconMenu2"; import IconMessage from "@tabler/icons-react-native/IconMessage"; +import IconMessageQuestion from "@tabler/icons-react-native/IconMessageQuestion"; import IconMinus from "@tabler/icons-react-native/IconMinus"; import IconMoon from "@tabler/icons-react-native/IconMoon"; import IconNetwork from "@tabler/icons-react-native/IconNetwork"; @@ -83,7 +85,9 @@ import IconPhoto from "@tabler/icons-react-native/IconPhoto"; import IconPin from "@tabler/icons-react-native/IconPin"; import IconPinnedOff from "@tabler/icons-react-native/IconPinnedOff"; import IconPlayerPlay from "@tabler/icons-react-native/IconPlayerPlay"; +import IconPlayerStop from "@tabler/icons-react-native/IconPlayerStop"; import IconPlayerStopFilled from "@tabler/icons-react-native/IconPlayerStopFilled"; +import IconShieldQuestion from "@tabler/icons-react-native/IconShieldQuestion"; import IconPlus from "@tabler/icons-react-native/IconPlus"; import IconQrcode from "@tabler/icons-react-native/IconQrcode"; import IconRefresh from "@tabler/icons-react-native/IconRefresh"; @@ -140,6 +144,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { checkmark: IconCheck, "checkmark.circle": IconCircleCheck, circle: IconCircle, + "circle.dashed": IconCircleDashed, "circle.fill": IconCircleFilled, clock: IconClock, timer: IconClock, @@ -159,6 +164,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "ellipsis.circle": IconDotsCircleHorizontal, "exclamationmark.triangle": IconAlertTriangle, "exclamationmark.circle": IconAlertCircle, + "exclamationmark.shield": IconShieldQuestion, eye: IconEye, folder: IconFolder, "folder.badge.plus": IconFolderPlus, @@ -206,10 +212,12 @@ const ANDROID_ICON_BY_SF_SYMBOL = { star: IconStar, "star.fill": IconStarFilled, "sun.max": IconSun, + "stop.circle": IconPlayerStop, "stop.fill": IconPlayerStopFilled, terminal: IconTerminal2, "text.alignleft": IconAlignLeft, "text.bubble": IconMessage, + "questionmark.bubble": IconMessageQuestion, "text.word.spacing": IconLetterSpacing, "textformat.size": IconTypography, "textformat.size.larger": IconTextIncrease, diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 08a8d8177b53b..47fc8daf013dd 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -44,6 +44,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks"; import { useQueuedThreadKeys } from "../../state/use-thread-outbox"; import { ThreadListV2PendingRow, + ThreadListV2ChildRow, ThreadListV2Row, ThreadListV2SettledShelfHeader, ThreadListV2ShowMoreRow, @@ -778,6 +779,17 @@ export function HomeScreen(props: HomeScreenProps) { /> ); } + if (item.type === "v2-child") { + return ( + + ); + } const thread = item.item.thread; return ( ); } + case "v2-child": + return ( + + ); case "v2-thread": { const thread = item.item.thread; const scopeKey = scopedProjectKey(thread.environmentId, thread.projectId); diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 10b01fef0ec73..96b6a49a2fc9f 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -23,7 +23,7 @@ import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } import { Alert, Pressable, useWindowDimensions, View } from "react-native"; import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable"; -import { SymbolView } from "../../components/AppSymbol"; +import { SymbolView, type AppSymbolName } from "../../components/AppSymbol"; import { AppText as Text } from "../../components/AppText"; import { ControlPillMenu } from "../../components/ControlPill"; import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol"; @@ -1232,3 +1232,121 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { ); }); + +// Same hues as the status labels; a settled child reads as a quiet check. +const CHILD_STATUS_SYMBOL: Record< + ThreadListV2Status, + { readonly name: AppSymbolName; readonly label: string; readonly tintClassName?: string } +> = { + approval: { + name: "exclamationmark.shield", + label: "Approval", + tintClassName: "accent-warning-foreground", + }, + input: { + name: "questionmark.bubble", + label: "Input", + tintClassName: "accent-adaptive-indigo-600-300", + }, + working: { + name: "circle.dashed", + label: "Working", + tintClassName: "accent-adaptive-sky-600-400", + }, + failed: { + name: "exclamationmark.circle", + label: "Failed", + tintClassName: "accent-danger-foreground", + }, + ready: { name: "checkmark.circle", label: "Done" }, +}; + +/** + * One-line row for a thread another thread delegated work to, drawn under + * its parent's card. Tap opens it; actions live on the thread screen. + */ +export const ThreadListV2ChildRow = memo(function ThreadListV2ChildRow(props: { + readonly thread: EnvironmentThreadShell; + readonly timeLabel: string; + readonly providerInstance: ThreadRowProviderInstance | null; + readonly pane?: "screen" | "sidebar"; + readonly selected?: boolean; + readonly showTrailingDivider?: boolean; + readonly onSelectThread: (thread: EnvironmentThreadShell) => void; +}) { + const { thread, onSelectThread } = props; + const theme = useUniwindTheme(); + const sidebarPane = props.pane === "sidebar"; + const selected = props.selected === true; + const rowAppearance = getThreadListV2RowAppearance(theme, sidebarPane, selected); + const status = resolveThreadListV2Status(thread); + const symbol = CHILD_STATUS_SYMBOL[status]; + const statusLabel = STATUS_LABEL_BY_STATUS[status]; + + return ( + onSelectThread(thread)} + style={rowAppearance.style} + > + + + {props.providerInstance ? ( + + ) : null} + + {thread.title} + + + {statusLabel?.label ?? props.timeLabel} + + + {!sidebarPane && THREAD_LIST_V2_ROW_DIVIDERS && props.showTrailingDivider === true ? ( + + ) : null} + + ); +}); diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 4bbcf2233a42c..fa22eecb303e3 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -192,6 +192,71 @@ describe("queued messages keep a settled thread active", () => { }); }); +describe("delegated threads", () => { + // Newest first in the active block, so the parent leads. + const parent = makeThread({ + id: ThreadId.make("parent"), + title: "Parent", + createdAt: "2026-06-01T02:00:00.000Z", + }); + const child = makeThread({ + id: ThreadId.make("child"), + title: "Child", + parentThreadId: ThreadId.make("parent"), + hasPendingUserInput: true, + }); + const settledParent = makeThread({ + id: ThreadId.make("settled-parent"), + title: "Settled parent", + settledOverride: "settled", + }); + const orphan = makeThread({ + id: ThreadId.make("orphan"), + title: "Orphan", + parentThreadId: ThreadId.make("settled-parent"), + createdAt: "2026-06-01T01:00:00.000Z", + }); + const threads = [parent, child, settledParent, orphan]; + + it("render under an active parent, and on their own under a settled one", () => { + const layout = buildThreadListV2Items({ + threads, + environmentId: null, + searchQuery: "", + now: NOW, + }); + const listItems = buildThreadListV2ListItems({ + items: layout.items, + pendingTasks: [], + settledCount: layout.settledCount, + settledShelfHeaderIndex: layout.settledShelfHeaderIndex, + }); + expect( + listItems.map((item) => + item.type === "v2-thread" + ? `thread:${item.item.thread.id}` + : item.type === "v2-child" + ? `child:${item.thread.id}` + : item.type, + ), + ).toEqual([ + "thread:parent", + "child:child", + "thread:orphan", + "v2-settled-shelf", + "thread:settled-parent", + ]); + }); + + it("never move on their own", () => { + expect( + getThreadListV2OrderedSection({ threads, section: "active", now: NOW }).map( + (thread) => thread.id, + ), + ).toEqual(["parent", "orphan"]); + }); +}); + describe("resolveThreadListV2SwipeActions", () => { it("offers settle and snooze for an active snoozable thread", () => { expect( diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index 8c4dd0b0f0975..beca4433b441e 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -10,6 +10,7 @@ import { import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { nestThreadsUnderParents } from "@t3tools/client-runtime/state/thread-nesting"; import { sortActiveThreadsByOrderKey, resolveSettledThreadTimestamp, @@ -166,7 +167,7 @@ export function getThreadListV2OrderedSection(input: { readonly snoozeEnvironmentIds?: ReadonlySet; readonly queuedThreadKeys?: ReadonlySet; }): EnvironmentThreadShell[] { - const threads = input.threads.filter((thread) => { + const cards = input.threads.filter((thread) => { if (thread.archivedAt !== null) return false; if ( (input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) && @@ -181,8 +182,15 @@ export function getThreadListV2OrderedSection(input: { ) { return false; } - return (thread.pinnedAt != null) === (input.section === "pinned"); + return true; }); + // A delegated thread rides under its parent's row and never moves on its own. + const { nestedKeys } = nestThreadsUnderParents(cards, cards); + const threads = cards.filter( + (thread) => + (thread.pinnedAt != null) === (input.section === "pinned") && + !nestedKeys.has(`${thread.environmentId}:${thread.id}`), + ); const ordered = input.section === "pinned" ? sortPinnedThreadsByOrderKey(threads) @@ -194,6 +202,8 @@ export function getThreadListV2OrderedSection(input: { return applyPendingThreadOrder(ordered, input.section, pending); } +const NO_CHILDREN: ReadonlyArray = []; + export interface ThreadListV2Item { readonly thread: EnvironmentThreadShell; readonly variant: "card" | "slim"; @@ -202,6 +212,8 @@ export interface ThreadListV2Item { /** Pinned-block row: renders the pin glyph and offers Unpin. */ readonly pinned: boolean; readonly isLast: boolean; + /** Threads this one delegated work to, rendered as compact rows beneath it. */ + readonly children: ReadonlyArray; } export interface ThreadListV2Layout { @@ -253,6 +265,17 @@ export interface ThreadListV2ThreadListItem { readonly canMoveDown: boolean; } +/** A delegated thread, drawn as a compact row under its parent's card. */ +export interface ThreadListV2ChildListItem { + readonly type: "v2-child"; + readonly key: string; + readonly thread: EnvironmentThreadShell; + /** Precomputed for the same reason as the thread row's. */ + readonly timeLabel: string; + /** Hairline under the last child of a parent; see the thread row's. */ + readonly showTrailingDivider: boolean; +} + export interface ThreadListV2PendingListItem { readonly type: "v2-pending"; readonly key: string; @@ -287,6 +310,7 @@ export interface ThreadListV2SettledShelfListItem { export type ThreadListV2ListItem = | ThreadListV2ThreadListItem + | ThreadListV2ChildListItem | ThreadListV2PendingListItem | ThreadListV2SnoozedShelfListItem | ThreadListV2SettledShelfListItem; @@ -298,6 +322,7 @@ export function isThreadListV2ListItem(value: { }): value is ThreadListV2ListItem { return ( value.type === "v2-thread" || + value.type === "v2-child" || value.type === "v2-pending" || value.type === "v2-snoozed-shelf" || value.type === "v2-settled-shelf" @@ -332,6 +357,14 @@ export function threadListV2ListItemsAreEqual( previous.canMoveUp === item.canMoveUp && previous.canMoveDown === item.canMoveDown ); + case "v2-child": + return ( + previous.type === "v2-child" && + previous.key === item.key && + previous.thread === item.thread && + previous.timeLabel === item.timeLabel && + previous.showTrailingDivider === item.showTrailingDivider + ); case "v2-pending": return ( previous.type === "v2-pending" && @@ -407,7 +440,9 @@ export function buildThreadListV2ListItems(input: { onto both shelf headers so the disabled state reaches recycled cells. */ readonly shelfPreferencesLoading?: boolean; }): ThreadListV2ListItem[] { - const threadItems = input.items.map((item): ThreadListV2ListItem => { + // Each thread row is followed by its delegated children, so the groups are + // sliced into sections by thread index and flattened afterwards. + const threadGroups = input.items.map((item): ThreadListV2ListItem[] => { const snoozeWakeLabelText = item.snoozed && item.thread.snoozedUntil != null && input.snoozeLabelNow !== undefined ? snoozeWakeLabel(item.thread.snoozedUntil, { now: input.snoozeLabelNow }) @@ -428,20 +463,30 @@ export function buildThreadListV2ListItems(input: { item.variant === "card" ? input.moveAvailability?.get(`${item.thread.environmentId}:${item.thread.id}`) : undefined; - return { - type: "v2-thread", - key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`, - item, - snoozeWakeLabelText, - timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined), - snoozePresetMinute, - showTrailingDivider: false, - hasQueuedMessages: - input.queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true, - canMoveUp: move?.canMoveUp === true, - canMoveDown: move?.canMoveDown === true, - }; + return [ + { + type: "v2-thread", + key: `v2-thread:${item.thread.environmentId}:${item.thread.id}`, + item, + snoozeWakeLabelText, + timeLabel: resolveThreadListV2ItemTimeLabel(item, snoozeWakeLabelText !== undefined), + snoozePresetMinute, + showTrailingDivider: false, + hasQueuedMessages: + input.queuedThreadKeys?.has(`${item.thread.environmentId}:${item.thread.id}`) === true, + canMoveUp: move?.canMoveUp === true, + canMoveDown: move?.canMoveDown === true, + }, + ...item.children.map((thread): ThreadListV2ListItem => ({ + type: "v2-child", + key: `v2-child:${thread.environmentId}:${thread.id}`, + thread, + timeLabel: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt), + showTrailingDivider: false, + })), + ]; }); + const threadItems = (start: number, end?: number) => threadGroups.slice(start, end).flat(); const pendingItems = input.pendingTasks.map((pendingTask, index): ThreadListV2ListItem => ({ type: "v2-pending", key: `v2-${pendingTask.key}`, @@ -453,9 +498,9 @@ export function buildThreadListV2ListItems(input: { const snoozedShelfHeaderIndex = input.snoozedShelfHeaderIndex ?? null; const settledCount = input.settledCount ?? 0; const settledShelfHeaderIndex = input.settledShelfHeaderIndex ?? null; - const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadItems.length; - const snoozedEnd = settledShelfHeaderIndex ?? threadItems.length; - const result: ThreadListV2ListItem[] = [...threadItems.slice(0, activeEnd), ...pendingItems]; + const activeEnd = snoozedShelfHeaderIndex ?? settledShelfHeaderIndex ?? threadGroups.length; + const snoozedEnd = settledShelfHeaderIndex ?? threadGroups.length; + const result: ThreadListV2ListItem[] = [...threadItems(0, activeEnd), ...pendingItems]; const shelfDisabled = input.shelfPreferencesLoading === true; if (snoozedShelfHeaderIndex !== null && snoozedCount > 0) { result.push({ @@ -465,7 +510,7 @@ export function buildThreadListV2ListItems(input: { expanded: input.snoozedShelfExpanded === true, disabled: shelfDisabled, }); - result.push(...threadItems.slice(snoozedShelfHeaderIndex, snoozedEnd)); + result.push(...threadItems(snoozedShelfHeaderIndex, snoozedEnd)); } if (settledShelfHeaderIndex !== null && settledCount > 0) { result.push({ @@ -475,12 +520,15 @@ export function buildThreadListV2ListItems(input: { expanded: input.settledShelfExpanded !== false, disabled: shelfDisabled, }); - result.push(...threadItems.slice(settledShelfHeaderIndex)); + result.push(...threadItems(settledShelfHeaderIndex)); } // Hairlines depend on the final neighbour, so they are stamped after the // splice: a recycled cell only re-renders when its divider actually flips. + // A card keeps no hairline above its children, so they read as one group. return result.map((entry, index) => { - if (entry.type !== "v2-thread" && entry.type !== "v2-pending") return entry; + if (entry.type !== "v2-thread" && entry.type !== "v2-child" && entry.type !== "v2-pending") { + return entry; + } const next = result[index + 1]; const showTrailingDivider = next?.type === "v2-thread" || (next?.type === "v2-pending" && !next.showPendingDivider); @@ -595,11 +643,28 @@ export function buildThreadListV2Items(input: { } } - const orderedActive = applyPendingThreadOrder(sortThreadsForListV2(active), "active", pending); - const orderedSnoozed = [...snoozed].sort( - (left, right) => - parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""), + // Delegated threads ride under a pinned or active parent's row; under a + // snoozed or settled parent they keep their own, so a collapsed shelf never + // hides one that needs attention. + const nesting = nestThreadsUnderParents( + [...pinned, ...active], + [...pinned, ...active, ...snoozed, ...settled], + ); + const isTopLevel = (thread: EnvironmentThreadShell) => + !nesting.nestedKeys.has(`${thread.environmentId}:${thread.id}`); + const childrenOf = (thread: EnvironmentThreadShell) => + nesting.childrenByParentKey.get(`${thread.environmentId}:${thread.id}`) ?? NO_CHILDREN; + const orderedActive = applyPendingThreadOrder( + sortThreadsForListV2(active.filter(isTopLevel)), + "active", + pending, ); + const orderedSnoozed = snoozed + .filter(isTopLevel) + .sort( + (left, right) => + parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""), + ); const selectedThreadKey = input.selectedThreadKey ?? null; const visibleSnoozed = input.snoozedShelfExpanded === true @@ -607,7 +672,7 @@ export function buildThreadListV2Items(input: { : orderedSnoozed.filter( (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey, ); - const orderedSettled = sortSettledThreads(settled); + const orderedSettled = sortSettledThreads(settled.filter(isTopLevel)); const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY; const pagedSettled = orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled; @@ -624,7 +689,7 @@ export function buildThreadListV2Items(input: { const items: ThreadListV2Item[] = []; for (const thread of applyPendingThreadOrder( - sortPinnedThreadsByOrderKey(pinned), + sortPinnedThreadsByOrderKey(pinned.filter(isTopLevel)), "pinned", pending, )) { @@ -634,6 +699,7 @@ export function buildThreadListV2Items(input: { snoozed: false, pinned: true, isLast: false, + children: childrenOf(thread), }); } for (const thread of orderedActive) { @@ -643,6 +709,7 @@ export function buildThreadListV2Items(input: { snoozed: false, pinned: false, isLast: false, + children: childrenOf(thread), }); } const snoozedShelfHeaderIndex = orderedSnoozed.length > 0 ? items.length : null; @@ -653,6 +720,7 @@ export function buildThreadListV2Items(input: { snoozed: true, pinned: false, isLast: false, + children: NO_CHILDREN, }); } const settledShelfHeaderIndex = orderedSettled.length > 0 ? items.length : null; @@ -663,6 +731,7 @@ export function buildThreadListV2Items(input: { snoozed: false, pinned: false, isLast: false, + children: NO_CHILDREN, }); } const last = items.at(-1); diff --git a/apps/server/integration/orchestrationEngine.integration.test.ts b/apps/server/integration/orchestrationEngine.integration.test.ts index 058ef55962271..2168f4bd81c6e 100644 --- a/apps/server/integration/orchestrationEngine.integration.test.ts +++ b/apps/server/integration/orchestrationEngine.integration.test.ts @@ -1459,6 +1459,8 @@ const delegateToCodex = (input: { prompt: "Review the uncommitted changes.", title: "Review changes", }); + const childThread = yield* harness.waitForThread(child, () => true); + assert.strictEqual(childThread.parentThreadId, THREAD_ID); const resultId = asMessageId(`delegation:${child}`); const parent = yield* harness.waitForThread(THREAD_ID, (thread) => diff --git a/apps/server/src/delegation/DelegationService.test.ts b/apps/server/src/delegation/DelegationService.test.ts index 1e5ab9b2443e3..1c4aaf7c70ade 100644 --- a/apps/server/src/delegation/DelegationService.test.ts +++ b/apps/server/src/delegation/DelegationService.test.ts @@ -143,8 +143,6 @@ const withService = ( readonly startedActivities?: ReadonlyArray; /** User messages already in the projection, as thread and message id. */ readonly userMessages?: ReadonlyArray; - /** Threads a previous process created as delegated tasks. */ - readonly delegatedThreads?: ReadonlyArray; /** What every thread's detail holds; one final answer by default. */ readonly messages?: ReadonlyArray; } = {}, @@ -167,13 +165,6 @@ const withService = ( const userMessages = new Set( (options.userMessages ?? []).map(([threadId, messageId]) => `${threadId}/${messageId}`), ); - /** The command id of each thread's creation event. */ - const createdBy = new Map( - (options.delegatedThreads ?? []).map((threadId) => [ - threadId, - CommandId.make(`server:delegation-thread-create:${threadId}`), - ]), - ); const layer = DelegationService.layer.pipe( Layer.provide( @@ -182,8 +173,12 @@ const withService = ( dispatch: (command) => Effect.gen(function* () { if (command.type === "thread.create") { - createdBy.set(command.threadId, command.commandId); - yield* setThread(shell(command.threadId, null, { title: command.title })); + yield* setThread( + shell(command.threadId, null, { + title: command.title, + parentThreadId: command.parentThreadId ?? null, + }), + ); } if (command.type === "thread.turn.start") { userMessages.add(`${command.threadId}/${command.message.messageId}`); @@ -191,11 +186,6 @@ const withService = ( yield* Queue.offer(commands, command); return { sequence: 1 }; }), - // Only the first event's command id is read. - readThreadEvents: ({ threadId }) => { - const commandId = createdBy.get(threadId); - return commandId ? Stream.make({ ...sessionSet(threadId), commandId }) : Stream.empty; - }, streamDomainEvents: Stream.unwrap( PubSub.subscribe(events).pipe( Effect.tap(() => Deferred.succeed(subscribed, undefined)), @@ -272,6 +262,7 @@ describe("DelegationService", () => { const create = yield* nextCommand; assert(create.type === "thread.create"); assert.strictEqual(create.threadId, result.threadId); + assert.strictEqual(create.parentThreadId, PARENT_ID); assert.strictEqual(create.worktreePath, "/tmp/worktree"); assert.strictEqual(create.branch, "feature"); assert.deepStrictEqual(create.modelSelection, { @@ -353,7 +344,12 @@ describe("DelegationService", () => { assert.include((yield* nested).message, "cannot delegate further"); // Finished and reported, then continued by the user. - yield* setThread(shell(child, "completed", { session: session(child, "ready") })); + yield* setThread( + shell(child, "completed", { + session: session(child, "ready"), + parentThreadId: PARENT_ID, + }), + ); yield* publish(sessionSet(child)); yield* nextCommand; assert.include((yield* nested).message, "cannot delegate further"); @@ -375,10 +371,12 @@ describe("DelegationService", () => { { threads: [ shell(PARENT_ID, "completed", { session: session(PARENT_ID, "ready") }), - shell(child, "completed", { session: session(child, "ready") }), + shell(child, "completed", { + session: session(child, "ready"), + parentThreadId: PARENT_ID, + }), ], userMessages: [[PARENT_ID, MessageId.make(`delegation:${child}`)]], - delegatedThreads: [child], messages: [], }, ); diff --git a/apps/server/src/delegation/DelegationService.ts b/apps/server/src/delegation/DelegationService.ts index 748929a202197..af783fd47db58 100644 --- a/apps/server/src/delegation/DelegationService.ts +++ b/apps/server/src/delegation/DelegationService.ts @@ -98,8 +98,6 @@ interface Outcome { const startedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:started`); const completedActivityId = (child: ThreadId) => EventId.make(`delegation:${child}:completed`); const resultMessageId = (child: ThreadId) => MessageId.make(`delegation:${child}`); -/** Tags the command that creates a delegated thread; its creation event keeps it for good. */ -const CREATE_COMMAND_TAG = "delegation-thread-create"; /** How a delegated thread stands; `null` while its turn has not finished. */ export function delegatedThreadStatus( @@ -347,35 +345,19 @@ const make = Effect.gen(function* () { }); const delegate = Effect.fn("DelegationService.delegate")(function* (input: DelegateInput) { - // Read from the thread's creation event, so the rule holds after the task finishes, when - // the user continues or rewinds it, and across restarts. - const created = yield* engine - .readThreadEvents({ - threadId: input.parentThreadId, - fromSequenceExclusive: 0, - toSequenceInclusive: Number.MAX_SAFE_INTEGER, - limit: 1, - }) - .pipe( - Stream.runHead, - Effect.mapError(() => new DelegationError({ message: "Could not read this thread." })), - ); - if ( - Option.exists( - created, - (event) => event.commandId?.startsWith(`server:${CREATE_COMMAND_TAG}:`) === true, - ) - ) { - return yield* failWith( - "This thread is itself a delegated task and cannot delegate further. Do the work here.", - ); - } const parent = yield* snapshots .getThreadShellById(input.parentThreadId) .pipe(Effect.mapError(() => new DelegationError({ message: "Could not read this thread." }))); if (Option.isNone(parent)) { return yield* failWith(`Thread ${input.parentThreadId} was not found.`); } + // Set at creation, so the rule holds after the task finishes, when the user continues or + // rewinds it, and across restarts. + if (parent.value.parentThreadId != null) { + return yield* failWith( + "This thread is itself a delegated task and cannot delegate further. Do the work here.", + ); + } const providers = yield* providerRegistry.getProviders; const provider = findProvider(providers, input.provider); if (!provider) { @@ -424,8 +406,9 @@ const make = Effect.gen(function* () { yield* Effect.gen(function* () { yield* engine.dispatch({ type: "thread.create", - commandId: yield* commandId(CREATE_COMMAND_TAG), + commandId: yield* commandId("delegation-thread-create"), threadId: childThreadId, + parentThreadId: input.parentThreadId, projectId: parent.value.projectId, title, modelSelection, diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 75c119b9b15fd..0f371e20b0aa8 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -619,6 +619,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti interactionMode: event.payload.interactionMode, branch: event.payload.branch, worktreePath: event.payload.worktreePath, + parentThreadId: event.payload.parentThreadId ?? null, linkedPullRequest: null, branchPullRequest: null, latestTurnId: null, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index cfba902976336..263f0df287061 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -487,6 +487,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { pinOrderKey: "gm", activeOrderKey: "hq", autoSettleDisabledAt: null, + parentThreadId: null, titleRegeneration: null, titleState: null, deletedAt: null, @@ -614,6 +615,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { pinOrderKey: "gm", activeOrderKey: "hq", autoSettleDisabledAt: null, + parentThreadId: null, titleRegeneration: null, titleState: null, session: { diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 07d30e47e27b1..fce7609f28c39 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -589,6 +589,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", auto_settle_disabled_at AS "autoSettleDisabledAt", + parent_thread_id AS "parentThreadId", title_regeneration_request_id AS "titleRegenerationRequestId", title_regeneration_started_at AS "titleRegenerationStartedAt", latest_user_message_at AS "latestUserMessageAt", @@ -637,6 +638,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", auto_settle_disabled_at AS "autoSettleDisabledAt", + parent_thread_id AS "parentThreadId", title_regeneration_request_id AS "titleRegenerationRequestId", title_regeneration_started_at AS "titleRegenerationStartedAt", latest_user_message_at AS "latestUserMessageAt", @@ -712,6 +714,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", auto_settle_disabled_at AS "autoSettleDisabledAt", + parent_thread_id AS "parentThreadId", title_regeneration_request_id AS "titleRegenerationRequestId", title_regeneration_started_at AS "titleRegenerationStartedAt", latest_user_message_at AS "latestUserMessageAt", @@ -1316,6 +1319,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", auto_settle_disabled_at AS "autoSettleDisabledAt", + parent_thread_id AS "parentThreadId", title_regeneration_request_id AS "titleRegenerationRequestId", title_regeneration_started_at AS "titleRegenerationStartedAt", latest_user_message_at AS "latestUserMessageAt", @@ -2392,6 +2396,7 @@ pending_approval_requests AS ( pinOrderKey: row.pinOrderKey ?? null, activeOrderKey: row.activeOrderKey ?? null, autoSettleDisabledAt: row.autoSettleDisabledAt ?? null, + parentThreadId: row.parentThreadId ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, deletedAt: row.deletedAt, @@ -2638,6 +2643,7 @@ pending_approval_requests AS ( pinOrderKey: row.pinOrderKey ?? null, activeOrderKey: row.activeOrderKey ?? null, autoSettleDisabledAt: row.autoSettleDisabledAt ?? null, + parentThreadId: row.parentThreadId ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, deletedAt: row.deletedAt, @@ -2799,6 +2805,7 @@ pending_approval_requests AS ( pinOrderKey: row.pinOrderKey ?? null, activeOrderKey: row.activeOrderKey ?? null, autoSettleDisabledAt: row.autoSettleDisabledAt ?? null, + parentThreadId: row.parentThreadId ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, session: sessionByThread.get(row.threadId) ?? null, @@ -2985,6 +2992,7 @@ pending_approval_requests AS ( pinOrderKey: row.pinOrderKey ?? null, activeOrderKey: row.activeOrderKey ?? null, autoSettleDisabledAt: row.autoSettleDisabledAt ?? null, + parentThreadId: row.parentThreadId ?? null, titleRegeneration: mapTitleRegeneration(row), titleState: row.titleState, session: sessionByThread.get(row.threadId) ?? null, @@ -3334,6 +3342,7 @@ pending_approval_requests AS ( pinOrderKey: threadRow.value.pinOrderKey ?? null, activeOrderKey: threadRow.value.activeOrderKey ?? null, autoSettleDisabledAt: threadRow.value.autoSettleDisabledAt ?? null, + parentThreadId: threadRow.value.parentThreadId ?? null, titleRegeneration: mapTitleRegeneration(threadRow.value), titleState: threadRow.value.titleState, session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null, @@ -3636,6 +3645,7 @@ pending_approval_requests AS ( pinOrderKey: threadRow.value.pinOrderKey ?? null, activeOrderKey: threadRow.value.activeOrderKey ?? null, autoSettleDisabledAt: threadRow.value.autoSettleDisabledAt ?? null, + parentThreadId: threadRow.value.parentThreadId ?? null, titleRegeneration: mapTitleRegeneration(threadRow.value), titleState: threadRow.value.titleState, deletedAt: null, diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index a6c795df2a5c1..20d1a523ac0b1 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -386,6 +386,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); + if (command.parentThreadId !== undefined) { + yield* requireThread({ + readModel, + command, + threadId: command.parentThreadId, + }); + } return { ...(yield* withEventBase({ aggregateKind: "thread", @@ -404,6 +411,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" interactionMode: command.interactionMode, branch: command.branch, worktreePath: command.worktreePath, + ...(command.parentThreadId !== undefined + ? { parentThreadId: command.parentThreadId } + : {}), createdAt: command.createdAt, updatedAt: command.createdAt, }, diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index 516b85fbdae87..f8a3c982a6307 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -94,6 +94,7 @@ describe("orchestration projector", () => { archivedAt: null, activeOrderKey: null, autoSettleDisabledAt: null, + parentThreadId: null, settledOverride: null, settledAt: null, unsettledAt: null, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index dd418b95b9bcc..96b4a3dd26c49 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -445,6 +445,7 @@ export function projectEvent( interactionMode: payload.interactionMode, branch: payload.branch, worktreePath: payload.worktreePath, + parentThreadId: payload.parentThreadId ?? null, pullRequests: [], branchPullRequest: null, latestTurn: null, diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 595bc0b5594c3..87f2e6375866a 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -55,6 +55,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pin_order_key, active_order_key, auto_settle_disabled_at, + parent_thread_id, title_regeneration_request_id, title_regeneration_started_at, latest_user_message_at, @@ -88,6 +89,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.pinOrderKey ?? null}, ${row.activeOrderKey ?? null}, ${row.autoSettleDisabledAt ?? null}, + ${row.parentThreadId ?? null}, ${row.titleRegenerationRequestId ?? null}, ${row.titleRegenerationStartedAt ?? null}, ${row.latestUserMessageAt}, @@ -121,6 +123,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pin_order_key = excluded.pin_order_key, active_order_key = excluded.active_order_key, auto_settle_disabled_at = excluded.auto_settle_disabled_at, + parent_thread_id = excluded.parent_thread_id, title_regeneration_request_id = excluded.title_regeneration_request_id, title_regeneration_started_at = excluded.title_regeneration_started_at, latest_user_message_at = excluded.latest_user_message_at, @@ -161,6 +164,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { pin_order_key AS "pinOrderKey", active_order_key AS "activeOrderKey", auto_settle_disabled_at AS "autoSettleDisabledAt", + parent_thread_id AS "parentThreadId", title_regeneration_request_id AS "titleRegenerationRequestId", title_regeneration_started_at AS "titleRegenerationStartedAt", latest_user_message_at AS "latestUserMessageAt", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 452c4fb08900f..18ca79cc3ae07 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -67,6 +67,7 @@ import Migration0052 from "./Migrations/052_ProjectionThreadTitleState.ts"; import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts"; import Migration0054 from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts"; import Migration0055 from "./Migrations/055_Notes.ts"; +import Migration0056 from "./Migrations/056_ProjectionThreadsParentThreadId.ts"; /** * Migration loader with all migrations defined inline. @@ -134,6 +135,7 @@ const migrationEntries = [ [53, "PullRequestFilesViewed", Migration0053], [54, "ProjectionThreadsAutoSettleDisabledAt", Migration0054], [55, "Notes", Migration0055], + [56, "ProjectionThreadsParentThreadId", Migration0056], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.test.ts b/apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.test.ts new file mode 100644 index 0000000000000..cc609ef8b8d16 --- /dev/null +++ b/apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.test.ts @@ -0,0 +1,59 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; + +import { runMigrations } from "../Migrations.ts"; +import migrateParentThreadId from "./056_ProjectionThreadsParentThreadId.ts"; + +it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( + "056_ProjectionThreadsParentThreadId", + (it) => { + it.effect("links existing delegated threads to the thread that started them", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 55 }); + const now = "2026-01-01T00:00:00.000Z"; + for (const threadId of ["parent", "child", "unrelated"]) { + yield* sql` + INSERT INTO projection_threads ( + thread_id, project_id, title, model_selection_json, runtime_mode, + created_at, updated_at + ) VALUES ( + ${threadId}, 'project-1', 'Thread', + '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', ${now}, ${now} + ) + `; + } + yield* sql` + INSERT INTO projection_thread_activities ( + activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at + ) VALUES ( + 'delegation:child:started', 'parent', NULL, 'info', 'task.started', + 'Delegated task started', '{}', ${now} + ) + `; + yield* runMigrations({ toMigrationInclusive: 56 }); + const parents = yield* sql<{ + readonly threadId: string; + readonly parentThreadId: string | null; + }>` + SELECT thread_id AS "threadId", parent_thread_id AS "parentThreadId" + FROM projection_threads + ORDER BY thread_id + `; + assert.deepEqual(parents, [ + { threadId: "child", parentThreadId: "parent" }, + { threadId: "parent", parentThreadId: null }, + { threadId: "unrelated", parentThreadId: null }, + ]); + // Re-running against a database that already has the column is a no-op. + yield* migrateParentThreadId; + const rerun = yield* sql<{ readonly parentThreadId: string | null }>` + SELECT parent_thread_id AS "parentThreadId" FROM projection_threads WHERE thread_id = 'child' + `; + assert.deepEqual(rerun, [{ parentThreadId: "parent" }]); + }), + ); + }, +); diff --git a/apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.ts b/apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.ts new file mode 100644 index 0000000000000..33bb7ac3c7107 --- /dev/null +++ b/apps/server/src/persistence/Migrations/056_ProjectionThreadsParentThreadId.ts @@ -0,0 +1,34 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +/** + * Adds the delegating thread to each thread. Delegations made before this + * column existed are recovered from the parent's `delegation::started` + * activity, which names both threads. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_threads) + `; + if (!columns.some((column) => column.name === "parent_thread_id")) { + yield* sql` + ALTER TABLE projection_threads + ADD COLUMN parent_thread_id TEXT + `; + } + yield* sql` + UPDATE projection_threads + SET parent_thread_id = ( + SELECT activity.thread_id + FROM projection_thread_activities AS activity + WHERE activity.activity_id = 'delegation:' || projection_threads.thread_id || ':started' + ) + WHERE parent_thread_id IS NULL + AND EXISTS ( + SELECT 1 + FROM projection_thread_activities AS activity + WHERE activity.activity_id = 'delegation:' || projection_threads.thread_id || ':started' + ) + `; +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index abd964382a09d..2984702ee9086 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -51,6 +51,7 @@ export const ProjectionThread = Schema.Struct({ pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)), activeOrderKey: Schema.optional(Schema.NullOr(Schema.String)), autoSettleDisabledAt: Schema.optional(Schema.NullOr(IsoDateTime)), + parentThreadId: Schema.optional(Schema.NullOr(ThreadId)), titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)), titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)), latestUserMessageAt: Schema.NullOr(IsoDateTime), diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index d016089023eb4..1596ce772b489 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -25,6 +25,7 @@ import { resolveSettledThreadTimestamp, sortSettledThreads, } from "@t3tools/client-runtime/state/thread-sort"; +import { nestThreadsUnderParents } from "@t3tools/client-runtime/state/thread-nesting"; import { threadSearchMatchKey, type EnvironmentThreadSearchMatch, @@ -52,6 +53,7 @@ import { CircleAlertIcon, CircleCheckIcon, CircleDashedIcon, + CircleStopIcon, ClockIcon, EyeIcon, FolderIcon, @@ -976,6 +978,149 @@ const dropVerbBadge: Record = { ), }; +// Same hues as the card row's status label, so a delegated thread reads the +// same color as it would on its own. +const childStatusTone = { + working: { + Icon: CircleDashedIcon, + label: "Working", + className: "text-sky-600 dark:text-sky-400", + }, + monitoring: { Icon: EyeIcon, label: "Monitoring", className: "text-foreground" }, + approval: { Icon: ShieldQuestionIcon, label: "Approval", className: "text-warning-foreground" }, + input: { + Icon: MessageCircleQuestionIcon, + label: "Input", + className: "text-indigo-600 dark:text-indigo-300", + }, + failed: { Icon: CircleAlertIcon, label: "Failed", className: "text-red-700 dark:text-red-300" }, + stopped: { Icon: CircleStopIcon, label: "Stopped", className: "text-muted-foreground/70" }, + done: { + Icon: CircleCheckIcon, + label: "Done", + className: "text-emerald-700 dark:text-emerald-300", + }, + read: { Icon: CircleCheckIcon, label: "Done", className: "text-muted-foreground/70" }, +} as const; + +/** + * One-line row for a thread another thread delegated work to. It renders + * inside the parent's list item, indented to the parent's text, so it moves + * with the parent when dragged. Click opens the thread; right-click gets the + * normal thread menu. + */ +const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { + thread: SidebarThreadSummary; + isActive: boolean; + providerEntryByInstanceId: ReadonlyMap; + onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; + onThreadActivate: (threadRef: ScopedThreadRef) => void; + onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void; +}) { + const { thread, onThreadClick, onThreadActivate, onContextMenu } = props; + const threadRef = useMemo( + () => scopeThreadRef(thread.environmentId, thread.id), + [thread.environmentId, thread.id], + ); + const threadKey = scopedThreadKey(threadRef); + const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); + const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); + const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); + const status = resolveSidebarThreadStatus(thread); + const turnState = thread.latestTurn?.state ?? null; + + const tone = + status === "failed" || turnState === "error" + ? "failed" + : status === "ready" + ? turnState === "interrupted" + ? "stopped" + : isUnread + ? "done" + : "read" + : status; + const { Icon, label, className: toneClassName } = childStatusTone[tone]; + const statusIcon = ; + + const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; + const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; + + const handleClick = useCallback( + (event: ReactMouseEvent) => { + event.stopPropagation(); + onThreadClick(event, threadRef); + }, + [onThreadClick, threadRef], + ); + const handleKeyDown = useCallback( + (event: ReactKeyboardEvent) => { + if (event.key !== "Enter" && event.key !== " ") return; + event.preventDefault(); + event.stopPropagation(); + onThreadActivate(threadRef); + }, + [onThreadActivate, threadRef], + ); + const handleContextMenu = useCallback( + (event: ReactMouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + onContextMenu(threadRef, { x: event.clientX, y: event.clientY }); + }, + [onContextMenu, threadRef], + ); + + return ( +
  • +
    + {statusIcon} + {providerEntry ? ( + + ) : null} + + {thread.title} + + + {status === "working" ? ( + + ) : ( + threadTimeLabel(thread) + )} + +
    +
  • + ); +}); + const SidebarThreadRow = memo(function SidebarThreadRow(props: { thread: SidebarThreadSummary; variant: "card" | "slim"; @@ -1036,6 +1181,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { * composer. Absent when the sidebar cannot open server threads. */ onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined; + /** Threads this one delegated work to, shown as one-line rows beneath it. */ + childThreads: readonly SidebarThreadSummary[]; + /** The routed child's key when the route is one of `childThreads`. */ + activeChildKey: string | null; }) { const { isRenaming, @@ -1761,6 +1910,30 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { const diff = latestTurnDiff(thread); + const childRows = + props.childThreads.length > 0 ? ( +
      + {props.childThreads.map((child) => { + const childKey = scopedThreadKey(scopeThreadRef(child.environmentId, child.id)); + return ( + + ); + })} +
    + ) : null; + return (
  • {detailsTooltip} + {childRows}
  • ); }); @@ -2591,6 +2765,7 @@ export default function Sidebar() { snoozedThreads, settledThreads, snoozeNow, + childThreadsByParentKey, } = useMemo(() => { // Snooze classification uses a REAL clock, not the quantized minute: // wake times are second-precise and a woken thread must not linger on @@ -2653,13 +2828,18 @@ export default function Sidebar() { active.push(thread); } } + // Delegated threads ride along under a pinned or active parent's row, so + // they move with it; under a settled or snoozed parent they keep their own. + const nesting = nestThreadsUnderParents([...pinned, ...active], visible); + const isTopLevel = (thread: EnvironmentThreadShell) => + !nesting.nestedKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))); // One shared rule on every platform (see sortPinnedThreadsByOrderKey): // user-arranged keys first, keyless threads in creation order below. // Server capability only gates DRAGGING — it must not influence the // sort, or mixed-version fleets would render different pinned orders on // web and mobile from the same data. - const sortedPinned = sortPinnedThreadsForSidebar(pinned); - const sortedActive = sortThreadsForSidebar(active); + const sortedPinned = sortPinnedThreadsForSidebar(pinned.filter(isTopLevel)); + const sortedActive = sortThreadsForSidebar(active.filter(isTopLevel)); return { pinnedThreads: optimisticDrop?.section !== "pinned" || optimisticDrop.order === null @@ -2680,13 +2860,16 @@ export default function Sidebar() { getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), }), // Soonest wake first: "what comes back next" is the shelf's question. - snoozedThreads: snoozed.toSorted( - (left, right) => - firstValidTimestampMs(left.snoozedUntil ?? null) - - firstValidTimestampMs(right.snoozedUntil ?? null), - ), - settledThreads: sortSettledThreads(settled), + snoozedThreads: snoozed + .filter(isTopLevel) + .toSorted( + (left, right) => + firstValidTimestampMs(left.snoozedUntil ?? null) - + firstValidTimestampMs(right.snoozedUntil ?? null), + ), + settledThreads: sortSettledThreads(settled.filter(isTopLevel)), snoozeNow: preciseNow, + childThreadsByParentKey: nesting.childrenByParentKey, }; }, [nowMinute, optimisticDrop, scopedProjectKeys, serverConfigs, snoozeWakeTick, threads]); @@ -4750,6 +4933,8 @@ export default function Sidebar() { // not from the sidebar second-guessing what still matters. const isCard = section === "active" || section === "pinned"; const rowVariant = isCard ? "card" : "slim"; + const childThreads = + childThreadsByParentKey.get(threadKey) ?? EMPTY_THREADS; return ( + scopedThreadKey(scopeThreadRef(child.environmentId, child.id)) === + routeThreadKey, + ) + ? routeThreadKey + : null + } /> ); }; diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 4811a772f4a67..ec3bde93b1508 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -179,9 +179,11 @@ On web and desktop, use **Agents** to follow work delegated to subagents. An agent can also hand a task to another provider, for example "ask Codex to review this". The task runs as its own thread in the same working copy and shows -in **Agents**; select it to open that thread. When it finishes, its final -message arrives in the original thread as a new message, and the agent picks up -from there. Stopping the delegated thread reports back too. +in **Agents**; select it to open that thread. While the original thread is +pinned or active, the delegated thread also appears as a short line beneath it +in the thread list, with its own status. When it finishes, its final message +arrives in the original thread as a new message, and the agent picks up from +there. Stopping the delegated thread reports back too. Expand a tool call in the conversation to see its full command and output. Summaries shorten shell wrappers and can still describe the latest call after it diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index e07bdd3249128..5a3bf455d0a4a 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -235,6 +235,10 @@ "types": "./src/state/threadSort.ts", "default": "./src/state/threadSort.ts" }, + "./state/thread-nesting": { + "types": "./src/state/threadNesting.ts", + "default": "./src/state/threadNesting.ts" + }, "./state/profile-scope": { "types": "./src/state/profileScope.ts", "default": "./src/state/profileScope.ts" diff --git a/packages/client-runtime/src/state/threadNesting.test.ts b/packages/client-runtime/src/state/threadNesting.test.ts new file mode 100644 index 0000000000000..1784096fab1a2 --- /dev/null +++ b/packages/client-runtime/src/state/threadNesting.test.ts @@ -0,0 +1,64 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { nestThreadsUnderParents } from "./threadNesting.ts"; + +const LOCAL = EnvironmentId.make("local"); +const REMOTE = EnvironmentId.make("remote"); + +const thread = ( + id: string, + options: { parent?: string; createdAt?: string; environmentId?: EnvironmentId } = {}, +) => ({ + environmentId: options.environmentId ?? LOCAL, + id: ThreadId.make(id), + parentThreadId: options.parent === undefined ? null : ThreadId.make(options.parent), + createdAt: options.createdAt ?? "2026-10-01T10:00:00.000Z", +}); + +const childIds = (result: ReturnType, parentKey: string) => + result.childrenByParentKey.get(parentKey)?.map((child) => child.id) ?? []; + +describe("nestThreadsUnderParents", () => { + it("nests children under their parent, oldest first", () => { + const parent = thread("parent"); + const all = [ + parent, + thread("later", { parent: "parent", createdAt: "2026-10-01T12:00:00.000Z" }), + thread("earlier", { parent: "parent", createdAt: "2026-10-01T11:00:00.000Z" }), + thread("unrelated"), + ]; + const result = nestThreadsUnderParents([parent], all); + expect(childIds(result, "local:parent")).toEqual(["earlier", "later"]); + expect([...result.nestedKeys].toSorted()).toEqual(["local:earlier", "local:later"]); + }); + + it("keeps a child on its own row when its parent cannot host it", () => { + // The parent is settled or snoozed, or not loaded at all. + const result = nestThreadsUnderParents( + [thread("active")], + [thread("settled-parent"), thread("child", { parent: "settled-parent" })], + ); + expect(result.nestedKeys.size).toBe(0); + }); + + it("matches parents within the child's own environment", () => { + const parent = thread("parent", { environmentId: REMOTE }); + const result = nestThreadsUnderParents( + [parent], + [parent, thread("child", { parent: "parent" })], + ); + expect(result.nestedKeys.size).toBe(0); + }); + + it("never hides a grandchild under a nested parent", () => { + const all = [ + thread("root"), + thread("child", { parent: "root" }), + thread("grandchild", { parent: "child" }), + ]; + const result = nestThreadsUnderParents(all, all); + expect(childIds(result, "local:root")).toEqual(["child"]); + expect(result.nestedKeys.has("local:grandchild")).toBe(false); + }); +}); diff --git a/packages/client-runtime/src/state/threadNesting.ts b/packages/client-runtime/src/state/threadNesting.ts new file mode 100644 index 0000000000000..c8bb52e64cee0 --- /dev/null +++ b/packages/client-runtime/src/state/threadNesting.ts @@ -0,0 +1,53 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; + +import { scopedThreadKey, scopeThreadRef } from "../environment/scoped.ts"; + +interface NestableThread { + readonly environmentId: EnvironmentId; + readonly id: ThreadId; + readonly parentThreadId?: ThreadId | null | undefined; + readonly createdAt: string; +} + +export interface NestedThreads { + /** Children by their parent's scoped key, oldest first. */ + readonly childrenByParentKey: ReadonlyMap; + /** Scoped keys of threads that render under a parent instead of on their own. */ + readonly nestedKeys: ReadonlySet; +} + +const keyOf = (thread: NestableThread) => + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + +/** + * Groups delegated threads under the thread that started them, one level + * deep. Only `hosts` take children: pass the rows that always render (pinned + * and active), so a child that needs attention is never folded into a + * collapsed shelf. A child whose parent is not a host keeps its own row. + */ +export function nestThreadsUnderParents( + hosts: readonly T[], + threads: readonly T[], +): NestedThreads { + const hostByKey = new Map( + hosts + .filter((thread) => thread.parentThreadId == null) + .map((thread) => [keyOf(thread), thread] as const), + ); + const childrenByParentKey = new Map(); + const nestedKeys = new Set(); + for (const thread of threads) { + const parentId = thread.parentThreadId; + if (parentId == null) continue; + const parentKey = scopedThreadKey(scopeThreadRef(thread.environmentId, parentId)); + if (!hostByKey.has(parentKey)) continue; + const children = childrenByParentKey.get(parentKey) ?? []; + children.push(thread); + childrenByParentKey.set(parentKey, children); + nestedKeys.add(keyOf(thread)); + } + for (const children of childrenByParentKey.values()) { + children.sort((left, right) => left.createdAt.localeCompare(right.createdAt)); + } + return { childrenByParentKey, nestedKeys }; +} diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts index 66f78a0464ec5..00f69da0ebddc 100644 --- a/packages/client-runtime/src/state/threadReducer.ts +++ b/packages/client-runtime/src/state/threadReducer.ts @@ -122,6 +122,7 @@ export function applyThreadDetailEvent( interactionMode: event.payload.interactionMode, branch: event.payload.branch, worktreePath: event.payload.worktreePath, + parentThreadId: event.payload.parentThreadId ?? null, branchPullRequest: null, latestTurn: null, createdAt: event.payload.createdAt, diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index fcb7d4788b69c..6efc3fe7bdaa0 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -842,6 +842,9 @@ export const OrchestrationThread = Schema.Struct({ // Survives manual settle, un-settle, and activity: only the user clears it. // Optional so payloads from older servers still decode. autoSettleDisabledAt: Schema.optional(Schema.NullOr(IsoDateTime)), + // The thread that delegated this one its task; fixed at creation. Clients + // nest the thread under it. Optional so payloads from older servers still decode. + parentThreadId: Schema.optional(Schema.NullOr(ThreadId)), // Pending-only state. Optional so older servers remain compatible. titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)), titleState: Schema.optional(Schema.NullOr(ThreadTitleState)), @@ -913,6 +916,8 @@ export const OrchestrationThreadShell = Schema.Struct({ pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), autoSettleDisabledAt: Schema.optional(Schema.NullOr(IsoDateTime)), + // See OrchestrationThread.parentThreadId. + parentThreadId: Schema.optional(Schema.NullOr(ThreadId)), titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)), titleState: Schema.optional(Schema.NullOr(ThreadTitleState)), session: Schema.NullOr(OrchestrationSession), @@ -1131,6 +1136,8 @@ const ThreadCreateCommand = Schema.Struct({ worktreePath: Schema.NullOr(TrimmedNonEmptyString), createdAt: IsoDateTime, historyImport: Schema.optional(Schema.Literal(true)), + /** The thread delegating this one its task. */ + parentThreadId: Schema.optional(ThreadId), }); const ThreadDeleteCommand = Schema.Struct({ @@ -1785,6 +1792,7 @@ export const ThreadCreatedPayload = Schema.Struct({ ), branch: Schema.NullOr(TrimmedNonEmptyString), worktreePath: Schema.NullOr(TrimmedNonEmptyString), + parentThreadId: Schema.optional(ThreadId), createdAt: IsoDateTime, updatedAt: IsoDateTime, }); From 955baa73776e227adaa16f206a7477f4f7269e23 Mon Sep 17 00:00:00 2001 From: Donald Silveira <9506146+donnes@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:14:32 -0300 Subject: [PATCH 2/3] fix(web): keep nested threads reachable in sidebar actions - Include delegated children in search, selection, and jump order - Route file drops and jump hints to nested thread rows --- apps/web/src/components/Sidebar.logic.test.ts | 16 +++++ apps/web/src/components/Sidebar.tsx | 72 ++++++++++++++++--- .../src/state/threadNesting.test.ts | 17 ++++- .../client-runtime/src/state/threadNesting.ts | 13 ++++ 4 files changed, 108 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 86cee77446f18..ac96cf831c541 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -50,6 +50,10 @@ import { resolveSidebarDropVerb, } from "./Sidebar.logic"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { + nestThreadsUnderParents, + withNestedChildren, +} from "@t3tools/client-runtime/state/thread-nesting"; import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort"; import { EnvironmentId, @@ -896,6 +900,18 @@ describe("searchSidebarThreads", () => { threads[2], ]); }); + it("finds delegated threads nested under their parent by title and content", () => { + const parent = { ...searchThread("parent", "Plan release", "Alpha"), createdAt: "" }; + const child = { + ...searchThread("child", "Review release notes", "Alpha"), + createdAt: "", + parentThreadId: ThreadId.make("parent"), + }; + const { childrenByParentKey } = nestThreadsUnderParents([parent], [parent, child]); + const searchable = withNestedChildren([parent], childrenByParentKey); + expect(searchSidebarThreads(searchable, "notes")).toEqual([child]); + expect(searchSidebarThreads(searchable, "changelog", contentKeys("child"))).toEqual([child]); + }); }); describe("filterSidebarProjectScopeItems", () => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 1596ce772b489..5ded1ba0b4241 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -25,7 +25,10 @@ import { resolveSettledThreadTimestamp, sortSettledThreads, } from "@t3tools/client-runtime/state/thread-sort"; -import { nestThreadsUnderParents } from "@t3tools/client-runtime/state/thread-nesting"; +import { + nestThreadsUnderParents, + withNestedChildren, +} from "@t3tools/client-runtime/state/thread-nesting"; import { threadSearchMatchKey, type EnvironmentThreadSearchMatch, @@ -1007,17 +1010,19 @@ const childStatusTone = { * One-line row for a thread another thread delegated work to. It renders * inside the parent's list item, indented to the parent's text, so it moves * with the parent when dragged. Click opens the thread; right-click gets the - * normal thread menu. + * normal thread menu; dropped files go to this thread, not the parent. */ const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { thread: SidebarThreadSummary; isActive: boolean; + jumpLabel: string | null; providerEntryByInstanceId: ReadonlyMap; onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; onThreadActivate: (threadRef: ScopedThreadRef) => void; onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void; + onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined; }) { - const { thread, onThreadClick, onThreadActivate, onContextMenu } = props; + const { thread, onThreadClick, onThreadActivate, onContextMenu, onFileDropThreads } = props; const threadRef = useMemo( () => scopeThreadRef(thread.environmentId, thread.id), [thread.environmentId, thread.id], @@ -1069,22 +1074,45 @@ const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { }, [onContextMenu, threadRef], ); + const [isFileDragOver, setIsFileDragOver] = useState(false); + const fileDropHandlers = useMemo( + () => + onFileDropThreads + ? makeWorkspaceFileDropHandlers({ + setDragActive: setIsFileDragOver, + addFiles: (files) => { + onFileDropThreads(threadRef, files); + }, + addFolders: () => {}, + }) + : null, + [onFileDropThreads, threadRef], + ); + useEffect(() => { + if (!isFileDragOver) return; + const clearFileDrag = () => setIsFileDragOver(false); + window.addEventListener("dragend", clearFileDrag); + return () => window.removeEventListener("dragend", clearFileDrag); + }, [isFileDragOver]); return (
  • + {props.jumpLabel ? : null}
  • ); @@ -1185,6 +1214,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { childThreads: readonly SidebarThreadSummary[]; /** The routed child's key when the route is one of `childThreads`. */ activeChildKey: string | null; + /** Jump hints for `childThreads`; null while hints are hidden. */ + childJumpLabelByKey: ReadonlyMap | null; }) { const { isRenaming, @@ -1924,10 +1955,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { key={childKey} thread={child} isActive={props.activeChildKey === childKey} + jumpLabel={props.childJumpLabelByKey?.get(childKey) ?? null} providerEntryByInstanceId={props.providerEntryByInstanceId} onThreadClick={onThreadClick} onThreadActivate={onThreadActivate} onContextMenu={onContextMenu} + onFileDropThreads={onFileDropThreads} /> ); })} @@ -1938,7 +1971,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
  • 0; const searchableThreads = useMemo( - () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads], - [activeThreads, pinnedThreads, settledThreads, snoozedThreads], + () => [ + ...withNestedChildren([...pinnedThreads, ...activeThreads], childThreadsByParentKey), + ...snoozedThreads, + ...settledThreads, + ], + [activeThreads, childThreadsByParentKey, pinnedThreads, settledThreads, snoozedThreads], ); const searchEnvironmentIds = useMemo( () => @@ -3015,9 +3054,21 @@ export default function Sidebar() { return routeThread === undefined ? EMPTY_THREADS : [routeThread]; }, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]); + // Rendered order, nested children included: the context menu, multi-select, + // shift-range select, and jump shortcuts all resolve rows through it. const orderedThreads = useMemo( - () => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads], - [pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads], + () => [ + ...withNestedChildren([...pinnedThreads, ...activeThreads], childThreadsByParentKey), + ...visibleSnoozedThreads, + ...renderedSettledThreads, + ], + [ + pinnedThreads, + activeThreads, + childThreadsByParentKey, + visibleSnoozedThreads, + renderedSettledThreads, + ], ); const orderedThreadKeys = useMemo( () => @@ -5036,6 +5087,9 @@ export default function Sidebar() { ? routeThreadKey : null } + childJumpLabelByKey={ + showThreadJumpHints && childThreads.length > 0 ? jumpLabelByKey : null + } /> ); }; diff --git a/packages/client-runtime/src/state/threadNesting.test.ts b/packages/client-runtime/src/state/threadNesting.test.ts index 1784096fab1a2..30abf1f953f7e 100644 --- a/packages/client-runtime/src/state/threadNesting.test.ts +++ b/packages/client-runtime/src/state/threadNesting.test.ts @@ -1,7 +1,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { nestThreadsUnderParents } from "./threadNesting.ts"; +import { nestThreadsUnderParents, withNestedChildren } from "./threadNesting.ts"; const LOCAL = EnvironmentId.make("local"); const REMOTE = EnvironmentId.make("remote"); @@ -61,4 +61,19 @@ describe("nestThreadsUnderParents", () => { expect(childIds(result, "local:root")).toEqual(["child"]); expect(result.nestedKeys.has("local:grandchild")).toBe(false); }); + + it("lists each nested child right after its parent", () => { + const parent = thread("parent"); + const other = thread("other"); + const child = thread("child", { parent: "parent" }); + const { childrenByParentKey } = nestThreadsUnderParents( + [parent, other], + [parent, other, child], + ); + expect(withNestedChildren([parent, other], childrenByParentKey).map((t) => t.id)).toEqual([ + "parent", + "child", + "other", + ]); + }); }); diff --git a/packages/client-runtime/src/state/threadNesting.ts b/packages/client-runtime/src/state/threadNesting.ts index c8bb52e64cee0..2f2f9be2d1a9f 100644 --- a/packages/client-runtime/src/state/threadNesting.ts +++ b/packages/client-runtime/src/state/threadNesting.ts @@ -51,3 +51,16 @@ export function nestThreadsUnderParents( } return { childrenByParentKey, nestedKeys }; } + +/** + * `threads` in display order with each one's nested children right after it. + * Lookups, search, selection, and keyboard order use this so a nested child + * stays reachable even though it renders inside its parent's row. + */ +export function withNestedChildren( + threads: readonly T[], + childrenByParentKey: ReadonlyMap, +): T[] { + if (childrenByParentKey.size === 0) return [...threads]; + return threads.flatMap((thread) => [thread, ...(childrenByParentKey.get(keyOf(thread)) ?? [])]); +} From 862c6f21ad1275dcb91e12e70d9a09cf5734a495 Mon Sep 17 00:00:00 2001 From: Donald Silveira <9506146+donnes@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:02:43 -0300 Subject: [PATCH 3/3] fix(web): keep nested threads' lifecycle and rename in the sidebar - Read settled and snoozed state from each thread, not the rendered sections - Let nested rows rename through the shared inline editor Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/web/src/components/Sidebar.logic.test.ts | 41 +++ apps/web/src/components/Sidebar.logic.ts | 33 +++ apps/web/src/components/Sidebar.tsx | 237 +++++++++++------- 3 files changed, 227 insertions(+), 84 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index ac96cf831c541..ffeaed930442b 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -28,6 +28,7 @@ import { resolveThreadStatusPill, resolveWorkingStartedAt, searchSidebarThreads, + nestSidebarSections, formatWorkingDurationLabel, shouldClearThreadSelectionOnMouseDown, shouldRecedeSidebarThread, @@ -2475,3 +2476,43 @@ describe("navigation after parking a thread", () => { }, ); }); + +describe("nestSidebarSections", () => { + const thread = (id: string, parent?: string) => ({ + environmentId: localEnvironmentId, + id: ThreadId.make(id), + parentThreadId: parent === undefined ? null : ThreadId.make(parent), + createdAt: "2026-10-01T10:00:00.000Z", + }); + + it("keeps a nested child's settled or snoozed state while it renders under its parent", () => { + const parent = thread("parent"); + const settledChild = thread("settled-child", "parent"); + const snoozedChild = thread("snoozed-child", "parent"); + const result = nestSidebarSections({ + pinned: [], + active: [parent], + snoozed: [snoozedChild], + settled: [settledChild], + }); + expect(result.settled).toEqual([]); + expect(result.snoozed).toEqual([]); + expect(result.childrenByParentKey.get(`${localEnvironmentId}:parent`)).toEqual([ + snoozedChild, + settledChild, + ]); + expect([...result.settledKeys]).toEqual([`${localEnvironmentId}:settled-child`]); + expect([...result.snoozedKeys]).toEqual([`${localEnvironmentId}:snoozed-child`]); + }); + + it("leaves children of a settled parent on their own rows", () => { + const result = nestSidebarSections({ + pinned: [], + active: [thread("child", "parent")], + snoozed: [], + settled: [thread("parent")], + }); + expect(result.active.map((entry) => entry.id)).toEqual(["child"]); + expect(result.childrenByParentKey.size).toBe(0); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 05664206105be..0915bdb3d4602 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -6,6 +6,7 @@ import { type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; +import { nestThreadsUnderParents } from "@t3tools/client-runtime/state/thread-nesting"; import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; import type { AsyncResult } from "effect/unstable/reactivity"; @@ -1247,3 +1248,35 @@ export function sortScopedProjectsForSidebar< left.id.localeCompare(right.id), ); } + +type NestableSidebarThread = Parameters[0][number]; + +/** + * Moves delegated threads under a pinned or active parent out of the section lists, so they + * render inside that parent's row; under a settled or snoozed parent they keep their own row. + * The settled and snoozed key sets come from every thread's own section, nested or not: + * menus and forward navigation must still treat a nested settled child as settled. + */ +export function nestSidebarSections(sections: { + readonly pinned: readonly T[]; + readonly active: readonly T[]; + readonly snoozed: readonly T[]; + readonly settled: readonly T[]; +}) { + const { pinned, active, snoozed, settled } = sections; + const nesting = nestThreadsUnderParents( + [...pinned, ...active], + [...pinned, ...active, ...snoozed, ...settled], + ); + const keyOf = (thread: T) => `${thread.environmentId}:${thread.id}`; + const isTopLevel = (thread: T) => !nesting.nestedKeys.has(keyOf(thread)); + return { + pinned: pinned.filter(isTopLevel), + active: active.filter(isTopLevel), + snoozed: snoozed.filter(isTopLevel), + settled: settled.filter(isTopLevel), + childrenByParentKey: nesting.childrenByParentKey, + settledKeys: new Set(settled.map(keyOf)), + snoozedKeys: new Set(snoozed.map(keyOf)), + }; +} diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 5ded1ba0b4241..a21598c991f6a 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -25,10 +25,7 @@ import { resolveSettledThreadTimestamp, sortSettledThreads, } from "@t3tools/client-runtime/state/thread-sort"; -import { - nestThreadsUnderParents, - withNestedChildren, -} from "@t3tools/client-runtime/state/thread-nesting"; +import { withNestedChildren } from "@t3tools/client-runtime/state/thread-nesting"; import { threadSearchMatchKey, type EnvironmentThreadSearchMatch, @@ -175,6 +172,7 @@ import { hasUnseenCompletion, isSidebarNestedLinkClick, isTrailingDoubleClick, + nestSidebarSections, orderItemsByPreferredIds, planSidebarThreadDrop, reduceSidebarProjectScopeMenuState, @@ -1006,6 +1004,59 @@ const childStatusTone = { read: { Icon: CircleCheckIcon, label: "Done", className: "text-muted-foreground/70" }, } as const; +/** + * Inline title editor for a sidebar row. Enter or leaving the field commits, + * Escape cancels. It mounts when a rename starts, so each rename starts fresh. + */ +function SidebarRenameInput(props: { + threadRef: ScopedThreadRef; + originalTitle: string; + value: string; + textClassName: string; + onChange: (title: string) => void; + onCommit: (threadRef: ScopedThreadRef, title: string, originalTitle: string) => void; + onCancel: () => void; +}) { + const { threadRef, originalTitle, value, onCommit, onCancel } = props; + const committedRef = useRef(false); + const handleKeyDown = useCallback( + (event: ReactKeyboardEvent) => { + event.stopPropagation(); + if (event.nativeEvent.isComposing || event.keyCode === 229) return; + if (event.key === "Enter") { + event.preventDefault(); + committedRef.current = true; + onCommit(threadRef, value, originalTitle); + } else if (event.key === "Escape") { + event.preventDefault(); + committedRef.current = true; + onCancel(); + } + }, + [onCancel, onCommit, originalTitle, threadRef, value], + ); + const handleBlur = useCallback(() => { + if (!committedRef.current) onCommit(threadRef, value, originalTitle); + }, [onCommit, originalTitle, threadRef, value]); + return ( + props.onChange(event.target.value)} + onFocus={(event) => event.currentTarget.select()} + onKeyDown={handleKeyDown} + onBlur={handleBlur} + onClick={(event) => event.stopPropagation()} + onDoubleClick={(event) => event.stopPropagation()} + className={cn( + "min-w-0 flex-1 rounded-sm border border-input bg-card px-1 font-medium text-card-foreground outline-none focus:border-foreground", + props.textClassName, + )} + /> + ); +} + /** * One-line row for a thread another thread delegated work to. It renders * inside the parent's list item, indented to the parent's text, so it moves @@ -1021,8 +1072,22 @@ const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { onThreadActivate: (threadRef: ScopedThreadRef) => void; onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void; onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined; + isRenaming: boolean; + renamingTitle: string; + onStartRename: (threadRef: ScopedThreadRef, title: string) => void; + onRenameTitleChange: (title: string) => void; + onCommitRename: (threadRef: ScopedThreadRef, title: string, originalTitle: string) => void; + onCancelRename: () => void; }) { - const { thread, onThreadClick, onThreadActivate, onContextMenu, onFileDropThreads } = props; + const { + thread, + onThreadClick, + onThreadActivate, + onContextMenu, + onFileDropThreads, + isRenaming, + onStartRename, + } = props; const threadRef = useMemo( () => scopeThreadRef(thread.environmentId, thread.id), [thread.environmentId, thread.id], @@ -1074,6 +1139,15 @@ const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { }, [onContextMenu, threadRef], ); + const handleDoubleClick = useCallback( + (event: ReactMouseEvent) => { + if (isRenaming || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + event.stopPropagation(); + onStartRename(threadRef, thread.title); + }, + [isRenaming, onStartRename, thread.title, threadRef], + ); const [isFileDragOver, setIsFileDragOver] = useState(false); const fileDropHandlers = useMemo( () => @@ -1115,6 +1189,7 @@ const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { isFileDragOver && !props.isActive && !isSelected && "bg-sidebar-row-hover", )} onClick={handleClick} + onDoubleClick={handleDoubleClick} onKeyDown={handleKeyDown} onContextMenu={handleContextMenu} > @@ -1128,15 +1203,27 @@ const SidebarChildThreadRow = memo(function SidebarChildThreadRow(props: { iconClassName="size-3.5 opacity-60" /> ) : null} - - {thread.title} - + {isRenaming ? ( + + ) : ( + + {thread.title} + + )} {status === "working" ? ( @@ -1216,6 +1303,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { activeChildKey: string | null; /** Jump hints for `childThreads`; null while hints are hidden. */ childJumpLabelByKey: ReadonlyMap | null; + /** The child being renamed, if any; `renamingTitle` then holds its draft. */ + renamingChildKey: string | null; }) { const { isRenaming, @@ -1483,31 +1572,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { window.addEventListener("dragend", clearFileDrag); return () => window.removeEventListener("dragend", clearFileDrag); }, [isFileDragOver]); - const renameCommittedRef = useRef(false); - useEffect(() => { - if (isRenaming) renameCommittedRef.current = false; - }, [isRenaming]); - const handleRenameKeyDown = useCallback( - (event: ReactKeyboardEvent) => { - event.stopPropagation(); - if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Enter") { - event.preventDefault(); - renameCommittedRef.current = true; - onCommitRename(threadRef, renamingTitle, thread.title); - } else if (event.key === "Escape") { - event.preventDefault(); - renameCommittedRef.current = true; - onCancelRename(); - } - }, - [onCancelRename, onCommitRename, renamingTitle, thread.title, threadRef], - ); - const handleRenameBlur = useCallback(() => { - if (!renameCommittedRef.current) { - onCommitRename(threadRef, renamingTitle, thread.title); - } - }, [onCommitRename, renamingTitle, thread.title, threadRef]); const handleSettleClick = useCallback( (event: ReactMouseEvent) => { event.preventDefault(); @@ -1655,17 +1719,14 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { }); const title = isRenaming ? ( - onRenameTitleChange(event.target.value)} - onFocus={(event) => event.currentTarget.select()} - onKeyDown={handleRenameKeyDown} - onBlur={handleRenameBlur} - onClick={(event) => event.stopPropagation()} - onDoubleClick={(event) => event.stopPropagation()} - className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground" + textClassName="text-sm" + onChange={onRenameTitleChange} + onCommit={onCommitRename} + onCancel={onCancelRename} /> ) : ( ); })} @@ -2801,6 +2868,8 @@ export default function Sidebar() { settledThreads, snoozeNow, childThreadsByParentKey, + settledThreadKeys, + snoozedThreadKeys, } = useMemo(() => { // Snooze classification uses a REAL clock, not the quantized minute: // wake times are second-precise and a woken thread must not linger on @@ -2863,18 +2932,14 @@ export default function Sidebar() { active.push(thread); } } - // Delegated threads ride along under a pinned or active parent's row, so - // they move with it; under a settled or snoozed parent they keep their own. - const nesting = nestThreadsUnderParents([...pinned, ...active], visible); - const isTopLevel = (thread: EnvironmentThreadShell) => - !nesting.nestedKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))); + const nested = nestSidebarSections({ pinned, active, snoozed, settled }); // One shared rule on every platform (see sortPinnedThreadsByOrderKey): // user-arranged keys first, keyless threads in creation order below. // Server capability only gates DRAGGING — it must not influence the // sort, or mixed-version fleets would render different pinned orders on // web and mobile from the same data. - const sortedPinned = sortPinnedThreadsForSidebar(pinned.filter(isTopLevel)); - const sortedActive = sortThreadsForSidebar(active.filter(isTopLevel)); + const sortedPinned = sortPinnedThreadsForSidebar(nested.pinned); + const sortedActive = sortThreadsForSidebar(nested.active); return { pinnedThreads: optimisticDrop?.section !== "pinned" || optimisticDrop.order === null @@ -2895,16 +2960,18 @@ export default function Sidebar() { getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), }), // Soonest wake first: "what comes back next" is the shelf's question. - snoozedThreads: snoozed - .filter(isTopLevel) - .toSorted( - (left, right) => - firstValidTimestampMs(left.snoozedUntil ?? null) - - firstValidTimestampMs(right.snoozedUntil ?? null), - ), - settledThreads: sortSettledThreads(settled.filter(isTopLevel)), + snoozedThreads: nested.snoozed.toSorted( + (left, right) => + firstValidTimestampMs(left.snoozedUntil ?? null) - + firstValidTimestampMs(right.snoozedUntil ?? null), + ), + settledThreads: sortSettledThreads(nested.settled), snoozeNow: preciseNow, - childThreadsByParentKey: nesting.childrenByParentKey, + childThreadsByParentKey: nested.childrenByParentKey, + // By each thread's own state, nested children included: the context menu + // and forward navigation read these. + settledThreadKeys: nested.settledKeys, + snoozedThreadKeys: nested.snoozedKeys, }; }, [nowMinute, optimisticDrop, scopedProjectKeys, serverConfigs, snoozeWakeTick, threads]); @@ -3102,26 +3169,8 @@ export default function Sidebar() { // a ref keeps it out of attemptSettle's dependency array. const handleNewThreadRef = useRef(newThreadContext.handleNewThread); handleNewThreadRef.current = newThreadContext.handleNewThread; - const settledThreadKeys = useMemo( - () => - new Set( - settledThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - ), - [settledThreads], - ); const settledThreadKeysRef = useRef(settledThreadKeys); settledThreadKeysRef.current = settledThreadKeys; - const snoozedThreadKeys = useMemo( - () => - new Set( - snoozedThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - ), - [snoozedThreads], - ); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); snoozedThreadKeysRef.current = snoozedThreadKeys; @@ -4986,6 +5035,15 @@ export default function Sidebar() { const rowVariant = isCard ? "card" : "slim"; const childThreads = childThreadsByParentKey.get(threadKey) ?? EMPTY_THREADS; + const renamingChildKey = + renamingThreadKey !== null && + childThreads.some( + (child) => + scopedThreadKey(scopeThreadRef(child.environmentId, child.id)) === + renamingThreadKey, + ) + ? renamingThreadKey + : null; return ( + scopedThreadKey(scopeThreadRef(child.environmentId, child.id)) === + renamingThreadKey, + ) || !draggableThreadKeys.has(threadKey) || optimisticDrop !== null }