Repository navigation
feat(site/src): render the chat tree sidebar and relayed messages behind the chat-tree experiment - #29618
Closed
jscottmiller wants to merge 6 commits into
Closed
feat(site/src): render the chat tree sidebar and relayed messages behind the chat-tree experiment#29618jscottmiller wants to merge 6 commits into
jscottmiller wants to merge 6 commits into
Conversation
jscottmiller
force-pushed
the
scott/chat-tree/3-messaging
branch
from
September 20, 2026 20:09
db5fcbd to
3e72a00
Compare
added 6 commits
September 20, 2026 20:11
Named child chats carry parent_chat_id but are not subagents, so the actions menu, top bar sharing gate, and cost tree id must use kind instead of inferring subagent from the parent link. Root chats hide pin and archive actions.
Adds the organization chat tree endpoint client, a query factory keyed outside the flat list family, and cache helpers that keep tree rows in sync with watch events and the pin, archive, and rename mutations.
…storage Pure modules for the tree sidebar: builds the hierarchy from tree responses per organization, flattens visible rows for rendering and keyboard navigation, implements the WAI-ARIA tree key pattern, and persists expansion and subagent visibility per node.
…eriment With the chat-tree experiment on, the agents sidebar replaces the flat list with an organization tree fed by the tree endpoint: WAI-ARIA tree semantics with roving focus, persisted expansion, per node subagent toggles, pinned and shared sections, unread filtering that keeps ancestors visible, a New chat here action that routes through the composer, and an archive confirmation that explains the cascade. The experiment-off path is unchanged and issues no tree request.
…nd chat tree tool calls User rows delivered by another chat's agent get a provenance header linking to the sender with its relation and relay hop, a distinct border, and no edit affordance; queued previews carry the same prefix. Adds renderers, icons, and stories for the send_chat_message and list_chat_tree tool calls.
jscottmiller
force-pushed
the
scott/chat-tree/4-ui
branch
from
September 20, 2026 20:11
0dcadf7 to
924178a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Behind the
chat-treeexperiment, the agents sidebar renders the owner's chats as a tree fed byGET /organizations/{org}/chats/tree(one query per organization, the flat list kept only for chats shared with the viewer), and the transcript renders PR3's relayed rows and thesend_chat_message/list_chat_treetool calls. With the experiment off the sidebar, the create form, and the transcript are unchanged and no tree endpoint is called. Stacked on #29617 (scott/chat-tree/3-messaging), which sits on #29615 and #29614.The tree is a WAI-ARIA navigation treeview: the row anchor is the
treeitem(client-derivedaria-level, filter-awarearia-setsize/aria-posinset,aria-expanded,aria-current="page"for the open chat), children sit inrole="group", one roving tab stop, arrow keys, Home/End,*, and type-ahead through a pure reducer. Expansion and per-node "Show subagents" are persisted inagents.chat-tree-expanded; ancestors of the open chat expand once per navigation. Pinned chats stay a flat section above the tree (dnd-kit reordering kept, grip handle isolated from the row link); shared chats are a flat section below it. The unread/read filter is a client-side predicate that keeps matching nodes and their ancestors (ancestors dimmed and force-expanded);groupByand PR-status filters are hidden in tree mode because tree rows carry nodiff_status. "New chat here" routes to the composer with router state and shows a dismissible "New chat under <title>" chip; the parent id is sent only when the parent's organization is available to the form. Archiving a chat with named descendants asks for confirmation in the layout, so the top bar and the tree share one dialog. Tree cache maintenance (watch events, optimistic pin/rename/archive/reorder patches, refetch cancellation) lives inapi/queries/chats.tsunder a key family that never overlaps the list caches.The first commit fixes three PR1/PR2 sweep misses in existing components that inferred "subagent" from
parent_chat_id(ChatActionsMenuItems,ChatTopBar,getChatCostTreeID); with the experiment on every adopted chat has a parent, so those gates hid pin, archive, and share for all user chats. The last commit applies the diff panel review (table below).Notes for reviewers:
diff_status(no PR badges or PR filter in tree mode) and nosubagent_count(the "Show subagents" toggle is offered on every named node without a count, and subagents are fetched per toggled node throughGET /chats/{id}).SortableChatTreeNode(experiment off) still starts a keyboard drag on Enter; the newSortablePinnedChatRowfixes that only for tree mode and is a back-port candidate.frontend-reviewjustifications:ChatActionsMenuItems.test.tsxasserts the set of rendered menu items per chat kind; the item set is the outcome of the kind gate and there is noChatActionsMenuItemsstory to screenshot it. TheRevoked Selection Does Not Resurrectstory inAgentCreateForm.stories.tsxfails locally in this environment with a proxied 502 on the base branch as well; it is not touched by this PR.ChatsPanel: a lingering PR-status filter in the URL now yields "No agents match these filters" plus "Clear filters" in tree mode instead of being ignored.Screenshots (Storybook)
ChatTreePanel/ExpandedChatTreePanel/StatusIndicatorsChatTreePanel/DeepTreeChatTreePanel/DepthLimitDisablesCreateChatTreePanel/ContextMenuOpenChatTreePanel/PinnedSectionChatTreePanel/ArchivedForestChatTreePanel/UnreadFilterDimsAncestorsChatTreePanel/SubagentsShownChatTreePanel/MultipleOrganizationsChatTreePanel/KeyboardFocusRingChatTreePanel/MobileSendChatMessageTool/QueuedSendChatMessageTool/ErrorResultListChatTreeTool/WithParentAndChildrenListChatTreeTool/ErrorResultConversationTimeline/RelayedMessageFromChildAgentCreateForm/WithParentChatAgentCreateForm/WithParentChatInUnavailableOrganizationDiff review dispositions (panel review, applied in the last commit)
N11 rejected; N5 accepted for the persisted preference and rejected for the org-change reset. All others accepted as written.
chats.tsapplyWatchedChatCreatedOrUnarchivedapplyChatArchiveStateToCaches(false)runs before the treecreatedhelper, so the archived-tree probe never sees the row and an unarchive is appended as a new chat withchild_chat_count + 1.cachedChat?.archivedas an unarchive signal; add a wrapper-level test.AgentsPageLayout.tsxmerge pathcancelChatTreeRefetchesbeforemergeWatchedChatIntoCaches; the has_unread effect invalidates every tree on navigation so a stale refetch reliably races the new chat'stitle_change.cancelChatTreeRefetchesnext tocancelChatListRefetchesin the watch handler; drop the later calls inside the helpers.AgentsPageLayout.tsxchatListkind === "root"and sort byupdated_atdesc when buildingchatListin tree mode.chats.tscreateChat.onSuccessinvalidateChatTreeQueries(queryClient, { organizationId }).AgentCreateForm.tsxparent orgparentOrgoverridingeffectiveOrgtriggers the org-change reset and persists the parent's org as the stored preference; dismissing flips back.parentOrgfrom the adopt/persist logic. The workspace/MCP reset on org flip is the same rule as a manual org change and a selection from another org is invalid for the parent's org.AgentsPageLayout.tsxarchive-and-deleteonSuccess/onErrorinvalidate the list but not the tree.invalidateChatTreeQueriesto both.AgentsPageLayout.tsxsidebarLoadErrorchats.tscreated appenddepth: undefined, so the depth limit is not enforced on fresh rows until refetch.depth = parent.depth + 1when the parent carries a depth.createdevents refetch the shared list; cascadedeletedevents restart the archived-tree refetch per member.createdevents in tree mode. The per-member archived invalidation is cheap and kept.AgentCreateForm.tsxpermittedOrgsafter settle still sendsparent_chat_idwith a different organization.parentChatIdinCreateChatOptionsonly whenparentOrgresolved; the page reads it from the options. Show an info alert when the parent's organization is not available.chats.tscancelChatTreeQueriesinonMutateonSettledinvalidation.ChatTreePanel.tsxauto-expansionsetExpansionis called duringChatTreeBody's render but the state belongs toChatTreePanel(React warns and the update is deferred).expansion; the body receives model and expansion as props. Add a Vitest for auto-expansion.ChatTreeRow.tsxactions triggerChatTreePanel.tsxpendingFocuspendingFocusset forever andonMenuCloseAutoFocusthen drops focus to body on every menu close.preventDefaultpath: Radix returns focus to the still-mounted trigger at close time, andFocusAfterRemovalmoves focus once the row is gone. ClearpendingFocuswhen the user focuses another row.ChatTreePanel.tsxFocusAfterRemovalsetPendingFocus, depending on the optimistic removal landing in a later tick.keyboardRowssynchronously inremoveRowWithFocusand store them in the pending state.ChatTreeRow.tsxactions triggeropacity-0until hover means an invisible tappable area on coarse pointers.[@media(hover:hover)]until hover or focus, mirroring the chevron.ChatTreeRow.tsxchevrontabIndex=-1button outside the treeitem, breaking the key handler; a button is not valid tree content.onPointerDownpreventDefault, focus the row's treeitem after toggle,aria-hiddenon the chevron (the treeitem'saria-expandedand the menu's Expand/Collapse cover it).AgentCreateForm.tsxchipsize-6target; move focus to the message textbox on dismiss.onToggleExpandedfor force-expanded rows.treeKeyboard.tsEnteropenbranch is unreachable from the panel.ChatTreePanel.stories.tsxMobilearia-labeltext,aria-disabled, unrelated constant), missing coverage for auto-expansion,*, organization node toggle, Show subagents, dialog cancel focus, new menu items; missing stories for filter-empty, context menu, collapsed organization.ChatTreeRow.tsxicon labelsrole=imgstatus icon prefixes the treeitem name, so type-ahead letters do not match what is announced.aria-hiddenicon plus an sr-only status suffix after the title.ListChatTreeTool.tsxhasContent={!isRunning && !isError}and a failure label; distinguish missing payload fromparent: null.ChatTopBar.tsxarchiverequestArchiveAgent(tree mode,child_chat_count > 0or cached named descendants) so the top bar and the tree share one dialog; the panel keeps only focus handling.child_chat_countincludes archived children, so a collapsed node with only archived children shows "1 chats" with no expander and the confirm prompts for nothing.ChatActionsMenuItems.tsxunarchiveisParentArchivedfrom the row and hide the item.SendChatMessageTool.tsxlabel mapsinand bare indexing on plain-object maps accept prototype keys.Object.hasOwn.ListChatTreeTool.tsxupdated_atTool.tsxSendChatMessageRendererargs.chat_idfor the link, which may be arbitrary model output.AgentsPageLayout.test.tskind: "chat".kind: "subagent".ListChatTreeTool.tsxdetailself.kind ?? "chat"hides a missing field.testHelpers/chatEntities.tsroot_chat_id.root_chat_idto the chat's own id on root/chat fixtures.Implementation plan (chat-tree-ui)
Plan: chat-tree-ui
Project
chat-tree-ui(implement-medium). Repositorycoder/coder, frontend only (site/src).Branch
scott/chat-tree/4-ui, based onscott/chat-tree/3-messaging(PR #29617, head92b9504510;PR #29615 and PR #29614 below it). Draft PR with label
experimentalafter the step 6 checkpoint.Revision 2: incorporates the plan panel review (
REVIEW-plan.md, findings #1-#26).Revision 3: folds in the orchestrator's step 3 decisions (see Decisions and constraints).
Decisions and constraints (step 3 checkpoint, orchestrator)
subagent_counton tree rows is a backendfollow-up, not this layer.
groupByandprStatuseshidden from the filter popover while the tree is on.aria-current="page"only on treeitems; noaria-selected.diff_statuson tree rows stays a backend follow-up (PR filter and badges hidden in treemode). The double-encoded tool errors are being fixed in PR3: the
send_chat_messagerenderer must NOT unwrap a nested JSON string; it reads
{ error, chat_id?, title? }directlyfrom the result. Before pushing, fetch
scott/chat-tree/3-messaging, rebase onto its new head,and rely on the corrected shape. If the PR3 fix has not landed at step 7, report instead of
working around it.
All
REVIEW-plan.mddispositions stand as recorded.Scope
Behind the
chat-treeexperiment, replace the flat chat list in the agents sidebar with a treerendered like an IDE file panel, fed by
GET /organizations/{org}/chats/tree. Add transcriptrendering for PR3's
sender-chatmessage part and thesend_chat_message/list_chat_treetool calls. With the experiment off, the sidebar and the transcript are unchanged and no tree
endpoint is called.
Out of scope: drag and drop or move between parents (dnd-kit reordering of the pinned section
stays as is), new backend fields or endpoints, a label filter UI (none exists today), changes to
the chat search dialog's server query.
Fixed constraints (PR2 Invariants and API contract, PR3 UI contract)
Chat.kindisroot | chat | subagent. Tree root located bykind === "root";root_chat_idis the subagent family root and is never the tree root. Never infer "subagent" from
parent_chat_id.GET /organizations/{org}/chats/tree?archived=returns{ root_chat_id: string | null, chats: Chat[] }:rootandchatrows owned by the caller, sorted by depth thenupdated_atdesc, subagents excluded,
childrenempty, nodiff_status(tree rows are converted withoutit,
db2sdk.go:2153-2161),depthandchild_chat_countpresent on rows anchored at a rootand absent on depth 0 rows;
child_chat_countcounts named children of any archive state.archived=truereturns the root plus archived rows only, so active intermediate ancestors aremissing and the archived response is a forest. The first call creates the root lazily and adopts
parentless chats.
root_chat_id: nullmeans the org has no usable model config: treatchatsas a flat list. 404 when the experiment is off.
POST /chatsrequires initialcontent;parent_chat_iddefaults to the root when omitted.Depth limit
ChatTreeMaxDepth = 5(root is depth 1): a chat at depth 5 cannot have children.and subagents) and fails if any member is running, interrupting, or requires action.
GET /chats/{chat}reportsdepthandchild_chat_countto the owner andchildren=subagents (one level).
GET /chats?source=shared_with_me./chats/watch) carrykind; root creation emits nocreatedevent.usermessage whose parts include{ type: "sender-chat", sender_chat_id?, sender_chat_title?, sender_chat_relation?: "parent" | "child", relay_hop? }followed by textparts. Missing
sender_chat_idmeans unknown sender; missingrelay_hopmeans 1. Editing such arow drops the part. Queued previews carry the same parts.
send_chat_messageargs{ chat_id, message, delivery? }(chat_idmay be theliteral
parent;deliverydefaults toqueue), success result{ chat_id (resolved UUID), title, relation, previous_status, status, delivery: started | queued | interrupting, downgraded_from?, message_id?, queued_message_id?, relay_hop }. Error results are markedis_errorand, because the tool is outside the subagent lifecycle allowlist(
chatprompt.go:745-752, 834-841), reach the client as{ error: "<JSON string of { error, chat_id?, title? }>" }.relationis the target relative to the sender (opposite frame fromthe part).
list_chat_treeresult{ self: { chat_id, title, kind }, parent: { chat_id, title, kind, status } | null, children: [{ chat_id, title, status, updated_at }] }; children areunarchived only;
parentis null when there is none, it is a subagent, or it is unreadable.What the code does today (verified on the branch)
Sidebar data flow (
pages/AgentsPage/AgentsPageLayout.tsx):useInfiniteQuery(infiniteChats({ archived, prStatuses, chatStatus, sources }))(L230-237);
chatList = pages.flat()(L390). Filters come from URL params throughgetAgentSidebarFilters(utils/agentSidebarFilters.ts):archiveStatus,groupBy(
date | chat_status),prStatuses,chatStatuses(unread | read),sources(
created_by_me | shared_with_me, defaultcreated_by_me). No label filter exists anywhere inthe sidebar;
Chat.labelsis not read by sidebar code.watchChats()handler (L558-681) writes to caches underchatListFamilyKey(
api/queries/chats.tsL24) andchatEntityKeyonly:applyWatchedChatArchived(L410),addChildToParentInCache(L193, subagentcreated),prependToInfiniteChatsCache(L142),mergeWatchedChatIntoCaches(L633, field merge throughmergeWatchedChatSummaryL521),plus conditional invalidations.
readInfiniteChatsCache(L174) feeds the chime previous status(L571) and
reorderPinnedChat(L1565).ChatsSidebar/chats/ChatsPanel.tsx:buildChatTree(tree/chatTree.ts) treats list rows as roots and embedschat.children(subagents, depth capped at 1); pinned =
pin_order > 0sorted; shared =shared && owner_id !== currentUserId; sections by time group or unread/read. Pinned reordering uses dnd-kit(
SortableChatTreeNode).expandedByIdandcollapsedSectionsareuseState, not persisted;ancestors of the active chat auto expand (L248-280).
tree/ChatTreeNode.tsxrenders a row: status icon fromgetChatDisplayConfig(
tree/statusConfig.ts: waiting, running, interrupting/requires_action, error), hover expandtoggle with
aria-expanded,NavLinkto/agents/:id(aria-current highlight), unread dot andsr-only "(unread)", shared icon, relative time, actions
DropdownMenuand right-clickContextMenusharingChatActionsMenuItems. Norole="tree",treeitem, oraria-levelexists anywhere in
site/src. Indent 26 px per level.components/ChatActionsMenuItems.tsx: pin, rename, show/hide subagents, archive, archive anddelete workspace.
isChildChat = getParentChatID(chat) !== undefined(L97) andchatHasMenuActions(L55) still infer "subagent" fromparent_chat_id.ChatTopBar.tsxL99-105 does the same (
isRootChat = parentChatID === undefined, gates the share popover andloads the parent chat for the breadcrumb).
chatHelpers.ts:97carries the stale COALESCEcomment PR2 deferred here. With the experiment on, every adopted chat has
parent_chat_idset,so these three sites hide pin, archive, and share for all user chats.
requestArchiveAgentL400-405, optimistic mutation);"Archive & delete workspace" uses
DeleteDialog. Archive is blocked client side bychatFamilyAllowsArchive(status, children)with the hint "Interrupt or wait for the agent tofinish first.";
activeChatChildren(L735) feeds the top bar fromchatList[...].children.handleNewAgentnavigates to/agents;AgentCreatePage.tsxbuildsCreateChatRequestfrom the composer (AgentCreateForm, which owns the organization choice)and navigates to the new chat. The list receives the row through the
createdwatch event.RenameChatDialoglifted to the layout (chatPendingRename)./agents(index) the composer is stacked abovethe sidebar (
order-2 flex-1), on/agents/:idthe sidebar ishidden sm:block(
AgentsPageLayout.tsxL750-760, L799-809).ResizableChatsSidebarFrameapplies width only atsm:.useDashboard().experiments.includes("...")(AgentChatPage.tsxL116);"chat-tree"is already in the generatedExperimentunion. Organizations for the page comefrom
useDashboard().organizations(models are queried per org at L238).agents.<kebab>prefix with guarded reads(
ChatsSidebar/sidebarWidth.ts,utils/sidebarTabStorage.ts).chats/treecall exists inapi/api.ts; org-scoped precedent is/api/v2/organizations/${encodeURIComponent(id)}/chats/models. Generated typesChatTreeResponse,ChatTreeMaxDepth,Chat.depth,Chat.child_chat_count,CreateChatRequest.parent_chat_id,ChatSenderChatPart,ChatSenderChatRelationexist.toolRenderers: Record<string, FC<ToolRendererProps>>inChatElements/tools/Tool.tsxL1175-1197, selected at L1238-1240, generic fallbackGenericToolRenderer.toolIconsinToolIcon.tsx;toolIconsCoverage.test.tsrequires anicon per registered renderer;
Tool.stories.tsx"all tools" story requires a showcase item perregistered renderer. Reference renderers:
ListAgentsRenderer+ListAgentsTool.tsx(parsewith
asRecord/asString/asNumber,ToolCall.Root/Header/Content, chat links throughsafeBuildAgentChatPath+Linkpreservinglocation.search).ChatMessageItem(ChatConversation/ConversationTimeline.tsxL96-400) rendersUserMessageContent(UserMessageContent.tsx, bubble with text and attachments; no author oravatar shown). Parts are folded by
parseMessageContent(messageParsing.ts) intoParsedMessageContent, which already hassenderChat?: ChatSenderChatPart(types.tsL69-72)from PR3's minimal switch case;
hookNoticesrender asLifecycleHookNoticeafter the bubble(L273-280). Edit button gated at L300-320 with
onEditUserMessagepassed per row at L601.QueuedMessagesList.tsxgetQueuedMessageInfo(L32-54) ignoressender-chat.Design decisions
D1. Data source: one tree query per organization, list query only for shared chats
API.experimental.getChatTree(organizationId, { archived })callsGET /api/v2/organizations/{org}/chats/tree?archived=. Query definitionchatTree(organizationId, { archived })inapi/queries/chats.tswith keychatTreeKey(organizationId, archived) = ["chats", "collections", "tree", organizationId, { archived }]and family keychatTreeFamilyKey = ["chats", "collections", "tree"]. The key deliberately does not share thechatListFamilyKeyprefix so the infinite-list cache helpers (which assumeInfiniteData<Chat[]>)never touch it.
With the experiment on,
AgentsPageLayoutrunsuseQueriesoverorganizations(same set themodels query uses) with
chatTree(org.id, { archived: archivedFilter }), and runs the existinginfiniteChatsquery only whensidebarFilters.sourcesincludesshared_with_me, withsources: ["shared_with_me"]. With the experiment off, the layout is byte-for-byte the currentcode path:
infiniteChatsas today, tree queries disabled (enabled: falseis not enough toavoid the hook, so the tree hook is called with an empty organization list).
Alternatives: (a) keep
infiniteChatsas the sole source and derive the tree fromparent_chat_id: rejected, the list excludes the root and never triggers lazy materialisation;(b) query only the default organization: rejected, chats exist per organization and the sidebar
lists all of them today. Cost of the chosen variant: one root per organization is created on first
load in every organization the user belongs to (the backend contract), and an organization
without a model config yields
root_chat_id: nulland a flat list for that organization.D2. Tree model: pure builder over
parent_chat_id, flattened for renderingtree/chatTreeModel.ts(new, pure):buildChatTreeModel({ trees: { organization, response }[], subagentsByParent })returns{ rootIds, nodesById, childrenById, parentById }where each node is{ chat, level, kind, organizationId }. Named children come fromparent_chat_id. A chat whose parent is not in theresponse is attached directly under its organization's root when
root_chat_idis set (thearchived view is a forest with active ancestors missing; legacy parentless rows during the
adoption race), or at top level when
root_chat_idis null. With several organizations, eachorganization's rows sit under a synthetic organization node (
div role="treeitem" aria-expanded, organization display name, Enter/Space/Right/Left toggle); with one organizationthe root is the top node.
levelis always derived client side; serverdepthis used onlyfor the depth-limit check on the node itself and is treated as optional. Children are ordered as
the response orders them (
updated_atdesc). Subagents (from D5) are appended after namedchildren.
flattenVisibleTree(model, { expanded, visible })returns the ordered list of visible rows{ id, level, hasChildren, isExpanded, setSize, posInSet }used both for rendering and forkeyboard navigation, so both share one definition of "visible".
collectMatchingChatIDs(model, predicate)returns matched ids plus all ancestors (the existingcollectVisibleChatIDsancestor/descendant walk generalised to a predicate); used for resultfilters (D6) and reusable for a future inline filter box.
childCount(model, id)anddescendantCount(model, id)count named children and descendantspresent in the model. The server's
child_chat_count(optional, any archive state) is used onlyfor the muted "n chats" hint on collapsed nodes; it never claims those chats are all listed.
The existing
buildChatTree/collectVisibleChatIDsandChatTreeNodestay untouched for theexperiment-off path (FE3: extending them would change the legacy rendering).
D3. Rendering:
ChatTreePanelwith WAI-ARIA tree semantics, IDE file panel lookNew components under
ChatsSidebar/tree/:ChatTreePanel.tsx: replaces the sections area ofChatsPanelwhen the experiment is on(
ChatsPanelgets atreeData?: ChatTreePanelDataprop; header, New chat, Search, filters,footer, loading, error, and empty states stay in
ChatsPanel). Layout: Pinned section (flatshortcuts, dnd-kit reordering kept,
ChatTreeNoderows as today so pinned rows keep theircurrent look), then "Shared with you" (flat, from the list query), then the tree with
role="tree"andaria-label="Chat tree". Pinned rows inside the panel use a newSortablePinnedChatRowwith a dedicated grip handle (setActivatorNodeRef, dnd-kitattributeson the handle only, handletabIndexfollowing the roving rule) so the row wrapperis not a
role="button"and Enter on the row link navigates instead of starting a keyboarddrag. The legacy
SortableChatTreeNodestays unchanged for the experiment-off path (the Enterhijack there is verified in step 4 and noted in the PR as a back-port candidate). Pinned and
shared rows in the panel are not treeitems;
focusedIdindexes tree rows only, so the secondaria-current="page"anchor on a pinned copy (already the case today) does not affect focus.ChatTreeRow.tsx: one row. Structure:div role="none"(ContextMenuTriggerasChild, whichadds only
data-stateand handlers) containing theNavLinkas thetreeitem(APG navigationtreeview pattern: the anchor carries
role="treeitem",aria-level,aria-setsize,aria-posinset,aria-expandedwhen it has children,aria-current="page"for the activechat).
aria-selectedis not set: it would duplicatearia-currentin announcements (raised asopen question 7). Children render in a
div role="group". Indent guide lines per level(
CHILD_INDENT_PX16 with a 1 px guide). Chevron button with a real name ("Expand" /"Collapse"),
tabIndex={-1}, visible on hover with[@media(hover:hover)]and always visiblewith a 24 px hit area under
pointer-coarse:; "Expand" / "Collapse" is also an actions-menuitem. Kind icon (root:
HouseIcon; chat: existing status icon; subagent:BotIconwith statusclass), title, unread dot and sr-only "(unread)", relative time, pin glyph when pinned, actions
trigger (
aria-label="Open actions for <title>") and right-clickContextMenu, both throughChatActionsMenuItems. No PR badge or diff stats: tree rows carry nodiff_status(reportedbackend gap).
Root) with the houseicon and the hint "Home" is not substituted. Rationale: the chat page header shows the same
title, and rename works on the root, so relabeling would desynchronise the two. Alternative
considered: show the user's name or "Home" when the title equals
Root.focusedIdin component state (initialised to the active chator the first row); only that row's anchor has
tabIndex={0}, other anchors-1. The actionstrigger has
tabIndex={0}only on the row that holds focus or is the active chat (-1otherwise), so Tab from the tree goes item, its actions, out. The chevron is never in the tab
order. This satisfies FE6 (every action reachable: arrow to the row, Tab, Enter) while keeping a
single tab stop for the tree body.
getChatDisplayConfigfor waiting, running, interrupting,requires_action, error; unread dot as today. There is no queued hint in the current sidebar, so
none is added.
aria-current="page"fromNavLink, samehas-[[aria-current=page]]styling.child_chat_count: shown as a muted count after the title on collapsed nodes only.D4. Keyboard navigation reducer
tree/treeKeyboard.ts(pure):treeKeyboardReducer(rows, focusedId, key, { typeahead }) -> { focusedId?, toggle?: { id, expanded }, open?: id }implementing the APG tree pattern:move to first child. Left: collapse an expanded node, else move to parent; on a force-expanded
ancestor (filter active) it moves to the parent without collapsing. Enter: open (the anchor's
native activation; the reducer returns
openfor parity in tests).*: expand all siblings.Printable characters: type-ahead over titles, cycling from the row after the focused one, with a
500 ms buffer reset (buffer state lives in the component; the reducer is pure and takes the
buffer as input). Right/Left are LTR; RTL mapping is a noted follow-up.
onKeyDownhandler on therole="tree"container acts only whenevent.targetis atreeitem (anchor or synthetic organization node) and no ctrl/meta/alt modifier is held, and
calls
preventDefaulton handled keys so ArrowDown from an actions trigger (Radix opens themenu) and Cmd+K never reach the reducer.
ChatTreePanelapplies the result: setsfocusedId, focuses the element through a ref map,calls
toggleExpanded.D5. Expansion persistence and subagent visibility
tree/chatTreeExpansion.ts:loadExpandedChatTreeIDs(orgIds)/persistExpandedChatTreeIDson localStorage key
agents.chat-tree-expandedstoring{ expanded: string[], subagents: string[] }with guarded parse (same style assidebarWidth.ts). Default whennothing is stored: roots expanded, everything else collapsed. Ancestors of the active chat are
expanded on navigation (existing behaviour, moved into the panel), and that expansion is
persisted too. A search or result filter forces expansion of matched ancestors without
persisting.
menu (the existing
ChatActionsMenuItemsitem, now shown for everychat/rootnode becausethe tree response carries no subagent count). Toggling on adds the node id to the persisted
subagentsset and mountsuseQuery(chatById(id))for that node; itschildren(subagents)render as
kind = subagentrows beneath the named children, withBotIcon. The active chat'sentity is already cached by the chat page, so its subagents appear without a new request.
Subagent
createdwatch events are merged into the entity cache by the existing handler(
addChildToParentInCachetargets list caches only; the panel also invalidateschatEntityKey(parent)for toggled nodes oncreated).cannot show "(n)" or hide itself when a node has none, and the per-node fetch is the only
bounded way to list subagents for arbitrary nodes. A
subagent_counton tree rows would removeboth limitations.
Alternative considered: a global "Show subagents" switch. Rejected because it needs one
GET /chats/{id}per expanded node with no way to skip nodes that have none.D6. Pins, shared chats, filters, and search in the tree
reordering preserved, same
ChatTreeNoderows). Pinned chats also keep their place in the tree(a node may have children) and show a small pin glyph there. Pin/unpin actions are hidden for
the root and for subagents.
infiniteChats({ sources: ["shared_with_me"] })when theshared_with_mesource filter is on; unchanged rows. Load-more sentinel applies to this sectiononly.
FilterPopover):archiveStatusswitches the tree query toarchived=true(archivedforest under the root, heading "Archived chats").
chatStatuses(unread/read) becomes aclient-side predicate on the tree (D2
collectMatchingChatIDs): matching nodes and theirancestors stay visible, ancestors are force-expanded, non-matching ancestors render dimmed with
an sr-only "(does not match filters)" in the treeitem name, and an
aria-live="polite"regionannounces "N chats match" while a filter is active.
groupByandprStatusesare notapplicable to the tree (no grouping; tree rows carry no
diff_status), so both options arehidden from
FilterPopoverwhen the tree is on (treeModeprop) and ignored.sourcesonlycontrols the shared section.
expands its ancestors. No inline filter box is added in this layer (open question 3).
D7. Actions from the tree
location.search).rootandchatnodes. At the limit(
depth >= ChatTreeMaxDepth) the item stays focusable witharia-disabled, a no-oponSelect,and the hint "Chat tree depth limit reached (5 levels)" rendered inside the item so arrow
navigation announces it (Radix
disableditems are skipped by roving focus). BecausePOST /chatsrequires initialcontent, the action navigates to the composer:
navigate("/agents", { state: { parentChatId, parentChatTitle } }).AgentCreatePagereadslocation.state, passesparent_chat_idinCreateChatRequest, andAgentCreateFormshows a dismissible chip "New chat under <title>"above the composer (clearing the chip clears the parent, so the chat is created under the root).
Router state, not a search param, so the parent does not leak into other navigation links that
copy
location.search. Also, when the experiment is on, the create form pins its organizationselector to the parent's organization.
RenameChatDialog(works for the root too).child_chat_count > 0), aConfirmDialogexplains the cascade: "Archive <title> and N chats beneath it? Subagents arearchived with them. Archiving fails if any of them is running, being interrupted, or waiting for
approval." (N =
descendantCount; when onlychild_chat_countis known the copy says "and thechats beneath it"). Confirm calls the existing
archiveChatmutation. Without named descendantsthe existing no-confirmation behaviour is kept (subagents were always cascaded silently). The
archive-blocked check extends
chatFamilyAllowsArchivewith the subtree statuses known to themodel (
chatSubtreeAllowsArchive); statuses of subagents that were never fetched are unknown,so the server rejection still surfaces through the existing toast. Root: archive, archive and
delete workspace, pin, and share are hidden (
kind === "root").trigger that is unmounted with the row, so the menus and dialogs opened from the tree set
onCloseAutoFocus={(e) => e.preventDefault()}.ChatTreePanelcomputes the focus target(next visible row, else previous, else parent) before the mutation and focuses it from an effect
keyed on the flattened rows once the removed row is gone;
focusedIdis never left on a removedid. Same rule for "Archive & delete workspace" (
DeleteDialog) and unarchive in the archivedtree. After creating a child, navigation to the new chat expands and highlights it (the existing
auto-expand on
activeChatId).chatnodes as today; the backend rejects it while theparent is archived, and the error surfaces through the existing toast.
D8. Live updates
The watch handler in
AgentsPageLayoutgains tree cache maintenance next to the list calls,implemented in
api/queries/chats.tsso it is unit testable:kind === "subagent"events (subagents are never tree rows).mergeWatchedChatIntoChatTreeCaches(queryClient, chat): for every cached tree of the chat'sorganization, replace the matching row through
mergeWatchedChatSummary(status, title,has_unread, updated_at;
diff_statusis not carried by tree rows and is skipped) withoutre-sorting (position is stable within a parent).
createdevents withkind === "chat": append the row to the active tree cache of itsorganization with
child_chat_count: 0,has_unread: false, nodepth(levels are derivedclient side), bump the parent's
child_chat_count, remove the row from cached archived trees(unarchive arrives as
createdwitharchived: false, once per family member) and invalidatethem; if the parent is not in the cache, invalidate
chatTreeFamilyKey. The list prepend(
prependToInfiniteChatsCache) is skipped when the tree is on and the chat is owned by thecurrent user, so owned rows do not flash into the shared list.
deleted(archived) events: remove the row and its descendants from the active tree cache,decrement the parent's
child_chat_count, and invalidate the archived tree for thatorganization.
cancelChatTreeRefetches(samestate.data === undefinedguard ascancelChatListRefetches) is called next to the list cancel before every websocket write so astale focus refetch cannot clobber it.
analogs:
cancelChatTreeQueriesinonMutate, the same optimistic patch throughupdateChatTreeCaches(patchChatArchiveState,pin_order,title), andinvalidateChatTreeQueriesinonSettled/onError.getNextOptimisticPinOrderandreorderPinnedChatread pinned rows from tree caches when present (there is nopinwatchevent).
readChatFromSidebarCacheslooks in the list caches then the tree caches; used by thechime previous-status read,
chatCostIdToInvalidate, the archive-and-delete resolver(
created_at), and thehas_unreadclear on navigation (which also patches the tree caches).The tree query keeps
refetchOnWindowFocuslike the list. Root creation emits no watch event andthe tree GET returns it directly, so nothing else is needed.
D9. Kind-based gates in existing components (compat fixes)
ChatActionsMenuItems.tsx:isChildChatbecomeschat.kind === "subagent";chatHasMenuActionslikewise; addisRootto hide pin and archive actions and show"New chat here".
ChatTopBar.tsx:isRootChat(share permission and parent breadcrumb) becomeschat.kind !== "subagent"; the parent chat query stays keyed onparent_chat_idbut thebreadcrumb is rendered only for subagents (a named chat's parent is a tree edge, not a spawn).
Share popover hidden for
kind === "root"(backend rejects ACL changes on the root).chatHelpers.tsgetChatCostTreeID: comment rewritten to the current server rule(
root_chat_idelse own id); theparent_chat_idfallback is removed since a named chat'sparent is not its cost root (PR2 dropped the COALESCE).
AgentsPageLayout.test.tscases thatencode the parent fallback are updated.
AgentsPageLayoutactiveChatChildren: sourced from the list when the experiment is off, fromthe entity cache (
chatById(agentId).children) when it is on.D10. Transcript: relayed rows and tool renderers
ConversationTimeline.tsx: whenparsed.senderChatis set,UserMessageContentreceivessenderChatand renders a provenance header as the first child of the bubble column:ArrowLeftRightIcon, "From <title>" where the title links to/agents/<sender_chat_id>(through
safeBuildAgentChatPath, plain text when the id is missing or unsafe, "Unknown chat"when the title is missing), a muted relation label ("parent chat" / "child chat"), and
"hop N" when
relay_hop > 1. The bubble gets a distinct left border (border-l-2 border-content-link) andaria-label="Relayed message from <title>"on the header group so itis not read as typed by the human. Edit is disabled on relayed rows (
onEditUserMessagepassed as
undefinedat L601 whensenderChatis set, with the copy action kept).QueuedMessagesList.tsx:getQueuedMessageInforecordssenderChat; the preview shows thesame "From <title>" prefix.
messageHelpers.hasRenderableContent: countssenderChatso a relayed row with an empty textpart still renders its header.
SendChatMessageTool.tsx+SendChatMessageRendererinTool.tsx: header label "Message to <title>", falling back to "Message to parent chat" when `args.chat_id === "parent"` and to "Message to chat" otherwise; link to the target chat when a UUID is known (`result.chat_id`, else `args.chat_id` when it is a UUID). Body lines: target relation, delivery (`started`, `queued`, `interrupting`; `args.delivery` may be absent and means `queue`), "downgraded from interrupt" when `downgraded_from` is present, previous status and status, hop. Error results: the result is `{ error: string, chat_id?, title? }` (PR3 fix); the renderer reads those fields directly and takes the target from `args` when `title` is absent. No nested-JSON unwrapping (decision 8). The message text is shown collapsed in `ToolCall.Content` like `message_agent`.ListChatTreeTool.tsx+ListChatTreeRenderer: header "Chat tree", body: parent row (kind,status, link) or "No parent", the chat itself, children rows (title, status icon,
updated_atvia
shortRelativeTime, link). Empty children: "No active child chats".toolIcons:send_chat_message->SendIcon,list_chat_tree->FolderTreeIcon.Tool.stories.tsxall-tools showcase gets both items.D11. Experiment off
ChatsPanelreceivestreeDataonly when the experiment is on;ChatActionsMenuItemsshows"New chat here" only when
onCreateChildChatis provided;AgentCreatePagesendsparent_chat_idonly when router state carries one (and the experiment is on). Tool renderers andthe relayed row header are keyed on data that only exists with the experiment on, so registering
them unconditionally is safe. No tree query is constructed when the experiment is off.
Affected files
New:
api/queries/chats.tsadditions;api/api.tsgetChatTree;ChatsSidebar/tree/chatTreeModel.ts(+test),treeKeyboard.ts(+test),chatTreeExpansion.ts(+test),
ChatTreePanel.tsx,ChatTreeRow.tsx,SortablePinnedChatRow.tsx,ArchiveChatTreeDialog.tsx,ChatTreePanel.stories.tsx,ChatTreePanel.test.tsx;ChatElements/tools/SendChatMessageTool.tsx,ListChatTreeTool.tsx(+stories);ChatConversation/SenderChatHeader.tsx;testHelpers/chatEntities.tsfixtures (MockChatTreeRoot,MockChatTreeChild, ...).Modified:
AgentsPageLayout.tsx(+test),ChatsSidebar.tsx,chats/ChatsPanel.tsx,filters/FilterPopover.tsx,ChatActionsMenuItems.tsx,ChatTopBar.tsx,chatHelpers.ts,AgentCreatePage.tsx,AgentCreateForm.tsx,ConversationTimeline.tsx,UserMessageContent.tsx,QueuedMessagesList.tsx(+test),messageHelpers.ts,tools/Tool.tsx,tools/ToolIcon.tsx,Tool.stories.tsx,ConversationTimeline.stories.tsx,ChatsSidebar.stories.tsx.Sequencing (commits)
fix(site/src/pages/AgentsPage): key chat tree gates on kind: D9 compat fixes with tests(
ChatActionsMenuItems,ChatTopBar,chatHelpers,AgentsPageLayout.test.ts).feat(site/src/api): add chat tree query and cache helpers:getChatTree,chatTree,chatTreeKey, D8 helpers withchats.test.tscoverage.feat(site/src/pages/AgentsPage/components/ChatsSidebar/tree): add chat tree model, keyboard reducer, and expansion storage: D2, D4, D5 pure modules with Vitest.feat(site/src/pages/AgentsPage): render the chat tree sidebar behind the chat-tree experiment:D1, D3, D6, D7, D11: panel, rows, dialogs, create-child routing, layout wiring, stories, tests.
feat(site/src/pages/AgentsPage/components): render relayed messages and chat tree tool calls:D10.
Each commit runs
pnpm check,pnpm lint:types, and the affectedpnpm testfiles; beforehandoff
pnpm lint,pnpm format,pnpm test:storybookfor the new story files, and thefrontend-reviewskill on the diff.Testing approach
Vitest (behaviour, non-visual assertions):
chatTreeModel.test.ts: building from one and several organizations,root_chat_id: nullflat fallback, orphan attachment under the root (archived child whose active parent is absent),
subagent appending,
flattenVisibleTreelevels and set/pos indices,descendantCount,collectMatchingChatIDsancestors and forced expansion.treeKeyboard.test.ts: every key of the APG pattern, boundaries, type-ahead cycling and buffer.chatTreeExpansion.test.ts: defaults, round trip, corrupt storage.chats.test.ts: tree cache merge, append on created (archived tree cleaned), removal onarchived, subagent events ignored, refetch cancellation guard, mutation optimistic patches and
invalidations on tree caches, pinned reads from tree caches, list caches untouched by tree
helpers and vice versa.
ChatTreePanel.test.tsx: arrow keys move focus (assertdocument.activeElementaccessiblename), Tab order (one stop into the tree, its actions trigger, out),
aria-levelandaria-expandedvalues after toggles, Enter navigates (assert router location), Enter on apinned row navigates, toggling persists to storage, "New chat here" navigates with state and is
aria-disabledat depth 5, archive with descendants opens the confirmation and callsonArchiveAgenton confirm, focus lands on the computed target after the row is removed, filterpredicate keeps ancestors and Left on a force-expanded ancestor does not collapse it.
ChatActionsMenuItems/ChatTopBartests: named child keeps pin and archive; root hides them.AgentsPageLayout.test.ts:activeChatChildrensource, cost id resolution without the parentfallback.
AgentCreatePage/AgentCreateFormtest:parent_chat_idsent from router state and droppedwhen the chip is cleared.
QueuedMessagesList.test.ts:senderChatextracted.ConversationTimelinetest: edit callbacknot offered for relayed rows.
Storybook (visual, setup-only play):
ChatTreePanel.stories.tsx: empty tree, single root withchildren, deep tree (5 levels, depth-limit menu open), collapsed and expanded, running / error /
requires_action / unread nodes, pinned section plus tree, shared section, archived tree, filter
pruning with dimmed ancestors, subagents shown under a node, archive confirmation open, multi
organization, mobile viewport, keyboard focus ring on a row.
ConversationTimeline.stories.tsx:relayed row (parent, child, hop 3, missing title, unknown sender), queued relayed preview.
SendChatMessageTool.stories.tsxandListChatTreeTool.stories.tsx: started, queued,interrupting with downgrade, error, running; tree with parent and children, root without parent,
empty children, error.
Tool.stories.tsxshowcase items.Open questions
Rootas "Home" or theuser's name. Verbatim chosen for consistency with the chat header.
the backend for
subagent_counton tree rows in a later PR.collectMatchingChatIDsmakes it asmall follow-up. Include now?
behaviour for leaf chats. Confirm.
groupByhidden from the filter popover while the tree is on (D6). Confirm.(not possible:
POST /chatsrequires content). Confirm.aria-current="page"only on treeitems, droppingaria-selectedfrom the overview's list toavoid double announcement (REVIEW-plan Implement initial API surface for creating workspace #23). Confirm or require both.
diff_status(no PRbadges or PR filter in the tree) and tree tool errors arrive double-encoded (REVIEW-plan chore: Initial GHA workflow #1,
chore: Add XState machines to model flows #16). Accept for this layer?
Generated by Coder Agents on behalf of @jscottmiller.