diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 70b3764550c9f..1549520cc8cb2 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -508,7 +508,13 @@ export function HomeScreen(props: HomeScreenProps) { ); } if (item.type === "v2-agent-section") { - return ; + return ( + + ); } if (item.type !== "v2-thread") return null; const thread = item.item.thread; diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index d0998de290bef..91b0074602d8a 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -422,7 +422,14 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { /> ); case "v2-agent-section": - return ; + 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 7b156875d8aeb..e5b07d9f48d17 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -4,6 +4,7 @@ import { IconButton } from "../../components/ui/IconButton"; import { formatSidebarAgentStates, sidebarRoleSectionLabels, + sidebarAgentsSectionLabel, } from "@t3tools/client-runtime/state/sidebar-families"; import { useViewability } from "@legendapp/list/react-native"; import { @@ -127,6 +128,8 @@ interface StatusLabel { } export const THREAD_ROW_VIEWABILITY = { itemVisiblePercentThreshold: 1 }; +const WORKING_STATUS_TINT = "accent-adaptive-sky-600-400"; + const STATUS_LABEL_BY_STATUS: Partial> = { approval: { label: msg("Approval", { $context: "thread status, waiting for approval" }), @@ -146,7 +149,7 @@ const STATUS_LABEL_BY_STATUS: Partial> = working: { label: null, icon: "circle.dashed", - iconTintClassName: "accent-adaptive-sky-600-400", + iconTintClassName: WORKING_STATUS_TINT, }, waiting: { label: null, @@ -704,7 +707,7 @@ export function ThreadListV2ProjectFolderHeader({ }) { const gt = useGT(); const m = useMessages(); - const summary = item.expanded ? "" : formatSidebarAgentStates(item.counts, m, true); + const summary = item.expanded ? "" : formatSidebarAgentStates(item.counts, m, true).text; const { project } = item; return ( @@ -753,12 +756,21 @@ export function ThreadListV2ProjectFolderHeader({ export function ThreadListV2AgentSectionHeader({ item, onToggle, + listVisible, + sidebarPane = false, }: { readonly item: ThreadListV2AgentSectionItem; + readonly listVisible: boolean; + readonly sidebarPane?: boolean; readonly onToggle: (key: string, expanded: boolean) => void; }) { const m = useMessages(); - const summary = formatSidebarAgentStates(item.counts, m); + const { working, details } = formatSidebarAgentStates(item.counts, m); + const [visible, setVisible] = useState(false); + useViewability(useCallback((token) => setVisible(token.isViewable), [])); + const appActive = useAppActive(); + const focused = useIsFocused(); + const animate = visible && listVisible && appActive && (focused || sidebarPane); return ( - {m(sidebarRoleSectionLabels[item.role])} + {m( + item.role === undefined ? sidebarAgentsSectionLabel : sidebarRoleSectionLabels[item.role], + )} {item.total} - {summary ? {summary} : null} + {working ? ( + + + {working.count} + + ) : null} + {working && details ? ( + + · + + ) : null} + {details ? ( + + {details} + + ) : null} ); } diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 2b7c58d4ba30a..35637678649d0 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1415,7 +1415,7 @@ it("renders saved section names, nesting, and interleaved project order", () => ]); }); -it("nests role sections under their orchestrator and summarizes collapsed folders", () => { +it("groups orchestrator and orphan agents separately and summarizes collapsed folders", () => { const root = makeThread({ id: ThreadId.make("root"), title: "Root" }); const working = makeThread({ id: ThreadId.make("working"), @@ -1447,7 +1447,17 @@ it("nests role sections under their orchestrator and summarizes collapsed folder title: "Settled", settledOverride: "settled", }); - const threads = [root, working, waiting, settled]; + const orphan = makeThread({ + id: ThreadId.make("orphan"), + title: "Orphan agent", + delegatedRole: "test", + lineage: { + parentThreadId: ThreadId.make("missing"), + rootThreadId: ThreadId.make("missing"), + relationshipToParent: "subagent", + }, + }); + const threads = [root, working, waiting, settled, orphan]; const children = indexSidebarChildren(threads); const projects = buildHomeProjectScopes({ projects: [makeProjectFixture({ id: root.projectId, title: "Project", environmentId })], @@ -1468,6 +1478,7 @@ it("nests role sections under their orchestrator and summarizes collapsed folder pendingTasks: [], folders: { children, + orphanAgents: [orphan], projects, layouts: new Map(), expanded: new Map(collapsed.map((key) => [key, false])), @@ -1481,22 +1492,39 @@ it("nests role sections under their orchestrator and summarizes collapsed folder expect(expanded.map((item) => item.key)).toEqual([ folderKey, `v2-thread:${environmentId}:root`, + `agents:${environmentId}:root`, roleKey("implementation"), `v2-thread:${environmentId}:working`, roleKey("review"), `v2-thread:${environmentId}:waiting`, `v2-thread:${environmentId}:settled`, + `agents:${folderKey}`, + `role:${folderKey}:test`, + `v2-thread:${environmentId}:orphan`, ]); expect(expanded[1]).toMatchObject({ agentCount: 2, agentRow: false, familyExpanded: true }); expect(expanded[2]).toMatchObject({ + total: 2, + counts: { working: 1, attention: 1, failed: 0 }, + }); + expect(expanded[3]).toMatchObject({ role: "implementation", counts: { working: 1, attention: 0, failed: 0 }, }); - expect(expanded[4]).toMatchObject({ + expect(expanded[5]).toMatchObject({ role: "review", counts: { working: 0, attention: 1, failed: 0 }, }); + expect(rows([`agents:${environmentId}:root`]).map(({ key }) => key)).toEqual([ + folderKey, + `v2-thread:${environmentId}:root`, + `agents:${environmentId}:root`, + `v2-thread:${environmentId}:settled`, + `agents:${folderKey}`, + `role:${folderKey}:test`, + `v2-thread:${environmentId}:orphan`, + ]); const collapsed = rows([folderKey]); expect(collapsed).toHaveLength(1); expect( diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index b58ea70347a04..8f5ce7e16f2b6 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -5,6 +5,7 @@ import { groupSidebarThreadsByProject, projectSectionRows, sidebarFamilyRows, + type SidebarFamilyItem, type SidebarAgentRole, type SidebarAgentState, } from "@t3tools/client-runtime/state/sidebar-families"; @@ -504,7 +505,7 @@ export interface ThreadListV2AgentSectionItem { readonly type: "v2-agent-section"; readonly key: string; readonly depth: number; - readonly role: SidebarAgentRole; + readonly role?: SidebarAgentRole; readonly total: number; readonly counts: Readonly>; readonly expanded: boolean; @@ -666,6 +667,7 @@ export function buildThreadListV2ListItems(input: { readonly pendingTasks: ReadonlyArray; readonly folders?: { readonly children: ReadonlyMap; + readonly orphanAgents?: readonly EnvironmentThreadShell[]; readonly projects: readonly HomeProjectScope[]; readonly layouts: ProjectThreadLayouts; readonly environmentId?: EnvironmentId | null; @@ -752,22 +754,61 @@ export function buildThreadListV2ListItems(input: { ), ); const threadKey = (thread: EnvironmentThreadShell) => `${thread.environmentId}:${thread.id}`; + const pinnedKeys = new Set( + input.items.filter((row) => row.pinned).map((row) => threadKey(row.thread)), + ); + const orphanAgents = (folders.orphanAgents ?? []).filter( + (thread) => + !pinnedKeys.has(threadKey(thread)) && + (folders.environmentId == null || folders.environmentId === thread.environmentId), + ); + const orphanKeys = new Set(orphanAgents.map(threadKey)); + const groups = folders.projects.map((project) => ({ + project, + projectKey: project.key, + memberProjectRefs: project.projectRefs, + })); + const groupedFolders = groupSidebarThreadsByProject( + groups, + [ + ...input.items.flatMap((row) => + row.pinned || orphanKeys.has(threadKey(row.thread)) ? [] : [row.thread], + ), + ...orphanAgents, + ], + ({ project }) => folders.scoped || !project.archived, + ); + const folderKey = (projectKey: string) => `v2-project-folder:${projectKey}`; const families = sidebarFamilyRows( - input.items.map((row) => row.thread), + [ + ...input.items + .map((row) => row.thread) + .filter((thread) => !orphanKeys.has(threadKey(thread))), + ...orphanAgents, + ], folders.children, folders.expanded, folders.routeKey, (key) => folders.expanded.get(key) ?? true, + new Map( + groupedFolders.map(({ group, threads }) => [ + folderKey(group.projectKey), + threads.filter((thread) => orphanKeys.has(threadKey(thread))), + ]), + ), ); - const renderFamily = (thread: EnvironmentThreadShell, depth: number, showChildren = true) => { - const family = families.get(threadKey(thread)) ?? []; + const renderFamily = ( + family: readonly SidebarFamilyItem[], + depth: number, + showChildren = true, + ) => { for (const item of showChildren ? family : family.slice(0, 1)) { - if (item.kind === "role") { + if (item.kind !== "thread") { result.push({ type: "v2-agent-section", key: item.key, depth: depth + item.depth, - role: item.role, + ...(item.kind === "role" ? { role: item.role } : {}), total: item.threads.length, counts: countStates(item.threads), expanded: item.expanded, @@ -796,18 +837,8 @@ export function buildThreadListV2ListItems(input: { } }; for (const row of input.items) { - if (row.pinned) renderFamily(row.thread, 0); + if (row.pinned) renderFamily(families.get(threadKey(row.thread)) ?? [], 0); } - const groups = folders.projects.map((project) => ({ - project, - projectKey: project.key, - memberProjectRefs: project.projectRefs, - })); - const groupedFolders = groupSidebarThreadsByProject( - groups, - input.items.flatMap((row) => (row.pinned ? [] : [row.thread])), - ({ project }) => folders.scoped || !project.archived, - ); const collapsedById = new Map([...folders.expanded].map(([key, expanded]) => [key, !expanded])); const sectionLayouts = folders.environmentId == null @@ -833,7 +864,7 @@ export function buildThreadListV2ListItems(input: { continue; } const { group, threads } = row.folder; - const key = `v2-project-folder:${group.projectKey}`; + const key = folderKey(group.projectKey); const savedExpansion = group.memberProjectRefs .map( ({ environmentId, projectId }) => @@ -864,7 +895,12 @@ export function buildThreadListV2ListItems(input: { counts: countStates(hiddenThreads), expanded, }); - for (const thread of visibleThreads) renderFamily(thread, depth, expanded); + for (const thread of visibleThreads) { + if (!expanded || !orphanKeys.has(threadKey(thread))) { + renderFamily(families.get(threadKey(thread)) ?? [], depth, expanded); + } + } + if (expanded) renderFamily(families.get(key) ?? [], depth); } } else { const threadItems = input.items.map((item) => buildThreadItem(item)); diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts index d41d372eb4de4..a96539f0c98f6 100644 --- a/apps/mobile/src/features/threads/useThreadListV2.ts +++ b/apps/mobile/src/features/threads/useThreadListV2.ts @@ -1,6 +1,9 @@ import { useAtom } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; -import { indexSidebarChildren } from "@t3tools/client-runtime/state/sidebar-families"; +import { + indexSidebarChildren, + sidebarOrphanAgents, +} from "@t3tools/client-runtime/state/sidebar-families"; import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads"; import type { EnvironmentId } from "@t3tools/contracts"; import { useCallback, useMemo } from "react"; @@ -70,6 +73,10 @@ export function useThreadListV2(input: { const { threads } = input; const [expanded, setExpanded] = useAtom(expandedSidebarRowsAtom); const children = useMemo(() => indexSidebarChildren(input.agentThreads), [input.agentThreads]); + const orphanAgents = useMemo( + () => sidebarOrphanAgents(input.agentThreads, children), + [input.agentThreads, children], + ); const projects = useMemo(() => { const projectKeys = input.projectRefs == null @@ -219,6 +226,7 @@ export function useThreadListV2(input: { ? { folders: { children, + orphanAgents, projects, layouts: input.projectLayouts, environmentId: input.environmentId, @@ -239,6 +247,7 @@ export function useThreadListV2(input: { [ layout, children, + orphanAgents, projects, input.projectLayouts, input.environmentId, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 0216ad02622d8..b69ed48f8ac36 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5728,5 +5728,6 @@ "ddbb7b9406af92ed": "Artefakt {name} entfernen", "54d9df5245fa49a7": "Das Seitenleistenlayout konnte nicht gespeichert werden. Versuche es erneut.", "ee71ac7e8e9b000c": "Ultrafast-Modus an", - "e649c08fbd9a1a30": "Fast-Modus an" + "e649c08fbd9a1a30": "Fast-Modus an", + "99d122b4ef1f6aa4": "Agenten" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 7923806372831..215329070dfa5 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5730,5 +5730,6 @@ "ddbb7b9406af92ed": "Remove artifact {name}", "54d9df5245fa49a7": "Could not save sidebar layout. Try again.", "ee71ac7e8e9b000c": "Ultrafast mode on", - "e649c08fbd9a1a30": "Fast mode on" + "e649c08fbd9a1a30": "Fast mode on", + "99d122b4ef1f6aa4": "Agents" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index cf53fd13da33a..0cda317f4c31a 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5722,5 +5722,6 @@ "ddbb7b9406af92ed": "Eliminar el artefacto {name}", "54d9df5245fa49a7": "No se pudo guardar la disposición de la barra lateral. Inténtalo de nuevo.", "ee71ac7e8e9b000c": "Modo Ultrafast activado", - "e649c08fbd9a1a30": "Modo rápido activado" + "e649c08fbd9a1a30": "Modo rápido activado", + "99d122b4ef1f6aa4": "Agentes" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 0008a05a60886..0bad75f3a85c8 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5722,5 +5722,6 @@ "ddbb7b9406af92ed": "Retirer l’artefact {name}", "54d9df5245fa49a7": "Impossible d’enregistrer la disposition de la barre latérale. Réessayez.", "ee71ac7e8e9b000c": "Mode Ultrafast activé", - "e649c08fbd9a1a30": "Mode Fast activé" + "e649c08fbd9a1a30": "Mode Fast activé", + "99d122b4ef1f6aa4": "Agents" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index ccbe5bed241bd..b2b099c367340 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5699,5 +5699,6 @@ "ddbb7b9406af92ed": "アーティファクト「{name}」を削除", "54d9df5245fa49a7": "サイドバーのレイアウトを保存できませんでした。もう一度お試しください。", "ee71ac7e8e9b000c": "超高速モード オン", - "e649c08fbd9a1a30": "高速モード オン" + "e649c08fbd9a1a30": "高速モード オン", + "99d122b4ef1f6aa4": "エージェント" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index d30ef692b34b4..f8a1f16005bf0 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5706,5 +5706,6 @@ "ddbb7b9406af92ed": "{name} 아티팩트 제거", "54d9df5245fa49a7": "사이드바 레이아웃을 저장하지 못했습니다. 다시 시도하세요.", "ee71ac7e8e9b000c": "초고속 모드 켜짐", - "e649c08fbd9a1a30": "고속 모드 켜짐" + "e649c08fbd9a1a30": "고속 모드 켜짐", + "99d122b4ef1f6aa4": "에이전트" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 5dd335eae72d5..bef3d89eba0e7 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5722,5 +5722,6 @@ "ddbb7b9406af92ed": "Remover o artefato {name}", "54d9df5245fa49a7": "Não foi possível salvar o layout da barra lateral. Tente novamente.", "ee71ac7e8e9b000c": "Modo Ultrafast ativado", - "e649c08fbd9a1a30": "Modo Fast ativado" + "e649c08fbd9a1a30": "Modo Fast ativado", + "99d122b4ef1f6aa4": "Agentes" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index a244c1388a143..0417d6267a27c 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5802,5 +5802,6 @@ "ddbb7b9406af92ed": "Удалить артефакт «{name}»", "54d9df5245fa49a7": "Не удалось сохранить расположение элементов боковой панели. Повторите попытку.", "ee71ac7e8e9b000c": "Сверхбыстрый режим включён", - "e649c08fbd9a1a30": "Быстрый режим включён" + "e649c08fbd9a1a30": "Быстрый режим включён", + "99d122b4ef1f6aa4": "Агенты" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 3c418089e04f4..e99e512776379 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5728,5 +5728,6 @@ "ddbb7b9406af92ed": "Ta bort artefakten {name}", "54d9df5245fa49a7": "Det gick inte att spara sidopanelens layout. Försök igen.", "ee71ac7e8e9b000c": "Ultrasnabbt läge på", - "e649c08fbd9a1a30": "Snabbläge på" + "e649c08fbd9a1a30": "Snabbläge på", + "99d122b4ef1f6aa4": "Agenter" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index d0bc17d5fe28f..b4dfdc53248e2 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5709,5 +5709,6 @@ "ddbb7b9406af92ed": "移除工件「{name}」", "54d9df5245fa49a7": "无法保存侧边栏布局。请重试。", "ee71ac7e8e9b000c": "极速模式已开启", - "e649c08fbd9a1a30": "快速模式已开启" + "e649c08fbd9a1a30": "快速模式已开启", + "99d122b4ef1f6aa4": "智能体" } diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index 8415145f5f31d..733098759a45d 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -78,6 +78,26 @@ function makeProject(title: string): Project { } describe("CommandPalette open intents", () => { + it("collapses and expands agent and task sections from the palette", async () => { + setup(); + const key = "t3code:sidebar:agent-task-sections"; + using cleanup = new DisposableStack(); + cleanup.defer(() => removeLocalStorageItem(key)); + await using _screen = await render({null}); + + for (const [query, title, allExpanded] of [ + ["collapse all agent", "Collapse all agent and task sections", false], + ["expand all agent", "Expand all agent and task sections", true], + ] as const) { + openCommandPalette({ query }); + await page.getByRole("option", { name: title }).click(); + expect(JSON.parse(localStorage.getItem(key) ?? "null")).toEqual({ + allExpanded, + overrides: {}, + }); + } + }); + it("drags a searched thread into the current composer without navigating", async () => { const environmentId = EnvironmentId.make("remote"); const threadId = ThreadId.make("dragged-thread"); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index ec48a4fe2ce2c..f2575102ca8f8 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -69,6 +69,8 @@ import { ChartNoAxesColumnIcon, CheckIcon, ChevronRightIcon, + ChevronsDownUpIcon, + ChevronsUpDownIcon, CornerLeftUpIcon, FileSearchIcon, FolderGit2Icon, @@ -89,6 +91,11 @@ import { UserPlusIcon, WorkflowIcon, } from "lucide-react"; +import { + collapseSidebarSectionsLabel, + expandSidebarSectionsLabel, + setAllSidebarSectionsExpanded, +} from "./sidebar/sidebarSectionExpansion"; import { openThreadFind } from "./chat/threadFindStore"; import { dispatchPreviewAction } from "./preview/previewActionBus"; import { previewBridge } from "./preview/previewBridge"; @@ -1961,6 +1968,18 @@ function OpenCommandPaletteDialog(props: { }); } + for (const expanded of [false, true]) { + const Icon = expanded ? ChevronsUpDownIcon : ChevronsDownUpIcon; + actionItems.push({ + kind: "action", + value: expanded ? "action:sidebar-sections:expand" : "action:sidebar-sections:collapse", + searchTerms: ["sidebar", "agents", "tasks"], + title: messages(expanded ? expandSidebarSectionsLabel : collapseSidebarSectionsLabel), + icon: , + run: async () => setAllSidebarSectionsExpanded(expanded), + }); + } + const rootGroups = buildRootGroups({ actionItems, recentThreadItems }, messages); const sourceSelectionViewValue = addProjectEnvironmentId === null ? null : `sources:${addProjectEnvironmentId}`; diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index b0567e288f011..5613b8699e796 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -357,8 +357,12 @@ it("lists child agents in role sections under their orchestrator and keeps a clo sidebarAgentTextSize: 18, }); const ROLE_SECTIONS_KEY = "t3code:sidebar:role-sections-collapsed"; - localStorage.removeItem(ROLE_SECTIONS_KEY); - stack.defer(() => localStorage.removeItem(ROLE_SECTIONS_KEY)); + const EXPANSION_KEY = "t3code:sidebar:agent-task-sections"; + const TASK_SECTIONS_KEY = "t3code:sidebar:task-sections-expanded"; + for (const key of [ROLE_SECTIONS_KEY, EXPANSION_KEY, TASK_SECTIONS_KEY]) { + localStorage.removeItem(key); + stack.defer(() => localStorage.removeItem(key)); + } const { environmentId, id: projectId, ...rest } = project("T3 Code"); const parent = threadShell(projectId, 1); @@ -446,7 +450,23 @@ it("lists child agents in role sections under their orchestrator and keeps a clo delegatedRole: "design" as const, archivedAt: time, }; - const owner = { ...threadShell(projectId, 5), title: "Release checklist" }; + const owner = { + ...threadShell(projectId, 5), + title: "Release checklist", + pendingBackgroundTasks: [ + { + taskId: "compile", + kind: "command" as const, + description: "Compile project", + }, + ], + }; + const orphan = { + ...threadShell(projectId, 6), + title: "Orphaned worker", + delegatedRole: "test" as const, + lineage: { ...child.lineage, parentThreadId: ThreadId.make("missing") }, + }; const rootRef = scopeThreadRef(environmentId, root.id); vi.mocked(useProjects).mockReturnValue([{ ...rest, environmentId, id: projectId }]); vi.mocked(useConnectedEnvironmentIds).mockReturnValue([environmentId]); @@ -506,7 +526,7 @@ it("lists child agents in role sections under their orchestrator and keeps a clo ); - vi.mocked(useQuietThreadShells).mockReturnValue([child, reviewer, root, owner, archived]); + vi.mocked(useQuietThreadShells).mockReturnValue([child, reviewer, root, owner, archived, orphan]); await using screen = await render(tree(), { container }); const parentRow = screen.getByRole("button", { name: /^Compact sidebar threads,/ }); const implementor = screen.getByRole("button", { @@ -519,7 +539,18 @@ it("lists child agents in role sections under their orchestrator and keeps a clo await expect.element(screen.getByText("Release checklist", { exact: true })).toBeVisible(); await expect.element(implementor).toBeVisible(); await expect.element(doneReviewer).toBeVisible(); - await expect.element(implementors).toHaveTextContent("Implementors11 working"); + const agents = parentRow.element().closest("li")!.nextElementSibling!; + const orchestratorAgents = screen.getByTestId("sidebar-agents-section").first(); + const projectAgents = screen.getByTestId("sidebar-agents-section").nth(1); + const orphanWorker = screen.getByRole("button", { name: /^Orphaned worker,/ }); + const tasks = screen.getByRole("button", { name: /^Tasks/ }); + expect(agents).toBe(orchestratorAgents.element().closest("li")); + expect(orchestratorAgents.element().querySelector(".lucide-loader-circle")).toBeVisible(); + expect(implementors.element().querySelector(".lucide-loader-circle")).toBeVisible(); + await expect.element(orphanWorker).toBeVisible(); + expect(projectAgents.element().getAttribute("data-sidebar-parent")).toBe( + tasks.element().getAttribute("data-sidebar-parent"), + ); await expect.element(reviewers).toHaveTextContent("Reviewers1"); // Archived children and empty roles stay out. await expect.element(screen.getByText("Designers", { exact: true })).not.toBeInTheDocument(); @@ -527,8 +558,11 @@ it("lists child agents in role sections under their orchestrator and keeps a clo expect(item(implementors)?.nextElementSibling).toBe(item(implementor)); expect(item(implementor)?.nextElementSibling).toBe(item(reviewers)); expect(item(reviewers)?.nextElementSibling).toBe(item(doneReviewer)); - expect(item(parentRow)?.nextElementSibling).toBe(item(implementors)); + expect(item(orchestratorAgents)?.nextElementSibling).toBe(item(implementors)); expect(implementors.element().getAttribute("data-sidebar-parent")).toBe( + orchestratorAgents.element().getAttribute("data-sidebar-row"), + ); + expect(orchestratorAgents.element().getAttribute("data-sidebar-parent")).toBe( parentRow.element().getAttribute("data-sidebar-row"), ); expect(implementor.element().getAttribute("data-sidebar-parent")).toBe( @@ -541,6 +575,35 @@ it("lists child agents in role sections under their orchestrator and keeps a clo await familyToggle.click(); await expect.element(implementors).toBeVisible(); + const altClick = (locator: { element: () => Element }) => + act(() => + locator + .element() + .querySelector("svg")! + .dispatchEvent(new MouseEvent("click", { bubbles: true, altKey: true })), + ); + await altClick(implementors); + await expect.element(orchestratorAgents).toHaveAttribute("aria-expanded", "false"); + await expect.element(projectAgents).toHaveAttribute("aria-expanded", "false"); + await expect.element(implementors).not.toBeInTheDocument(); + await expect.element(orphanWorker).not.toBeInTheDocument(); + await altClick(tasks); + await expect.element(tasks).toHaveAttribute("aria-expanded", "true"); + await expect.element(screen.getByText("Compile project")).toBeVisible(); + await expect.element(implementor).toBeVisible(); + await expect.element(orphanWorker).toBeVisible(); + + const menu = screen.getByRole("button", { name: "Sidebar options" }); + await menu.click(); + await screen.getByRole("menuitem", { name: "Collapse all agent and task sections" }).click(); + await screen.rerender(tree("collapsed")); + await expect.element(orchestratorAgents).toHaveAttribute("aria-expanded", "false"); + await expect.element(tasks).toHaveAttribute("aria-expanded", "false"); + await menu.click(); + await screen.getByRole("menuitem", { name: "Expand all agent and task sections" }).click(); + await expect.element(implementor).toBeVisible(); + await expect.element(screen.getByText("Compile project")).toBeVisible(); + await implementors.click(); await expect.element(implementors).toHaveAttribute("aria-expanded", "false"); await expect.element(implementor).not.toBeInTheDocument(); @@ -605,7 +668,7 @@ it("lists child agents in role sections under their orchestrator and keeps a clo { ...finished, hasPendingUserInput: true }, reviewer, root, - owner, + { ...owner, pendingBackgroundTasks: [] }, archived, ]); await screen.rerender(tree("remount")); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 5ae05be9794eb..6106d5b201302 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1743,14 +1743,20 @@ describe("resolveSidebarAgentState", () => { }); describe("formatSidebarAgentStates", () => { - it("joins the non-zero states in a fixed order", () => { - expect(formatSidebarAgentStates({ working: 2, attention: 1, failed: 1 })).toBe( - "2 working · 1 waiting on you · 1 failed", - ); - expect(formatSidebarAgentStates({ working: 3, attention: 1, failed: 0 }, undefined, true)).toBe( - "3 working · 1 waiting", - ); - expect(formatSidebarAgentStates({ working: 0, attention: 0, failed: 0 })).toBe(""); + it("keeps the icon count and accessible label separate from waiting and failed text", () => { + expect(formatSidebarAgentStates({ working: 2, attention: 1, failed: 1 })).toEqual({ + working: { count: 2, label: "2 working" }, + details: "1 waiting on you · 1 failed", + text: "2 working · 1 waiting on you · 1 failed", + }); + expect( + formatSidebarAgentStates({ working: 3, attention: 1, failed: 0 }, undefined, true).text, + ).toBe("3 working · 1 waiting"); + expect(formatSidebarAgentStates({ working: 0, attention: 0, failed: 0 })).toEqual({ + working: null, + details: "", + text: "", + }); }); }); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e6446716b4940..4571891be95d3 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -278,7 +278,7 @@ import { import { SidebarProjectSectionHeader, SidebarProjectSectionNameDialog, - SidebarRoleSectionHeader, + SidebarAgentSectionHeader, } from "./sidebar/SidebarProjectSections"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; import { TooltipScrollDismissArea } from "./ui/tooltip"; @@ -298,11 +298,13 @@ import { import { indexSidebarChildren, sidebarFamilyRows, + sidebarOrphanAgents, groupSidebarThreadsByProject, projectSectionRows, type SidebarFamilyItem, type SidebarFamilyRow, } from "@t3tools/client-runtime/state/sidebar-families"; +import { useSidebarSectionExpansion } from "./sidebar/sidebarSectionExpansion"; import { setSidebarFamilyExpanded, sidebarFamilyExpansion } from "./sidebar/sidebarFamilies"; import { draftTerminalLabel, @@ -378,10 +380,6 @@ const SETTLED_TAIL_PAGE_COUNT = 25; const SETTLED_SHELF_EXPANDED_KEY = "t3code:sidebar:settled-expanded"; const SNOOZED_SHELF_EXPANDED_KEY = "t3code:sidebar:snoozed-expanded"; const WORKING_SHELF_EXPANDED_KEY = "t3code:sidebar:working-expanded"; -const ROLE_SECTIONS_COLLAPSED_KEY = "t3code:sidebar:role-sections-collapsed"; -const TASK_SECTIONS_EXPANDED_KEY = "t3code:sidebar:task-sections-expanded"; -const EMPTY_ROLE_SECTION_KEYS: readonly string[] = []; -const ROLE_SECTION_KEYS_SCHEMA = Schema.Array(Schema.String); function sidebarTextSize(size: number | null) { return size === null ? undefined : `${size / 16}rem`; @@ -478,6 +476,7 @@ function useSidebarThreads(input: { readonly departingThreadKey: string | null; // Set in project mode: the project groups to fold threads into, in order. readonly folderGroups: readonly SidebarProjectSnapshot[] | null; + readonly sectionExpanded: (key: string) => boolean; readonly projectLayouts: Layouts; readonly collapseOverrides: ReadonlyMap; readonly onChangeFolderExpansion: (group: SidebarProjectSnapshot, expanded: boolean) => boolean; @@ -496,6 +495,7 @@ function useSidebarThreads(input: { routeRowThreadKey, departingThreadKey, folderGroups, + sectionExpanded, projectLayouts, collapseOverrides, onChangeFolderExpansion, @@ -587,19 +587,26 @@ function useSidebarThreads(input: { : routeThreadOnly(workingThreads, routeRowThreadKey); const pinnedThreadKeys = new Set(pinnedThreads.map(threadShellKey)); const childrenByParent = indexSidebarChildren(threads, delegatedUnderParent); - const [collapsedRoleSections, setCollapsedRoleSections] = useLocalStorage( - ROLE_SECTIONS_COLLAPSED_KEY, - EMPTY_ROLE_SECTION_KEYS, - ROLE_SECTION_KEYS_SCHEMA, + const orphanAgents = + folderGroups === null ? EMPTY_THREADS : sidebarOrphanAgents(threads, childrenByParent); + const orphanKeys = new Set(orphanAgents.map(threadShellKey)); + const folderRouteKey = + routeThreadKey !== null && orphanKeys.has(routeThreadKey) ? routeThreadKey : routeRowThreadKey; + const folderOrphans = orphanAgents.filter( + (thread) => !pinnedThreadKeys.has(threadShellKey(thread)), ); const projectFolders = folderGroups === null ? null : groupSidebarThreadsByProject( folderGroups, - partition.visibleThreads.filter( - (thread) => !pinnedThreadKeys.has(threadShellKey(thread)), - ), + [ + ...partition.visibleThreads.filter((thread) => { + const key = threadShellKey(thread); + return !pinnedThreadKeys.has(key) && !orphanKeys.has(key); + }), + ...folderOrphans, + ], keepEmpty, ).map((folder) => { const sharedExpansion = folder.group.memberProjectRefs.flatMap( @@ -622,9 +629,14 @@ function useSidebarThreads(input: { ? threads.flatMap((thread) => childrenByParent.get(threadShellKey(thread)) ?? []) : EMPTY_THREADS, // A closed folder still shows the open thread, and hints at the rest. - threads: collapsed ? routeThreadOnly(threads, routeRowThreadKey) : threads, + threads: collapsed + ? routeThreadOnly(threads, folderRouteKey) + : threads.filter((thread) => !orphanKeys.has(threadShellKey(thread))), + agents: collapsed + ? EMPTY_THREADS + : threads.filter((thread) => orphanKeys.has(threadShellKey(thread))), hiddenThreads: collapsed - ? threads.filter((thread) => threadShellKey(thread) !== routeRowThreadKey) + ? threads.filter((thread) => threadShellKey(thread) !== folderRouteKey) : EMPTY_THREADS, }; }); @@ -676,9 +688,34 @@ function useSidebarThreads(input: { visibleChildren, familyExpansion, routeThreadKey, - (key) => !collapsedRoleSections.includes(key), + sectionExpanded, + projectRows === null + ? undefined + : new Map( + projectRows.flatMap((row) => + row.kind === "folder" + ? [[sidebarFolderRowId(row.folder.group.projectKey), row.folder.agents] as const] + : [], + ), + ), ); - const visibleFamilyRows = [...familyRows.values()].flat().filter((row) => row.kind === "thread"); + const familyOrder = + projectRows === null + ? orderedThreads.map(threadShellKey) + : [ + ...pinnedThreads.map(threadShellKey), + ...projectRows.flatMap((row) => + row.kind === "folder" + ? [ + ...row.folder.threads.map(threadShellKey), + sidebarFolderRowId(row.folder.group.projectKey), + ] + : [], + ), + ]; + const visibleFamilyRows = familyOrder + .flatMap((key) => familyRows.get(key) ?? []) + .filter((row) => row.kind === "thread"); const orderedThreadKeys = visibleFamilyRows.map((row) => row.key); const threadByKey = new Map(visibleFamilyRows.map((row) => [row.key, row.thread])); const settledThreadKeys = new Set(settledThreads.map(threadShellKey)); @@ -739,10 +776,6 @@ function useSidebarThreads(input: { visibleWorkingThreads, familyRows, agentCountByKey: childrenByParent, - toggleRoleSection: (key: string) => - setCollapsedRoleSections((current) => - current.includes(key) ? current.filter((entry) => entry !== key) : [...current, key], - ), orderedThreadKeys, threadByKey, settledThreadKeys, @@ -1259,11 +1292,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), ); const threads = useQuietThreadShells(); - const [expandedTaskSections, setExpandedTaskSections] = useLocalStorage( - TASK_SECTIONS_EXPANDED_KEY, - EMPTY_ROLE_SECTION_KEYS, - ROLE_SECTION_KEYS_SCHEMA, - ); + const { sectionExpanded, toggleSection } = useSidebarSectionExpansion(); const taskEnvironmentIds = [...new Set(threads.map((thread) => thread.environmentId))]; const runningTerminals = useRunningTerminalsByThreadKey(taskEnvironmentIds); const workflowRuns = useSidebarWorkflowRuns(taskEnvironmentIds); @@ -1626,7 +1655,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve visibleWorkingThreads, familyRows, agentCountByKey, - toggleRoleSection, orderedThreadKeys, threadByKey, settledThreadKeys, @@ -1672,6 +1700,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } return true; }, + sectionExpanded, folderGroups: boringSidebarEnabled ? scopedProjectGroups.length === 0 ? // An archived project keeps a folder for its active threads, below the rest. @@ -4047,17 +4076,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve folderRow?: string, folderDepth = 0, ) => - item.kind === "role" ? ( - ) : ( renderThreadRow( @@ -4171,6 +4200,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), )} , + ...(familyRows.get(folderRow) ?? []).map((item) => + renderFamilyItem(item, "active", folderRow, row.depth), + ), ...(!folder.collapsed && tasks.length > 0 ? [ - setExpandedTaskSections((current) => - current.includes(folderRow) - ? current.filter((key) => key !== folderRow) - : [...current, folderRow], - ) - } + collapsed={!sectionExpanded(`tasks:${folderRow}`)} + onToggle={toggleSection} onOpen={(task) => { const ref = scopeThreadRef( task.thread.environmentId, diff --git a/apps/web/src/components/sidebar/SidebarCollapsibleSection.tsx b/apps/web/src/components/sidebar/SidebarCollapsibleSection.tsx new file mode 100644 index 0000000000000..ac3227b7395d6 --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarCollapsibleSection.tsx @@ -0,0 +1,37 @@ +import { ChevronDownIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +import { cn } from "../../lib/utils"; + +export function SidebarCollapsibleSection(props: { + readonly id: string; + readonly parent: string; + readonly depth: number; + readonly familyDepth?: number; + readonly collapsed: boolean; + readonly onToggle: (id: string, all: boolean) => void; + readonly label: string; + readonly children: ReactNode; + readonly testId?: string; +}) { + const offset = Math.min(props.depth, 3) * 10 + (props.familyDepth ?? 0) * 12; + return ( + + ); +} diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx index 93ec5e8c8419c..aac88558115fe 100644 --- a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx @@ -60,7 +60,7 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead const { group, collapsed, hiddenThreads, hiddenAgents } = props; const hiddenWork = hiddenAgents.length === 0 ? hiddenThreads : [...hiddenThreads, ...hiddenAgents]; - const summary = useSidebarAgentStateSummary(collapsed ? hiddenWork : [], true); + const { text: summary } = useSidebarAgentStateSummary(collapsed ? hiddenWork : [], true); const rowId = sidebarFolderRowId(group.projectKey); const localLastVisitedAtById = useUiStateStore((state) => state.threadLastVisitedAtById); const dot = collapsed diff --git a/apps/web/src/components/sidebar/SidebarProjectSections.tsx b/apps/web/src/components/sidebar/SidebarProjectSections.tsx index 21c8f1f622003..8fca281e440b7 100644 --- a/apps/web/src/components/sidebar/SidebarProjectSections.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectSections.tsx @@ -4,6 +4,7 @@ import { countSidebarAgentStates, formatSidebarAgentStates, sidebarRoleSectionLabels, + sidebarAgentsSectionLabel, type SidebarAgentRole, } from "@t3tools/client-runtime/state/sidebar-families"; import type { ContextMenuSource } from "@t3tools/contracts"; @@ -25,6 +26,8 @@ import { DialogTitle, } from "../ui/dialog"; import { Input } from "../ui/input"; +import { SidebarCollapsibleSection } from "./SidebarCollapsibleSection"; +import { TopStatusIcon } from "./SidebarThreadRow"; export function SidebarProjectSectionHeader(props: { id: string; @@ -89,42 +92,47 @@ export function useSidebarAgentStateSummary( return formatSidebarAgentStates(counts, messages, short); } -export const SidebarRoleSectionHeader = memo(function SidebarRoleSectionHeader(props: { +export const SidebarAgentSectionHeader = memo(function SidebarAgentSectionHeader(props: { id: string; - role: SidebarAgentRole; + role?: SidebarAgentRole; parent: string; depth: number; familyDepth: number; collapsed: boolean; threads: readonly EnvironmentThreadShell[]; - onToggle: (sectionKey: string) => void; + onToggle: (id: string, all: boolean) => void; }) { const messages = useMessages(); - const summary = useSidebarAgentStateSummary(props.threads); + const { working, details } = useSidebarAgentStateSummary(props.threads); return (
  • - + + {working && ( + + {working.label} + + {working.count} + + )} + {working && details && ·} + {details && {details}} + +
  • ); }); diff --git a/apps/web/src/components/sidebar/SidebarProjectTasks.tsx b/apps/web/src/components/sidebar/SidebarProjectTasks.tsx index e8d9913af6f1e..da678b95de25f 100644 --- a/apps/web/src/components/sidebar/SidebarProjectTasks.tsx +++ b/apps/web/src/components/sidebar/SidebarProjectTasks.tsx @@ -1,7 +1,7 @@ import type { ProjectTask, ProjectTaskKind } from "@t3tools/client-runtime/state/project-tasks"; -import { ChevronDownIcon, MonitorIcon, TerminalIcon, WorkflowIcon } from "lucide-react"; +import { MonitorIcon, TerminalIcon, WorkflowIcon } from "lucide-react"; import { msg, useGT, useMessages } from "gt-react"; -import { cn } from "../../lib/utils"; +import { SidebarCollapsibleSection } from "./SidebarCollapsibleSection"; const sections: readonly { kind: ProjectTaskKind; label: string }[] = [ { kind: "commands", label: msg("Commands", { $context: "project tasks subsection" }) }, @@ -17,7 +17,7 @@ export function SidebarProjectTasks(props: { readonly tasks: readonly ProjectTask[]; readonly now: number; readonly collapsed: boolean; - readonly onToggle: () => void; + readonly onToggle: (id: string, all: boolean) => void; readonly onOpen: (task: ProjectTask) => void; }) { const gt = useGT(); @@ -26,21 +26,18 @@ export function SidebarProjectTasks(props: { const inset = `calc(var(--sidebar-row-content-inset) + 16px + ${Math.min(props.depth, 3) * 10}px)`; return (
  • - + {!props.collapsed && sections.map((section) => { const tasks = props.tasks.filter((task) => task.kind === section.kind); diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index 91f7fe206d825..fc7d0f49ff029 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -1,5 +1,5 @@ -import { useGT } from "gt-react"; -import { SearchIcon, SquarePenIcon, XIcon } from "lucide-react"; +import { useGT, useMessages } from "gt-react"; +import { EllipsisIcon, SearchIcon, SquarePenIcon, XIcon } from "lucide-react"; import { type ComponentProps, type KeyboardEvent as ReactKeyboardEvent, @@ -11,6 +11,12 @@ import { import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; import { SidebarInput, SidebarMenuButton } from "../ui/sidebar"; +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; +import { + collapseSidebarSectionsLabel, + expandSidebarSectionsLabel, + setAllSidebarSectionsExpanded, +} from "./sidebarSectionExpansion"; import { SharedTooltipTrigger } from "../ui/shared-tooltip"; export interface SidebarThreadHeaderProps { @@ -49,6 +55,7 @@ export function SidebarThreadHeader({ onClearSearch, }: SidebarThreadHeaderProps) { const gt = useGT(); + const messages = useMessages(); const resultsVisible = isSearching && searchResultCount > 0; // Shrinking results can remove the active option; never leave aria-activedescendant pointing at it. const activeResultExists = resultsVisible && activeSearchResultIndex < searchResultCount; @@ -98,6 +105,21 @@ export function SidebarThreadHeader({
    {hasProjects ? projectScope : null} + {hasProjects ? ( + + }> + + + + setAllSidebarSectionsExpanded(false)}> + {messages(collapseSidebarSectionsLabel)} + + setAllSidebarSectionsExpanded(true)}> + {messages(expandSidebarSectionsLabel)} + + + + ) : null} ({ + allExpanded, + overrides: {}, +}); +const initial = allSections(null); +const legacySchema = Schema.Array(Schema.String); +const emptyKeys: readonly string[] = []; + +export const collapseSidebarSectionsLabel = msg("Collapse all agent and task sections"); +export const expandSidebarSectionsLabel = msg("Expand all agent and task sections"); + +export function setAllSidebarSectionsExpanded(expanded: boolean) { + writeLocalStorageValue(key, allSections(expanded), initial, schema); +} + +export function useSidebarSectionExpansion() { + const [state, setState] = useLocalStorage(key, initial, schema); + const [collapsedRoles] = useLocalStorage( + "t3code:sidebar:role-sections-collapsed", + emptyKeys, + legacySchema, + ); + const [expandedTasks] = useLocalStorage( + "t3code:sidebar:task-sections-expanded", + emptyKeys, + legacySchema, + ); + + function defaultExpanded(id: string) { + if (id.startsWith("tasks:")) return expandedTasks.includes(id.slice("tasks:".length)); + return !collapsedRoles.includes(id); + } + + function isExpanded(current: SectionExpansion, id: string) { + return current.overrides[id] ?? current.allExpanded ?? defaultExpanded(id); + } + + function toggleSection(id: string, all: boolean) { + setState((current) => { + const expanded = !isExpanded(current, id); + return all + ? allSections(expanded) + : { ...current, overrides: { ...current.overrides, [id]: expanded } }; + }); + } + + return { sectionExpanded: (id: string) => isExpanded(state, id), toggleSection }; +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 99bd1a15a5e2d..ee7aaad07aea9 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -13085,5 +13085,9 @@ "b7df38b7d8792d78": "Leitfaden öffnen", "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", "ee71ac7e8e9b000c": "Ultrafast-Modus an", - "e649c08fbd9a1a30": "Fast-Modus an" + "e649c08fbd9a1a30": "Fast-Modus an", + "99d122b4ef1f6aa4": "Agenten", + "55556e217edef043": "Sidebar-Optionen", + "c3d3392960181c62": "Alle Agenten- und Aufgabenbereiche einklappen", + "dbac868688de3988": "Alle Agenten- und Aufgabenbereiche ausklappen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index b5f26da1032e3..c27006997224e 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -13094,5 +13094,9 @@ "b7df38b7d8792d78": "Open guide", "9e91e9a77b664e4e": "Could not start a review guide", "ee71ac7e8e9b000c": "Ultrafast mode on", - "e649c08fbd9a1a30": "Fast mode on" + "e649c08fbd9a1a30": "Fast mode on", + "99d122b4ef1f6aa4": "Agents", + "55556e217edef043": "Sidebar options", + "c3d3392960181c62": "Collapse all agent and task sections", + "dbac868688de3988": "Expand all agent and task sections" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index b741518ccbf76..e2d95affffa41 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -13080,5 +13080,9 @@ "b7df38b7d8792d78": "Abrir guía", "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", "ee71ac7e8e9b000c": "Modo Ultrafast activado", - "e649c08fbd9a1a30": "Modo rápido activado" + "e649c08fbd9a1a30": "Modo rápido activado", + "99d122b4ef1f6aa4": "Agentes", + "55556e217edef043": "Opciones de la barra lateral", + "c3d3392960181c62": "Contraer todas las secciones de agentes y tareas", + "dbac868688de3988": "Expandir todas las secciones de agentes y tareas" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index de03939589878..a0bc1dc406586 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -13085,5 +13085,9 @@ "b7df38b7d8792d78": "Ouvrir le guide", "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", "ee71ac7e8e9b000c": "Mode Ultrafast activé", - "e649c08fbd9a1a30": "Mode Fast activé" + "e649c08fbd9a1a30": "Mode Fast activé", + "99d122b4ef1f6aa4": "Agents", + "55556e217edef043": "Options de la barre latérale", + "c3d3392960181c62": "Réduire toutes les sections d’agents et de tâches", + "dbac868688de3988": "Développer toutes les sections d’agents et de tâches" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index e8d1700f2dd4c..e80ecf97c75b2 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -13021,5 +13021,9 @@ "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", "ee71ac7e8e9b000c": "超高速モード オン", - "e649c08fbd9a1a30": "高速モード オン" + "e649c08fbd9a1a30": "高速モード オン", + "99d122b4ef1f6aa4": "エージェント", + "55556e217edef043": "サイドバーのオプション", + "c3d3392960181c62": "すべてのエージェントとタスクのセクションを折りたたむ", + "dbac868688de3988": "すべてのエージェントとタスクのセクションを展開する" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c4ed9a5462c52..573b2fb841125 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -13018,5 +13018,9 @@ "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", "ee71ac7e8e9b000c": "초고속 모드 켜짐", - "e649c08fbd9a1a30": "고속 모드 켜짐" + "e649c08fbd9a1a30": "고속 모드 켜짐", + "99d122b4ef1f6aa4": "에이전트", + "55556e217edef043": "사이드바 옵션", + "c3d3392960181c62": "모든 에이전트 및 작업 섹션 접기", + "dbac868688de3988": "모든 에이전트 및 작업 섹션 펼치기" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index ac50f963f4ee5..3fdaa7b78a569 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -13085,5 +13085,9 @@ "b7df38b7d8792d78": "Abrir guia", "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", "ee71ac7e8e9b000c": "Modo Ultrafast ativado", - "e649c08fbd9a1a30": "Modo Fast ativado" + "e649c08fbd9a1a30": "Modo Fast ativado", + "99d122b4ef1f6aa4": "Agentes", + "55556e217edef043": "Opções da barra lateral", + "c3d3392960181c62": "Recolher todas as seções de agentes e tarefas", + "dbac868688de3988": "Expandir todas as seções de agentes e tarefas" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0b55b34e4f297..036acdb05a06c 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -13085,5 +13085,9 @@ "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", "ee71ac7e8e9b000c": "Сверхбыстрый режим включён", - "e649c08fbd9a1a30": "Быстрый режим включён" + "e649c08fbd9a1a30": "Быстрый режим включён", + "99d122b4ef1f6aa4": "Агенты", + "55556e217edef043": "Настройки боковой панели", + "c3d3392960181c62": "Свернуть все разделы агентов и задач", + "dbac868688de3988": "Развернуть все разделы агентов и задач" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 86a93ee99f507..f3e74fc6ec625 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -13092,5 +13092,9 @@ "b7df38b7d8792d78": "Öppna guiden", "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", "ee71ac7e8e9b000c": "Ultrasnabbt läge på", - "e649c08fbd9a1a30": "Snabbläge på" + "e649c08fbd9a1a30": "Snabbläge på", + "99d122b4ef1f6aa4": "Agenter", + "55556e217edef043": "Alternativ för sidofältet", + "c3d3392960181c62": "Fäll ihop alla agent- och uppgiftsavsnitt", + "dbac868688de3988": "Fäll ut alla agent- och uppgiftsavsnitt" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index bb810e960209c..48605deb098ae 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -13099,5 +13099,9 @@ "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", "ee71ac7e8e9b000c": "极速模式已开启", - "e649c08fbd9a1a30": "快速模式已开启" + "e649c08fbd9a1a30": "快速模式已开启", + "99d122b4ef1f6aa4": "智能体", + "55556e217edef043": "侧边栏选项", + "c3d3392960181c62": "折叠所有智能体和任务分区", + "dbac868688de3988": "展开所有智能体和任务分区" } diff --git a/packages/client-runtime/src/state/sidebarFamilies.test.ts b/packages/client-runtime/src/state/sidebarFamilies.test.ts index bc56f06161eb7..612ba5b434173 100644 --- a/packages/client-runtime/src/state/sidebarFamilies.test.ts +++ b/packages/client-runtime/src/state/sidebarFamilies.test.ts @@ -6,6 +6,7 @@ import { countSidebarAgentStates, groupSidebarThreadsByProject, sidebarFamilyRows, + sidebarOrphanAgents, indexSidebarChildren, } from "./sidebarFamilies.ts"; @@ -67,20 +68,22 @@ it("keeps each orchestrator's role sections and each worker's native children to "env:first", [ ["env:first", undefined, 0], - ["role:env:first:implementation", "env:first", 1], - ["env:new-impl", "role:env:first:implementation", 2], - ["env:/root/native", "env:new-impl", 3], - ["env:old-impl", "role:env:first:implementation", 2], - ["role:env:first:review", "env:first", 1], - ["env:review", "role:env:first:review", 2], + ["agents:env:first", "env:first", 1], + ["role:env:first:implementation", "agents:env:first", 2], + ["env:new-impl", "role:env:first:implementation", 3], + ["env:/root/native", "env:new-impl", 4], + ["env:old-impl", "role:env:first:implementation", 3], + ["role:env:first:review", "agents:env:first", 2], + ["env:review", "role:env:first:review", 3], ], ], [ "env:second", [ ["env:second", undefined, 0], - ["role:env:second:implementation", "env:second", 1], - ["env:other-impl", "role:env:second:implementation", 2], + ["agents:env:second", "env:second", 1], + ["role:env:second:implementation", "agents:env:second", 2], + ["env:other-impl", "role:env:second:implementation", 3], ], ], ["env:owner", [["env:owner", undefined, 0]]], @@ -88,10 +91,21 @@ it("keeps each orchestrator's role sections and each worker's native children to expect(rows(new Map(expanded).set("env:first", false))[0]?.[1]).toEqual([ ["env:first", undefined, 0], ]); - expect(rows(expanded, "role:env:first:implementation")[1]).toEqual(rows()[1]); + expect(rows(expanded, "role:env:first:implementation")[0]?.[1]).toEqual([ + ["env:first", undefined, 0], + ["agents:env:first", "env:first", 1], + ["role:env:first:implementation", "agents:env:first", 2], + ["role:env:first:review", "agents:env:first", 2], + ["env:review", "role:env:first:review", 3], + ]); + expect(rows(expanded, "agents:env:first")[0]?.[1]).toEqual([ + ["env:first", undefined, 0], + ["agents:env:first", "env:first", 1], + ]); + expect(rows(expanded, "agents:env:first")[1]).toEqual(rows()[1]); }); -it("can group linked agents when the parent's environment is absent", () => { +it("puts agents with missing or archived parents under the project Agents row", () => { const linked = { ...thread("linked", { role: "review" }), delegatedFrom: { @@ -100,8 +114,29 @@ it("can group linked agents when the parent's environment is absent", () => { title: "Parent", }, }; - expect(indexSidebarChildren([linked]).get("remote:parent")).toEqual([linked]); - expect(indexSidebarChildren([linked], new Set()).size).toBe(0); + const owner = thread("owner"); + const archived = thread("archived", { archived: true }); + const orphan = thread("orphan", { parent: "archived", role: "implementation" }); + const attached = thread("attached", { parent: "owner", role: "implementation" }); + const threads = [owner, archived, orphan, linked, attached]; + const children = indexSidebarChildren(threads); + const orphans = sidebarOrphanAgents(threads, children); + expect(orphans).toEqual([orphan, linked]); + + const project = "folder:app"; + const projectAgents = new Map([[project, orphans]]); + const keys = (expanded: boolean) => + sidebarFamilyRows([], children, new Map(), null, () => expanded, projectAgents) + .get(project) + ?.map(({ key, parentKey }) => [key, parentKey]); + expect(keys(true)).toEqual([ + ["agents:folder:app", project], + ["role:folder:app:implementation", "agents:folder:app"], + ["env:orphan", "role:folder:app:implementation"], + ["role:folder:app:review", "agents:folder:app"], + ["env:linked", "role:folder:app:review"], + ]); + expect(keys(false)).toEqual([["agents:folder:app", project]]); }); describe("countSidebarAgentStates", () => { diff --git a/packages/client-runtime/src/state/sidebarFamilies.ts b/packages/client-runtime/src/state/sidebarFamilies.ts index 3dcc98be8aba9..6fa05ca6126c0 100644 --- a/packages/client-runtime/src/state/sidebarFamilies.ts +++ b/packages/client-runtime/src/state/sidebarFamilies.ts @@ -40,6 +40,35 @@ export function indexSidebarChildren( return children; } +function sidebarThreadKey(thread: EnvironmentThreadShell) { + return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); +} + +export function sidebarOrphanAgents( + threads: readonly EnvironmentThreadShell[], + childrenByParent: ReadonlyMap, +) { + const activeKeys = new Set( + threads.filter((thread) => thread.archivedAt === null).map(sidebarThreadKey), + ); + const attached = new Set(); + for (const [parent, children] of childrenByParent) { + if (activeKeys.has(parent)) { + for (const child of children) attached.add(sidebarThreadKey(child)); + } + } + return threads.filter( + (thread) => + thread.archivedAt === null && + !thread.lineage.sideChat && + !thread.lineage.workflowStep && + (thread.lineage.relationshipToParent === "subagent" || + thread.delegatedFrom != null || + thread.delegatedRole !== undefined) && + !attached.has(sidebarThreadKey(thread)), + ); +} + export interface SidebarFamilyRow { kind: "thread"; thread: EnvironmentThreadShell; @@ -55,7 +84,8 @@ export function sidebarFamilyRows( childrenByParent: ReadonlyMap, expansion: ReadonlyMap, routeKey: string | null, - roleExpanded: (key: string) => boolean, + sectionExpanded: (key: string) => boolean, + projectAgents?: ReadonlyMap, ) { type FamilyNode = { row: SidebarFamilyRow; @@ -64,18 +94,16 @@ export function sidebarFamilyRows( hasRoute: boolean; }; - function build(thread: EnvironmentThreadShell, parentKey?: string): FamilyNode { - const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - const children: FamilyNode[] = (childrenByParent.get(key) ?? []).map((child) => - build(child, key), - ); + function build(thread: EnvironmentThreadShell): FamilyNode { + const key = sidebarThreadKey(thread); + const children = (childrenByParent.get(key) ?? []).map((child) => build(child)); const hasLiveChildren = children.some((child) => child.live); const hasChildRoute = children.some((child) => child.hasRoute); const row: SidebarFamilyRow = { kind: "thread", thread, key, - parentKey, + parentKey: undefined, depth: 0, descendantCount: children.reduce((count, child) => count + 1 + child.row.descendantCount, 0), expanded: expansion.get(key) ?? (hasLiveChildren || hasChildRoute), @@ -97,40 +125,66 @@ export function sidebarFamilyRows( function flatten( node: FamilyNode, depth = 0, - parentKey = node.row.parentKey, + parentKey?: string, + agent = false, ): SidebarFamilyItem[] { const { row, children } = node; const result: SidebarFamilyItem[] = [{ ...row, depth, parentKey }]; if (!row.expanded) return result; - if (row.thread.lineage.parentThreadId !== null || row.thread.delegatedFrom != null) { - return result.concat(children.flatMap((child) => flatten(child, depth + 1))); + if (agent) { + return result.concat(children.flatMap((child) => flatten(child, depth + 1, row.key, true))); } - for (const section of sidebarRoleSections(row.key, children)) { - const expanded = roleExpanded(section.key); + return result.concat(flattenAgents(row.key, children, depth + 1)); + } + + function flattenAgents(parentKey: string, children: FamilyNode[], depth: number) { + if (children.length === 0) return []; + const key = `agents:${parentKey}`; + const expanded = sectionExpanded(key); + const result: SidebarFamilyItem[] = [ + { + kind: "agents", + key, + parentKey, + depth, + threads: children.map((child) => child.row.thread), + expanded, + }, + ]; + for (const section of sidebarRoleSections(parentKey, children)) { + if (!expanded && !section.children.some((child) => child.hasRoute)) continue; + const roleExpanded = sectionExpanded(section.key); result.push({ kind: "role", key: section.key, - parentKey: row.key, + parentKey: key, depth: depth + 1, role: section.role, threads: section.children.map((child) => child.row.thread), - expanded, + expanded: roleExpanded, }); for (const child of section.children) { - if (expanded || child.hasRoute) { - result.push(...flatten(child, depth + 2, section.key)); + if ((expanded && roleExpanded) || child.hasRoute) { + result.push(...flatten(child, depth + 2, section.key, true)); } } } return result; } - return new Map( + const rows = new Map( roots.map((thread) => { const node = build(thread); - return [node.row.key, flatten(node)] as const; + const isAgent = thread.lineage.parentThreadId !== null || thread.delegatedFrom != null; + return [node.row.key, flatten(node, 0, undefined, isAgent)] as const; }), ); + if (projectAgents) { + for (const [key, threads] of projectAgents) { + rows.set(key, flattenAgents(key, threads.map(build), 0)); + } + } + return rows; } const SIDEBAR_AGENT_ROLES = [ @@ -151,15 +205,13 @@ function sidebarAgentRole(thread: Pick) export type SidebarFamilyItem = | SidebarFamilyRow - | { - kind: "role"; + | ({ key: string; parentKey: string; depth: number; - role: SidebarAgentRole; threads: readonly EnvironmentThreadShell[]; expanded: boolean; - }; + } & ({ kind: "agents" } | { kind: "role"; role: SidebarAgentRole })); function sidebarRoleSections( parentKey: string, @@ -236,24 +288,32 @@ export function sidebarAgentState( } } -/** "2 working · 1 waiting on you · 1 failed", leaving out zeros; `short` says "waiting". */ export function formatSidebarAgentStates( counts: Readonly>, resolve: MFunctionType = mFallback, short = false, -): string { - const parts = [ - counts.working > 0 ? resolve(msg("{count} working", { count: counts.working })) : null, +) { + const working = + counts.working > 0 + ? { count: counts.working, label: resolve(msg("{count} working", { count: counts.working })) } + : null; + const details = [ counts.attention > 0 ? short ? resolve(msg("{count} waiting", { count: counts.attention })) : resolve(msg("{count} waiting on you", { count: counts.attention })) : null, counts.failed > 0 ? resolve(msg("{count} failed", { count: counts.failed })) : null, - ]; - return parts.filter((part) => part !== null).join(" · "); + ] + .filter((part) => part !== null) + .join(" · "); + return { working, details, text: [working?.label, details].filter(Boolean).join(" · ") }; } +export const sidebarAgentsSectionLabel = msg("Agents", { + $context: "sidebar section for agent threads", +}); + /** * Boring sidebar folders. Folders follow `groups` order and threads keep their * input order. A project with no threads gets a folder only when `keepEmpty` says so.