From 0436ab44bc344a8f87148335fc3e7ed4b22706d2 Mon Sep 17 00:00:00 2001 From: Evan Rusackas Date: Tue, 24 Nov 2026 21:06:55 -0800 Subject: [PATCH] feat(agor-ui): eject a session from the sidebar onto the board canvas A button in the session panel header pops an open session out of the sidebar drawer onto the board canvas as a live, interactive node. The node reuses SessionPanel (`isEjected`) so transcript, prompt input and footer behave the same as in the sidebar. Re-dock moves it back to the drawer, Close dismisses the node, and several sessions can be ejected at once. Positions persist per user and board in localStorage (`useEjectedSessions`). Ported onto the current shell: the ejected node reads its MCP server ids via `useSessionMcpServerIds`, the drawer keeps the mobile full-screen layout, and the canvas keeps its zone-grid layout pass. The `ejectedSessions` default is a module-level constant so omitting the prop cannot re-run the node sync effect forever. Co-Authored-By: Evan Rusackas Co-Authored-By: Claude Sonnet 5.5 --- apps/agor-ui/src/components/App/App.tsx | 83 +++++++++- .../SessionCanvas/SessionCanvas.tsx | 117 +++++++++++++- .../canvas/EjectedSessionNode.tsx | 145 ++++++++++++++++++ .../components/SessionPanel/SessionPanel.tsx | 59 ++++++- .../src/hooks/useEjectedSessions.test.tsx | 55 +++++++ apps/agor-ui/src/hooks/useEjectedSessions.ts | 81 ++++++++++ 6 files changed, 522 insertions(+), 18 deletions(-) create mode 100644 apps/agor-ui/src/components/SessionCanvas/canvas/EjectedSessionNode.tsx create mode 100644 apps/agor-ui/src/hooks/useEjectedSessions.test.tsx create mode 100644 apps/agor-ui/src/hooks/useEjectedSessions.ts diff --git a/apps/agor-ui/src/components/App/App.tsx b/apps/agor-ui/src/components/App/App.tsx index 6306b448a6..68ffbedf0b 100644 --- a/apps/agor-ui/src/components/App/App.tsx +++ b/apps/agor-ui/src/components/App/App.tsx @@ -36,6 +36,7 @@ import { useAppNavigation } from '../../hooks/useAppNavigation'; import { useBoardPartition } from '../../hooks/useBoardPartition'; import { useBoardTitle } from '../../hooks/useBoardTitle'; import { useCreateFlows } from '../../hooks/useCreateFlows'; +import { useEjectedSessions } from '../../hooks/useEjectedSessions'; import { useEventStream } from '../../hooks/useEventStream'; import { useFaviconStatus } from '../../hooks/useFaviconStatus'; import { useLocalStorage } from '../../hooks/useLocalStorage'; @@ -425,6 +426,31 @@ export const App: React.FC = ({ const activeUrlTargetArtifactId = activeUrlTarget?.kind === 'artifact' ? activeUrlTarget.id : null; + // currentBoardId must be declared before useEjectedSessions (which is scoped per board) + // and before effectiveSelectedSessionId (which excludes ejected sessions). + // Initialize current board only from explicit route/bootstrap state. Home (`/`) + // is a valid no-board route, so do not auto-select localStorage/first board. + const [currentBoardId, setCurrentBoardIdInternal] = useState(() => initialBoardId || ''); + + // Ejected session positions — stored in localStorage per user+board. Sessions in + // this map render as interactive canvas nodes instead of opening in the sidebar. + const { + ejectedSessions, + ejectSession, + updateEjectedPosition, + redockSession, + closeEjectedSession, + } = useEjectedSessions(user?.user_id, currentBoardId); + + // Ref so handleSessionClick (a stable useCallback) can read ejectedSessions + // without being included in its dependency array and breaking referential stability. + const ejectedSessionsRef = useRef(ejectedSessions); + ejectedSessionsRef.current = ejectedSessions; + + // Ref so eject/redock handlers can read currentBoardId without capturing a stale value. + const currentBoardIdRef = useRef(currentBoardId); + currentBoardIdRef.current = currentBoardId; + // Synchronously derive the effective session selection. When a session is // archived/deleted, it vanishes from sessionById. Without this, there is a // two-phase unmount: first SessionPanel renders null (session gone but @@ -439,8 +465,15 @@ export const App: React.FC = ({ const selectedSessionExists = useAgorStore( useMemo(() => makeSessionExistsSelector(selectedSessionId), [selectedSessionId]) ); + // Ejected sessions are excluded so they stay on the canvas rather than + // opening in the sidebar drawer when navigated to via URL. const effectiveSelectedSessionId = - !isRootHomePath && selectedSessionId && selectedSessionExists ? selectedSessionId : null; + !isRootHomePath && + selectedSessionId && + selectedSessionExists && + !ejectedSessions[selectedSessionId] + ? selectedSessionId + : null; // The open session, its branch and the URL's branch target stay while // shown, whatever scope evicts (`rowPins.ts`). usePinnedOpenRows({ sessions: [selectedSessionId], branches: [activeUrlTargetBranchId] }); @@ -515,10 +548,6 @@ export const App: React.FC = ({ // Handle external user settings modal control (e.g., from onboarding "Configure API Keys") const effectiveUserSettingsOpen = userSettingsOpen || !!openUserSettings; - // Initialize current board only from explicit route/bootstrap state. Home (`/`) - // is a valid no-board route, so do not auto-select localStorage/first board. - const [currentBoardId, setCurrentBoardIdInternal] = useState(() => initialBoardId || ''); - // Initialize comments panel state from localStorage (collapsed by default) const [commentsPanelCollapsed, setCommentsPanelCollapsed] = useLocalStorage( 'agor:commentsPanelCollapsed', @@ -864,6 +893,37 @@ export const App: React.FC = ({ if (currentBoardId) navigation.goToBoard(currentBoardId); }, [navigation, currentBoardId]); + // Eject a session from the sidebar drawer onto the board canvas as a live node. + // Position is derived from the viewport center plus a small offset per existing ejected count. + const handleEjectSession = useCallback( + (sessionId: string) => { + const center = sessionCanvasRef.current?.getViewportCenter() ?? { x: 200, y: 100 }; + const ejectedCount = Object.keys(ejectedSessionsRef.current).length; + const offset = ejectedCount * 40; + ejectSession(sessionId, { x: center.x - 300 + offset, y: center.y - 350 + offset }); + // Close the sidebar drawer — the session now lives on the canvas. + if (currentBoardIdRef.current) navigation.goToBoard(currentBoardIdRef.current); + }, + [ejectSession, navigation] + ); + + // Move an ejected session back into the sidebar drawer. + const handleRedockSession = useCallback( + (sessionId: string) => { + redockSession(sessionId); + navigation.goToSession(sessionId); + }, + [redockSession, navigation] + ); + + // Close an ejected session without re-docking. Next click opens it in the drawer. + const handleCloseEjectedSession = useCallback( + (sessionId: string) => { + closeEjectedSession(sessionId); + }, + [closeEjectedSession] + ); + const handleCloseTerminal = () => { setTerminalOpen(false); setTerminalCommands([]); @@ -975,6 +1035,10 @@ export const App: React.FC = ({ const handleSessionClick = useCallback( (sessionId: string) => { + // If the session is already ejected onto the canvas, don't also open it in the drawer. + // The ejected node is its own live panel. + if (ejectedSessionsRef.current[sessionId]) return; + // Reads the store at call time, so the handler's identity stays stable across // socket churn (it flows into SessionCanvas → initialNodes deps). clearOpenedSessionFlags(client, sessionId); @@ -1494,6 +1558,10 @@ export const App: React.FC = ({ onOpenCommentsPanel={handleOpenCommentsPanel} onCommentHover={setHoveredCommentId} onCommentSelect={handleCommentSelect} + ejectedSessions={ejectedSessions} + onEjectSessionRedock={handleRedockSession} + onEjectSessionClose={handleCloseEjectedSession} + onUpdateEjectedPosition={updateEjectedPosition} /> )} @@ -1541,6 +1609,11 @@ export const App: React.FC = ({ open={!!effectiveSelectedSessionId} onClose={handleCloseSessionPanel} uploadPolicy={uploadPolicy} + onEject={ + effectiveSelectedSessionId + ? () => handleEjectSession(effectiveSelectedSessionId) + : undefined + } /> diff --git a/apps/agor-ui/src/components/SessionCanvas/SessionCanvas.tsx b/apps/agor-ui/src/components/SessionCanvas/SessionCanvas.tsx index fdfeec54d7..a443110b9b 100644 --- a/apps/agor-ui/src/components/SessionCanvas/SessionCanvas.tsx +++ b/apps/agor-ui/src/components/SessionCanvas/SessionCanvas.tsx @@ -132,6 +132,7 @@ import { BoardPartitionStatus } from './BoardPartitionStatus'; import { AppNode } from './canvas/AppNodeLazy'; import { ArtifactNode } from './canvas/ArtifactNodeLazy'; import { CommentNode, ZoneNode } from './canvas/BoardObjectNodes'; +import EjectedSessionNode, { type EjectedSessionNodeData } from './canvas/EjectedSessionNode'; import { MarkdownNode } from './canvas/MarkdownNode'; import { RemoteCursorLayer, type StaticRemoteCursor } from './canvas/RemoteCursorLayer'; import { STALE_DRAFT_TITLE, useCopyDraft } from './canvas/staleDraft'; @@ -216,8 +217,24 @@ interface SessionCanvasProps { height?: React.CSSProperties['height']; /** View only (mobile): pan, zoom and open items; no tools, dragging, edits or cursor broadcast. */ readOnly?: boolean; + /** + * Map of ejected session IDs → canvas positions. Sessions in this map are + * rendered as interactive `ejectedSessionNode` nodes instead of in the sidebar. + * Persisted in localStorage by `useEjectedSessions` in App.tsx. + */ + ejectedSessions?: Record; + /** Called when the user re-docks an ejected session back to the sidebar. */ + onEjectSessionRedock?: (sessionId: string) => void; + /** Called when the user closes an ejected session without re-docking. */ + onEjectSessionClose?: (sessionId: string) => void; + /** Called when an ejected session node is dragged to persist its new position. */ + onUpdateEjectedPosition?: (sessionId: string, position: { x: number; y: number }) => void; } +// Stable default: an inline `{}` is a new object every render, which would +// re-run the ejected-node memo and its sync effect forever. +const NO_EJECTED_SESSIONS: NonNullable = {}; + export interface SessionCanvasRef { getViewportCenter: () => { x: number; y: number } | null; } @@ -459,6 +476,7 @@ const nodeTypes = { markdown: MarkdownNode, appNode: AppNode, artifactNode: ArtifactNode, + ejectedSessionNode: EjectedSessionNode, }; const EMPTY_BOARD_ENTITY_OBJECTS: BoardEntityObject[] = Object.freeze( @@ -560,6 +578,10 @@ const SessionCanvasInner = forwardRef( staticCursorScale, height = '100vh', readOnly = false, + ejectedSessions = NO_EJECTED_SESSIONS, + onEjectSessionRedock, + onEjectSessionClose, + onUpdateEjectedPosition, }: SessionCanvasProps, ref ) => { @@ -1638,6 +1660,27 @@ const SessionCanvasInner = forwardRef( canMutateBoard, ]); + // Build ejected session nodes from the ejectedSessions map passed in from App.tsx. + // These render as full interactive panels on the canvas (no backend persistence needed). + const ejectedSessionNodes: Node[] = useMemo(() => { + return Object.entries(ejectedSessions).map(([sessionId, position]) => ({ + id: `ejected-${sessionId}`, + type: 'ejectedSessionNode', + dragHandle: REACT_FLOW_DRAG_HANDLE_SELECTOR, + position, + zIndex: 600, // Above branches (500), below comments (1000) + width: 600, + height: 700, + data: { + sessionId, + client, + currentUserId, + onRedock: onEjectSessionRedock ?? (() => {}), + onClose: onEjectSessionClose ?? (() => {}), + } satisfies EjectedSessionNodeData, + })); + }, [ejectedSessions, client, currentUserId, onEjectSessionRedock, onEjectSessionClose]); + // No edges needed for branch-centric boards // (Session genealogy is visualized within BranchCard, not as canvas edges) const initialEdges: Edge[] = useMemo(() => [], []); @@ -2073,6 +2116,7 @@ const SessionCanvasInner = forwardRef( if (node.type === 'comment') return token.colorText; if (node.type === 'markdown') return `${token.colorText}B3`; if (node.type === 'zone') return `${token.colorText}66`; + if (node.type === 'ejectedSessionNode') return token.colorPrimary; if (node.type === 'cardNode') { const cardData = node.data as CardNodeData; return cardData.card?.effective_color || token.colorPrimaryBorder; @@ -2108,6 +2152,7 @@ const SessionCanvasInner = forwardRef( const cards: Node[] = []; const apps: Node[] = []; const comments: Node[] = []; + const ejected: Node[] = []; for (const node of nodes) { switch (node.type) { case 'zone': @@ -2129,13 +2174,16 @@ const SessionCanvasInner = forwardRef( case 'comment': comments.push(node); break; + case 'ejectedSessionNode': + ejected.push(node); + break; } } - return { zones, markdown, branches, cards, apps, comments }; + return { zones, markdown, branches, cards, apps, comments, ejected }; }, []); // Helper: Apply consistent z-ordering to nodes - // Z-order: zones < branches/cards < apps/artifacts < markdown < comments + // Z-order: zones < branches/cards < apps/artifacts < markdown < ejected < comments const applyZOrder = useCallback( ( zones: Node[], @@ -2143,10 +2191,11 @@ const SessionCanvasInner = forwardRef( branches: Node[], cards: Node[], comments: Node[], - apps: Node[] = [] + apps: Node[] = [], + ejected: Node[] = [] ) => { return sanitizeOrphanedNodeParents( - [...zones, ...branches, ...cards, ...apps, ...markdown, ...comments], + [...zones, ...branches, ...cards, ...apps, ...markdown, ...ejected, ...comments], { onOrphan: onOrphanedParent } ); }, @@ -2168,7 +2217,7 @@ const SessionCanvasInner = forwardRef( const boardObjectNodes = getBoardObjectNodes(); setNodes((currentNodes) => { - const { comments } = partitionNodesByType(currentNodes); + const { comments, ejected } = partitionNodesByType(currentNodes); const currentNodesById = new Map(currentNodes.map((n) => [n.id, n])); const zones = boardObjectNodes @@ -2210,7 +2259,7 @@ const SessionCanvasInner = forwardRef( const updatedCards = applyLocalPositions(cardNodes, currentNodesById, zones); return layoutZoneGrids( - applyZOrder(zones, markdown, updatedBranches, updatedCards, comments, apps) + applyZOrder(zones, markdown, updatedBranches, updatedCards, comments, apps, ejected) ); }); }, [ @@ -2250,7 +2299,8 @@ const SessionCanvasInner = forwardRef( if (isDraggingRef.current) return; setNodes((currentNodes) => { - const { zones, markdown, branches, cards, apps } = partitionNodesByType(currentNodes); + const { zones, markdown, branches, cards, apps, ejected } = + partitionNodesByType(currentNodes); // Comment parents are branches or zones; branches take precedence on id // collision (insertion order below makes them overwrite). @@ -2303,10 +2353,47 @@ const SessionCanvasInner = forwardRef( return newNode; }); - return applyZOrder(zones, markdown, branches, cards, commentsWithLocalPositions, apps); + return applyZOrder( + zones, + markdown, + branches, + cards, + commentsWithLocalPositions, + apps, + ejected + ); }); }, [commentNodes, setNodes, applyZOrder, partitionNodesByType]); + // Sync EJECTED SESSION nodes separately. Position is owned by localStorage + // (via ejectedSessionNodes prop); apply localPositionsRef overrides to prevent + // flicker while a drag is in-flight waiting for the localStorage write to round-trip. + useEffect(() => { + if (isDraggingRef.current) return; + + setNodes((currentNodes) => { + const { zones, markdown, branches, cards, apps, comments } = + partitionNodesByType(currentNodes); + + const updatedEjected = ejectedSessionNodes.map((newNode) => { + const localPosition = localPositionsRef.current[newNode.id]; + if (localPosition) { + const positionConfirmed = + Math.abs(localPosition.x - newNode.position.x) <= 1 && + Math.abs(localPosition.y - newNode.position.y) <= 1; + if (positionConfirmed) { + delete localPositionsRef.current[newNode.id]; + return newNode; + } + return { ...newNode, position: localPosition }; + } + return newNode; + }); + + return applyZOrder(zones, markdown, branches, cards, comments, apps, updatedEjected); + }); + }, [ejectedSessionNodes, setNodes, applyZOrder, partitionNodesByType]); + // Sync edges useEffect(() => { setEdges(initialEdges); @@ -2594,6 +2681,19 @@ const SessionCanvasInner = forwardRef( const ticket = guard.capture(); if (!ticket) return; + // Ejected session nodes are client-side only — persist to localStorage and return. + // No board_object update needed. + if (node.type === 'ejectedSessionNode') { + const absolutePos = node.positionAbsolute || node.position; + localPositionsRef.current[node.id] = { x: absolutePos.x, y: absolutePos.y }; + // Extract sessionId from node id (format: `ejected-`) + const sessionId = node.id.replace(/^ejected-/, ''); + onUpdateEjectedPosition?.(sessionId, { x: absolutePos.x, y: absolutePos.y }); + return; + } + + if (!board || !client || !reactFlowInstanceRef.current) return; + // Track final position locally // IMPORTANT: Store ABSOLUTE position, not relative! const absolutePos = node.positionAbsolute || node.position; @@ -3048,6 +3148,7 @@ const SessionCanvasInner = forwardRef( reorderInZone, enterArrangedZone, shownSizeOf, + onUpdateEjectedPosition, ] ); diff --git a/apps/agor-ui/src/components/SessionCanvas/canvas/EjectedSessionNode.tsx b/apps/agor-ui/src/components/SessionCanvas/canvas/EjectedSessionNode.tsx new file mode 100644 index 0000000000..d6c59cd2c4 --- /dev/null +++ b/apps/agor-ui/src/components/SessionCanvas/canvas/EjectedSessionNode.tsx @@ -0,0 +1,145 @@ +import type { AgorClient } from '@agor-live/client'; +import { CloseOutlined, ShrinkOutlined } from '@ant-design/icons'; +import { Button, Space, Tooltip, theme } from 'antd'; +import React from 'react'; +import { useSessionMcpServerIds } from '../../../hooks/useSessionMcpServerIds'; +import { useAgorStore } from '../../../store/agorStore'; +import { selectBranchById, selectSessionById } from '../../../store/selectors'; +import { + REACT_FLOW_DRAG_HANDLE_CLASS, + REACT_FLOW_NO_DRAG_CLASS, +} from '../../../utils/reactFlowDragClasses'; +import { getSessionDisplayTitle } from '../../../utils/sessionTitle'; +import SessionPanel from '../../SessionPanel/SessionPanel'; +import { ToolIcon } from '../../ToolIcon'; + +export interface EjectedSessionNodeData { + sessionId: string; + client: AgorClient | null; + currentUserId?: string; + /** Called when the user clicks "Re-dock" — removes from canvas and opens in sidebar. */ + onRedock: (sessionId: string) => void; + /** Called when the user clicks "Close" — removes from canvas; next click opens in sidebar. */ + onClose: (sessionId: string) => void; +} + +/** + * ReactFlow node that renders a full interactive session panel on the board canvas. + * + * Drag handle: the top strip (className="drag-handle"). + * Content area: SessionPanel with `isEjected={true}`, which adds drag handle class + * to the panel header and stop-wheel propagation to the body. + * + * All realtime subscriptions, draft persistence, and prompt input are handled + * by SessionPanel itself — identical to the sidebar variant. + */ +const EjectedSessionNode: React.FC<{ data: EjectedSessionNodeData }> = ({ data }) => { + const { token } = theme.useToken(); + + // Read live data directly from the store — no prop drilling needed. + const sessionById = useAgorStore(selectSessionById); + const branchById = useAgorStore(selectBranchById); + const { + ids: mcpServerIds, + failed: sessionMcpLoadFailed, + retry: retrySessionMcpLoad, + } = useSessionMcpServerIds(data.client, data.sessionId); + + const session = sessionById.get(data.sessionId) ?? null; + const branch = session ? (branchById.get(session.branch_id) ?? null) : null; + + // Session was deleted/archived while ejected — render nothing. + if (!session) return null; + + return ( +
+ {/* Drag-handle title bar — dragging this moves the node */} +
+ + + + {getSessionDisplayTitle(session, { includeAgentFallback: true })} + + + {/* Buttons must not initiate drag (nodrag class) */} + + +
+ + {/* Full session panel — same component as the sidebar, just sized differently */} +
e.stopPropagation()} + > + data.onRedock(data.sessionId)} + /> +
+
+ ); +}; + +export default React.memo(EjectedSessionNode); diff --git a/apps/agor-ui/src/components/SessionPanel/SessionPanel.tsx b/apps/agor-ui/src/components/SessionPanel/SessionPanel.tsx index eb4810914e..8f15b8ef6d 100644 --- a/apps/agor-ui/src/components/SessionPanel/SessionPanel.tsx +++ b/apps/agor-ui/src/components/SessionPanel/SessionPanel.tsx @@ -31,10 +31,12 @@ import { DownOutlined, EditOutlined, EllipsisOutlined, + ExpandAltOutlined, InboxOutlined, RobotOutlined, SearchOutlined, SettingOutlined, + ShrinkOutlined, UpOutlined, } from '@ant-design/icons'; import type { InputRef, MenuProps } from 'antd'; @@ -89,6 +91,10 @@ import { readPromptDraftSeed, savePromptDraft, } from '../../utils/promptDrafts'; +import { + REACT_FLOW_DRAG_HANDLE_CLASS, + REACT_FLOW_NO_DRAG_CLASS, +} from '../../utils/reactFlowDragClasses'; import { describeSessionStatus } from '../../utils/sessionStatus'; import { getSessionDisplayTitle, getSessionTitleStyles } from '../../utils/sessionTitle'; import { AgentSelectionGrid } from '../AgentSelectionGrid/AgentSelectionGrid'; @@ -377,6 +383,20 @@ export interface SessionPanelProps { open: boolean; onClose: () => void; uploadPolicy?: import('@agor/core/types').UploadIngressPolicy; + /** + * When provided, an "eject to board" button appears in the header. + * Only used in sidebar/drawer mode (not when already ejected). + */ + onEject?: () => void; + /** + * When true, the panel is rendered inside a ReactFlow canvas node. + * - The header gets the drag-handle class so the node can be dragged by it. + * - The body gets wheel-stop propagation so scrolling the conversation + * doesn't accidentally zoom the canvas. + * - The left border is suppressed (the node container provides its own border). + * - `onClose` becomes "Re-dock to sidebar" in the header button. + */ + isEjected?: boolean; } const SessionPanel: React.FC = ({ @@ -390,6 +410,8 @@ const SessionPanel: React.FC = ({ open, onClose, uploadPolicy, + onEject, + isEjected = false, }) => { const { token } = theme.useToken(); const isMobileShell = useIsMobileViewport(); @@ -1571,17 +1593,21 @@ const SessionPanel: React.FC = ({ display: open ? 'flex' : 'none', flexDirection: 'column', background: token.colorBgElevated, - // No adjacent canvas on the mobile full-screen shell, so drop the left seam. - borderLeft: isMobileShell ? undefined : `1px solid ${token.colorBorder}`, + // The ejected node container provides its own border; the mobile full-screen + // shell has no adjacent canvas, so it drops the left seam too. + borderLeft: isEjected || isMobileShell ? undefined : `1px solid ${token.colorBorder}`, }} > - {/* Header */} + {/* Header — becomes drag-handle when ejected so the user can move the canvas node */}
{/* Row 1: icon + title + badge + actions, center-aligned */} @@ -1706,7 +1732,7 @@ const SessionPanel: React.FC = ({
- + @@ -1727,8 +1753,28 @@ const SessionPanel: React.FC = ({ style={mobileHeaderButtonStyle} /> + {onEject && !isEjected && !isMobileShell && ( + +