Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 78 additions & 5 deletions apps/agor-ui/src/components/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -425,6 +426,31 @@ export const App: React.FC<AppProps> = ({
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
Expand All @@ -439,8 +465,15 @@ export const App: React.FC<AppProps> = ({
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] });
Expand Down Expand Up @@ -515,10 +548,6 @@ export const App: React.FC<AppProps> = ({
// 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<boolean>(
'agor:commentsPanelCollapsed',
Expand Down Expand Up @@ -864,6 +893,37 @@ export const App: React.FC<AppProps> = ({
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([]);
Expand Down Expand Up @@ -975,6 +1035,10 @@ export const App: React.FC<AppProps> = ({

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);
Expand Down Expand Up @@ -1494,6 +1558,10 @@ export const App: React.FC<AppProps> = ({
onOpenCommentsPanel={handleOpenCommentsPanel}
onCommentHover={setHoveredCommentId}
onCommentSelect={handleCommentSelect}
ejectedSessions={ejectedSessions}
onEjectSessionRedock={handleRedockSession}
onEjectSessionClose={handleCloseEjectedSession}
onUpdateEjectedPosition={updateEjectedPosition}
/>
)}
</div>
Expand Down Expand Up @@ -1541,6 +1609,11 @@ export const App: React.FC<AppProps> = ({
open={!!effectiveSelectedSessionId}
onClose={handleCloseSessionPanel}
uploadPolicy={uploadPolicy}
onEject={
effectiveSelectedSessionId
? () => handleEjectSession(effectiveSelectedSessionId)
: undefined
}
/>
</div>
</Flex>
Expand Down
117 changes: 109 additions & 8 deletions apps/agor-ui/src/components/SessionCanvas/SessionCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, { x: number; y: number }>;
/** 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<SessionCanvasProps['ejectedSessions']> = {};

export interface SessionCanvasRef {
getViewportCenter: () => { x: number; y: number } | null;
}
Expand Down Expand Up @@ -459,6 +476,7 @@ const nodeTypes = {
markdown: MarkdownNode,
appNode: AppNode,
artifactNode: ArtifactNode,
ejectedSessionNode: EjectedSessionNode,
};

const EMPTY_BOARD_ENTITY_OBJECTS: BoardEntityObject[] = Object.freeze(
Expand Down Expand Up @@ -560,6 +578,10 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
staticCursorScale,
height = '100vh',
readOnly = false,
ejectedSessions = NO_EJECTED_SESSIONS,
onEjectSessionRedock,
onEjectSessionClose,
onUpdateEjectedPosition,
}: SessionCanvasProps,
ref
) => {
Expand Down Expand Up @@ -1638,6 +1660,27 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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(() => [], []);
Expand Down Expand Up @@ -2073,6 +2116,7 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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;
Expand Down Expand Up @@ -2108,6 +2152,7 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
const cards: Node[] = [];
const apps: Node[] = [];
const comments: Node[] = [];
const ejected: Node[] = [];
for (const node of nodes) {
switch (node.type) {
case 'zone':
Expand All @@ -2129,24 +2174,28 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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[],
markdown: Node[],
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 }
);
},
Expand All @@ -2168,7 +2217,7 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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
Expand Down Expand Up @@ -2210,7 +2259,7 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
const updatedCards = applyLocalPositions(cardNodes, currentNodesById, zones);

return layoutZoneGrids(
applyZOrder(zones, markdown, updatedBranches, updatedCards, comments, apps)
applyZOrder(zones, markdown, updatedBranches, updatedCards, comments, apps, ejected)
);
});
}, [
Expand Down Expand Up @@ -2250,7 +2299,8 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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).
Expand Down Expand Up @@ -2303,10 +2353,47 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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);
Expand Down Expand Up @@ -2594,6 +2681,19 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
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-<sessionId>`)
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;
Expand Down Expand Up @@ -3048,6 +3148,7 @@ const SessionCanvasInner = forwardRef<SessionCanvasRef, SessionCanvasProps>(
reorderInZone,
enterArrangedZone,
shownSizeOf,
onUpdateEjectedPosition,
]
);

Expand Down
Loading
Loading