Skip to content

Open-source, local-first AI agent for real work.

21.9 KB
Raw Blame
import { decodeRouteValue, rememberSpaceLocation, useSpaceNavigation } from "@domains/project/hooks/useSpaceNavigation";
import type {
	DesktopMcpElicitationRequest,
	DesktopMcpTask,
	DesktopMcpTasksChangedEvent,
	DesktopUserQuestionRequest,
} from "@preload/api";
import { MAIN_SPACE, spacesAtom } from "@shared/store/spaces";
import { useMatches, useNavigate } from "@tanstack/react-router";
import type { CodingAgentPlanReviewRequest } from "@vetta/coding-agent/function-extensions";
import { getDefaultStore, useAtom, useAtomValue, useSetAtom } from "jotai";
import { useCallback, useEffect, useRef, useState } from "react";
import { FILE_EDITOR_SAVE_EVENT, OPEN_MODEL_SELECTOR_EVENT, SPACE_SHORTCUT_ACTIONS } from "@/shared/shortcuts";
import { useSwitchToPreviousSession } from "../domains/command-menu/hooks/useSwitchToPreviousSession";
import { loadNewSessionPage } from "../domains/conversation/components/loadNewSessionPage";
import { useAppInit } from "../domains/conversation/hooks/useAppInit";
import { useSessionManager } from "../domains/conversation/hooks/useSessionManager";
import { useProjectActions } from "../domains/project/hooks/useProjects";
import { playNotificationSound } from "../shared/audio/notification-sound-player";
import { useAttentionSessionsSync } from "../shared/hooks/useAttentionSessionsSync";
import { useModelCatalogSync } from "../shared/hooks/useModelCatalogSync";
import { useNarrowScreen } from "../shared/hooks/useNarrowScreen";
import { usePendingInteractionsSync } from "../shared/hooks/usePendingInteractionsSync";
import { useRunningSessionsSync } from "../shared/hooks/useRunningSessionsSync";
import { useSessionPinsSync } from "../shared/hooks/useSessionPinsSync";
import { useGlobalShortcuts } from "../shared/hooks/useShortcuts";
import { useUpdaterInit } from "../shared/hooks/useUpdaterInit";
import { i18n } from "../shared/i18n";
import {
	activeSessionAtom,
	appshotAttachmentAtom,
	automationSessionLinksAtom,
	commandMenuOpenAtom,
	defaultConversationCwdAtom,
	fileEditorHasUnsavedChangesAtom,
	focusInputRequestAtom,
	groupMcpTasksBySession,
	lastActiveSessionAtom,
	mcpTasksBySessionAtom,
	pendingMcpElicitationsAtom,
	pendingPlanReviewsAtom,
	pendingQuestionsAtom,
	pendingSessionCreationAtom,
	pendingSessionOpenAtom,
	projectsAtom,
	sandboxPermissionDrawerAtom,
	sidebarCollapsedAtom,
	sidebarWidthAtom,
} from "../shared/store/atoms";
import { recordRecentSessionVisitAtom } from "../shared/store/recent-sessions-atoms";
import { startSpaceStoreSync } from "../shared/store/space-store-sync";
import { showToast } from "../shared/store/toast-atoms";
import { shouldShowChatRoutePending } from "./chat-route-pending";
import { syncPendingInteractions } from "./pending-interaction-sync";
import type { RootLayoutModel } from "./types";

type SessionRestoreState = "pending" | "restoring" | "complete";

export function useRootLayoutModel(): RootLayoutModel {
	const { openProject, ensureLocalSession } = useProjectActions();
	const projects = useAtomValue(projectsAtom);
	const navigate = useNavigate();
	const setSandboxPermissionDrawer = useSetAtom(sandboxPermissionDrawerAtom);
	const setCommandMenuOpen = useSetAtom(commandMenuOpenAtom);
	const defaultConversationCwd = useAtomValue(defaultConversationCwdAtom);
	const activeSession = useAtomValue(activeSessionAtom);
	const pendingSessionCreation = useAtomValue(pendingSessionCreationAtom);
	const pendingSessionOpen = useAtomValue(pendingSessionOpenAtom);
	const setActiveSession = useSetAtom(activeSessionAtom);
	const [lastActiveSession, setLastActiveSession] = useAtom(lastActiveSessionAtom);
	const matchesForGuard = useMatches();
	const currentPath = matchesForGuard[matchesForGuard.length - 1]?.pathname ?? "/";
	const [sidebarCollapsed, setSidebarCollapsed] = useAtom(sidebarCollapsedAtom);
	// 左栏占位宽度与侧边栏面板读同一个 atom(拖拽改宽时逐帧同步),见 SidebarDock。
	const sidebarWidth = useAtomValue(sidebarWidthAtom);
	const hasUnsavedFileChanges = useAtomValue(fileEditorHasUnsavedChangesAtom);
	const [sessionRestoreState, setSessionRestoreState] = useState<SessionRestoreState>("pending");
	const sessionRestoreAttemptedRef = useRef(false);
	const toggleSidebar = useCallback(() => {
		setSidebarCollapsed((v) => !v);
	}, [setSidebarCollapsed]);

	// 响应式侧边栏:窄屏时不挤压布局,改为悬浮浮层(hover 唤出,移出即隐藏)。
	const narrow = useNarrowScreen();
	const [overlayOpen, setOverlayOpen] = useState(false);
	const overlayCloseTimerRef = useRef<number | null>(null);
	const cancelOverlayClose = useCallback(() => {
		if (overlayCloseTimerRef.current != null) {
			window.clearTimeout(overlayCloseTimerRef.current);
			overlayCloseTimerRef.current = null;
		}
	}, []);
	const openOverlay = useCallback(() => {
		cancelOverlayClose();
		setOverlayOpen(true);
	}, [cancelOverlayClose]);
	const closeOverlay = useCallback(() => {
		cancelOverlayClose();
		setOverlayOpen(false);
	}, [cancelOverlayClose]);
	// 触发按钮 → 浮层之间留出短暂宽限,避免指针经过间隙时闪烁。
	const scheduleOverlayClose = useCallback(() => {
		cancelOverlayClose();
		overlayCloseTimerRef.current = window.setTimeout(() => setOverlayOpen(false), 120);
	}, [cancelOverlayClose]);
	// 退出窄屏时复位浮层状态。
	useEffect(() => {
		if (!narrow) {
			cancelOverlayClose();
			setOverlayOpen(false);
		}
	}, [narrow, cancelOverlayClose]);

	useAppInit();
	useUpdaterInit();
	// 模型目录保鲜:focus / 切回可见时按 TTL 重拉,服务端增删模型无需重启应用。
	useModelCatalogSync();
	// 全局 running-sessions 订阅必须挂在始终挂载的 App 上:它是 streaming 状态真值
	// 来源之一,挂在会被卸载的 Sidebar 上会在卸载期间丢 RUNNING_CHANGED 事件。
	useRunningSessionsSync();
	const recordRecentSessionVisit = useSetAtom(recordRecentSessionVisitAtom);
	useAttentionSessionsSync();
	// 同上:侧栏的「等你处理」标记也以主进程为真值,挂在会被卸载的侧栏上会漏事件。
	usePendingInteractionsSync();
	// 会话置顶以主进程为准(手机也会改它),同理挂在根部。
	useSessionPinsSync();
	// 队列的出队/续发已收归主进程 kernel(ADR-0060):followUp 在 turn 自然停止点
	// 接力消费,renderer 不再需要全局出队调度器。
	// 会话打开/发送的唯一挂载点。ChatPage 与新会话页走模块级 ref,避免再挂一份。
	const { openSession } = useSessionManager();
	const switchSpace = useSpaceNavigation();
	const activePath = activeSession?.sessionPath;
	const activeCwd = activeSession?.cwd;
	useEffect(() => {
		if (!defaultConversationCwd) return;
		const store = getDefaultStore();
		if (currentPath === "/" && activePath && activeCwd) {
			rememberSpaceLocation(store, { kind: "conversation", path: activePath, cwd: activeCwd });
		} else if (currentPath.startsWith("/project/")) {
			rememberSpaceLocation(store, { kind: "project", cwd: decodeRouteValue(currentPath.slice(9)) });
		} else if (currentPath.startsWith("/agent-teams/") && currentPath.includes("/sessions/")) {
			const [, , rawTeam, , rawSession] = currentPath.split("/");
			if (!rawTeam || !rawSession) return;
			const teamId = decodeRouteValue(rawTeam);
			const sessionId = decodeRouteValue(rawSession);
			let cancelled = false;
			void window.vetta.agentTeams
				.listSessions(teamId)
				.then((sessions) => {
					const session = sessions.find(({ id }) => id === sessionId);
					if (cancelled || !session) return;
					rememberSpaceLocation(store, {
						kind: "team",
						teamId,
						sessionId,
						projectCwd: session.workspaceKind === "project" ? session.cwd : undefined,
					});
				})
				.catch((error: unknown) => console.warn("[space] remember Team session failed", error));
			return () => {
				cancelled = true;
			};
		}
	}, [activeCwd, activePath, currentPath, defaultConversationCwd]);

	useEffect(() => {
		if (!hasUnsavedFileChanges) return;
		const preventClose = (event: BeforeUnloadEvent) => {
			event.preventDefault();
			event.returnValue = "";
		};
		window.addEventListener("beforeunload", preventClose);
		return () => window.removeEventListener("beforeunload", preventClose);
	}, [hasUnsavedFileChanges]);

	// 没有待恢复会话时提前加载 NewSession 路由代码;侧栏项目/会话列表可继续独立加载。
	// 页面本身仍等路由守卫确认后再挂载,避免其初始化 effect 清除待恢复记录。
	useEffect(() => {
		if (currentPath !== "/" || activeSession || pendingSessionCreation || pendingSessionOpen || lastActiveSession)
			return;
		void loadNewSessionPage().catch((error: unknown) => {
			console.warn("[RootLayout] preload new session page failed", error);
		});
	}, [currentPath, activeSession, pendingSessionCreation, pendingSessionOpen, lastActiveSession]);

	// 刷新根路由时先用持久化的 cwd + sessionPath 重建 runtime session。
	// 持久化定位信息已足够恢复,无需等待默认 cwd 或侧栏历史列表完成加载。
	// runtimeId 不能跨 renderer 生命周期复用,必须重新走 openSession/session.create。
	useEffect(() => {
		if (currentPath !== "/" || !defaultConversationCwd || sessionRestoreAttemptedRef.current) {
			return;
		}
		sessionRestoreAttemptedRef.current = true;
		const state = getDefaultStore().get(spacesAtom);
		if (
			!activeSession &&
			!pendingSessionCreation &&
			!pendingSessionOpen &&
			(state.selected !== MAIN_SPACE || state.locations[MAIN_SPACE])
		) {
			setSessionRestoreState("restoring");
			void switchSpace(state.selected, true).finally(() => setSessionRestoreState("complete"));
			return;
		}
		if (activeSession || pendingSessionCreation || pendingSessionOpen || !lastActiveSession) {
			setSessionRestoreState("complete");
			return;
		}
		setSessionRestoreState("restoring");
		void openSession(lastActiveSession.cwd, lastActiveSession.sessionPath)
			.catch((error: unknown) => {
				console.warn("[RootLayout] restore active session failed", error);
				setActiveSession(null);
				setLastActiveSession(null);
			})
			.finally(() => setSessionRestoreState("complete"));
	}, [
		currentPath,
		activeSession,
		pendingSessionCreation,
		pendingSessionOpen,
		lastActiveSession,
		defaultConversationCwd,
		switchSpace,
		openSession,
		setActiveSession,
		setLastActiveSession,
	]);

	// 路由守卫:仅在确认没有可恢复会话后,才跳到默认「对话」项目的 NewSession 页。
	useEffect(() => {
		if (
			currentPath !== "/" ||
			activeSession ||
			pendingSessionCreation ||
			pendingSessionOpen ||
			!defaultConversationCwd ||
			sessionRestoreState !== "complete"
		) {
			return;
		}
		void navigate({
			to: "/new-session/$cwd",
			params: { cwd: encodeURIComponent(defaultConversationCwd) },
		});
	}, [
		currentPath,
		activeSession,
		pendingSessionCreation,
		pendingSessionOpen,
		defaultConversationCwd,
		sessionRestoreState,
		navigate,
	]);

	// 上报「聊天页当前所在 session」给主进程:仅在聊天路由 "/" 且有 activeSession
	// 时报其 sessionPath,否则 null。主进程据此 + 窗口聚焦态做系统通知抑制判定。
	// 同一时机记一次「最近打开」:命令面板据此把打开过的会话排在前面。
	useEffect(() => {
		const sessionPath = currentPath === "/" ? activeSession?.sessionPath || null : null;
		void window.vetta.notification.setForegroundSession(sessionPath);
		if (sessionPath) recordRecentSessionVisit(sessionPath);
	}, [currentPath, activeSession, recordRecentSessionVisit]);

	// 点击系统通知 → 主进程已前台化窗口,这里把对应 session 打开并路由到聊天页。
	useEffect(() => {
		return window.vetta.notification.onNavigate((payload) => {
			if (payload.type === "agent-turn-complete" || payload.type === "agent-question-pending") {
				void openSession(payload.cwd, payload.sessionPath);
				return;
			}
			if (payload.type === "remote-settings") {
				void navigate({ to: "/settings/$tab", params: { tab: "remote" } });
			}
		});
	}, [openSession, navigate]);

	useEffect(
		() =>
			window.vetta.notification.onSound(({ soundId, volume }) => {
				void playNotificationSound(soundId, volume);
			}),
		[],
	);

	useEffect(() => {
		const store = getDefaultStore();
		const unsubCaptured = window.vetta.appshot.onCaptured((payload) => {
			store.set(appshotAttachmentAtom, {
				id: payload.id,
				appName: payload.appName,
				windowTitle: payload.windowTitle,
				documentPath: payload.documentPath,
				imagePath: payload.imagePath,
				iconPath: payload.iconPath,
				textPath: payload.textPath,
				capturedAt: payload.capturedAt,
			});
			if (currentPath !== "/" && !currentPath.startsWith("/new-session") && defaultConversationCwd) {
				void navigate({
					to: "/new-session/$cwd",
					params: { cwd: encodeURIComponent(defaultConversationCwd) },
				});
			}
			store.set(focusInputRequestAtom, (previous) => previous + 1);
		});
		const unsubCaptureError = window.vetta.appshot.onCaptureError((payload) => {
			const message =
				payload.reason === "self-capture"
					? i18n.t("chat:appshot.errorSelfCapture")
					: payload.reason === "no-permission"
						? i18n.t("chat:appshot.errorNoPermission")
						: i18n.t("chat:appshot.errorHelperFailed");
			showToast({ variant: "warning", message });
		});
		return () => {
			unsubCaptured();
			unsubCaptureError();
		};
	}, [currentPath, defaultConversationCwd, navigate]);

	// 工作空间的事实源在主进程的 ~/.vetta(ADR-0160);本地 localStorage 只作首帧缓存与降级兼容。
	useEffect(
		() =>
			startSpaceStoreSync(
				getDefaultStore(),
				{
					sync: (request) => window.vetta.project.syncSpaces(request),
					save: (data) => window.vetta.project.saveSpaces(data),
					onChanged: (handler) => window.vetta.project.onSpacesChanged(handler),
				},
				{ onError: (error) => console.warn("[RootLayout] sync workspace store failed", error) },
			),
		[],
	);

	// 主进程持有「等待用户处理」的真相源;三类请求共用同一套订阅 + 快照收敛。
	const setPendingQuestions = useSetAtom(pendingQuestionsAtom);
	useEffect(
		() =>
			syncPendingInteractions<DesktopUserQuestionRequest>(
				{
					onRequest: (handler) => window.vetta.session.onQuestionRequest(handler),
					onResolved: (handler) => window.vetta.session.onQuestionResolved(handler),
					listPending: () => window.vetta.session.listPendingQuestions(),
				},
				setPendingQuestions,
				(error) => console.warn("[RootLayout] sync pending questions failed", error),
			),
		[setPendingQuestions],
	);

	const setPendingMcpElicitations = useSetAtom(pendingMcpElicitationsAtom);
	useEffect(
		() =>
			syncPendingInteractions<DesktopMcpElicitationRequest>(
				{
					onRequest: (handler) => window.vetta.session.onMcpElicitationRequest(handler),
					onResolved: (handler) => window.vetta.session.onMcpElicitationResolved(handler),
					listPending: () => window.vetta.session.listPendingMcpElicitations(),
				},
				setPendingMcpElicitations,
				(error) => console.warn("[RootLayout] sync pending MCP elicitations failed", error),
			),
		[setPendingMcpElicitations],
	);

	const setPendingPlanReviews = useSetAtom(pendingPlanReviewsAtom);
	useEffect(
		() =>
			syncPendingInteractions<CodingAgentPlanReviewRequest>(
				{
					onRequest: (handler) => window.vetta.session.onPlanReviewRequest(handler),
					onResolved: (handler) => window.vetta.session.onPlanReviewResolved(handler),
					listPending: () => window.vetta.session.listPendingPlanReviews(),
				},
				setPendingPlanReviews,
				(error) => console.warn("[RootLayout] sync pending plan reviews failed", error),
			),
		[setPendingPlanReviews],
	);

	const setMcpTasks = useSetAtom(mcpTasksBySessionAtom);
	useEffect(() => {
		let active = true;
		let latest: readonly DesktopMcpTask[] | undefined;
		const apply = (tasks: readonly DesktopMcpTask[]): void => {
			latest = tasks;
			setMcpTasks(groupMcpTasksBySession(tasks));
		};
		const unsubscribe = window.vetta.session.onMcpTasksChanged((event: DesktopMcpTasksChangedEvent) => {
			if (active) apply(event.tasks);
		});
		void window.vetta.session
			.listMcpTasks()
			.then((snapshot) => {
				if (active && latest === undefined) apply(snapshot);
			})
			.catch((error: unknown) => console.warn("[RootLayout] sync MCP tasks failed", error));
		return () => {
			active = false;
			unsubscribe();
		};
	}, [setMcpTasks]);

	const grantQueueRef = useRef<Parameters<Parameters<typeof window.vetta.session.onSandboxGrantRequest>[0]>[0][]>([]);
	const grantActiveRef = useRef(false);

	useEffect(() => {
		const showGrant = (request: Parameters<Parameters<typeof window.vetta.session.onSandboxGrantRequest>[0]>[0]) => {
			grantActiveRef.current = true;
			const showNext = () => {
				const nextRequest = grantQueueRef.current.shift();
				if (nextRequest) {
					showGrant(nextRequest);
				} else {
					grantActiveRef.current = false;
				}
			};
			setSandboxPermissionDrawer({
				requestId: request.requestId,
				runtimeId: request.sessionId,
				title: request.title,
				message: request.message,
				sensitive: request.sensitive,
				onConfirm: () => {
					void window.vetta.session.respondToSandboxGrant(request.requestId, "allow_once");
					setSandboxPermissionDrawer(null);
					showNext();
				},
				onCancel: () => {
					void window.vetta.session.respondToSandboxGrant(request.requestId, "deny");
					setSandboxPermissionDrawer(null);
					showNext();
				},
				onAllowSession: request.sensitive
					? undefined
					: () => {
							void window.vetta.session.respondToSandboxGrant(request.requestId, "allow_session");
							setSandboxPermissionDrawer(null);
							showNext();
						},
			});
		};
		return window.vetta.session.onSandboxGrantRequest((request) => {
			if (grantActiveRef.current) {
				grantQueueRef.current.push(request);
				return;
			}
			showGrant(request);
		});
	}, [setSandboxPermissionDrawer]);

	// 调度任务(自动化)"立即执行"时,session 在 main 进程已经建好,但 JSONL
	// 要等 assistant 首个回复才落盘。这里订阅 task.started,乐观地把 session
	// 插入 sidebar,避免必须等 agent 跑完才出现的延迟。
	const setAutomationSessionLinks = useSetAtom(automationSessionLinksAtom);
	useEffect(() => {
		// 会话与自动化的归属由主进程按执行记录与任务配置算出;任务或记录变化后整体重拉,
		// 保证会话组、换绑后的旧会话、被删除的会话都与主进程一致。
		const refreshLinks = (): void => {
			void window.vetta.scheduler.getSessionLinks().then((links) => {
				setAutomationSessionLinks(new Map(links.map((link) => [link.sessionPath, link])));
			});
		};
		refreshLinks();
		return window.vetta.scheduler.onTaskEvent((event) => {
			if (event.type !== "task.started") {
				refreshLinks();
				return;
			}
			if (!event.sessionPath || !event.listCwd) return;
			setAutomationSessionLinks((prev) => {
				const next = new Map(prev);
				next.set(event.sessionPath, {
					sessionPath: event.sessionPath,
					taskId: event.taskId,
					taskName: event.taskName,
					mode: event.mode,
				});
				return next;
			});
			ensureLocalSession(event.listCwd, {
				id: event.sessionId,
				path: event.sessionPath,
				cwd: event.listCwd,
				name: event.sessionName,
				firstMessage: event.firstMessage,
				modifiedAt: Date.now(),
			});
		});
	}, [ensureLocalSession, setAutomationSessionLinks]);

	// ─── Global keyboard shortcuts ───
	const projectsRef = useRef(projects);
	projectsRef.current = projects;

	const defaultCwdRef = useRef(defaultConversationCwd);
	defaultCwdRef.current = defaultConversationCwd;

	const currentPathRef = useRef(currentPath);
	currentPathRef.current = currentPath;
	const activeSessionPathRef = useRef<string | null>(null);
	activeSessionPathRef.current = activeSession?.sessionPath || null;
	const switchToPreviousSession = useSwitchToPreviousSession({ onOpenSession: openSession });

	useGlobalShortcuts(
		useCallback(
			(actionId: string) => {
				const spaceIndex = SPACE_SHORTCUT_ACTIONS.findIndex(({ id }) => id === actionId);
				if (spaceIndex >= 0) {
					const { spaces } = getDefaultStore().get(spacesAtom);
					const id = spaceIndex === 0 ? MAIN_SPACE : spaces[spaceIndex - 1]?.id;
					if (id) void switchSpace(id);
					return;
				}
				switch (actionId) {
					case "new-session": {
						// 默认走「对话」项目的 NewSession 页面;若主进程尚未返回 cwd,退回第一个项目。
						const target = defaultCwdRef.current || projectsRef.current[0]?.cwd;
						if (target) {
							void navigate({
								to: "/new-session/$cwd",
								params: { cwd: encodeURIComponent(target) },
							});
						}
						break;
					}
					case "open-project": {
						void openProject();
						break;
					}
					case "open-settings": {
						void navigate({ to: "/settings/$tab", params: { tab: "general" } });
						break;
					}
					case "open-command-menu": {
						// 面板内自己绑了一条开关键用于关闭;能走到这里说明面板是关着的。
						setCommandMenuOpen(true);
						break;
					}
					case "previous-session": {
						// 「当前」与记最近打开的口径一致:只有聊天页上开着的会话才算。
						switchToPreviousSession(currentPathRef.current === "/" ? activeSessionPathRef.current : null);
						break;
					}
					case "open-model-selector": {
						window.dispatchEvent(new Event(OPEN_MODEL_SELECTOR_EVENT));
						break;
					}
					case "save-file": {
						window.dispatchEvent(new Event(FILE_EDITOR_SAVE_EVENT));
						break;
					}
				}
			},
			[openProject, navigate, setCommandMenuOpen, switchSpace, switchToPreviousSession],
		),
	);

	return {
		actions: {
			closeOverlay,
			openOverlay,
			scheduleOverlayClose,
			toggleSidebar,
		},
		narrow,
		onOpenSession: openSession,
		overlayOpen,
		routePending: shouldShowChatRoutePending({
			hasActiveSession: Boolean(activeSession),
			hasDefaultConversation: Boolean(defaultConversationCwd),
			hasPendingSessionCreation: Boolean(pendingSessionCreation),
			hasPendingSessionOpen: Boolean(pendingSessionOpen),
			isChatRoute: currentPath === "/",
			sessionRestoreComplete: sessionRestoreState === "complete",
		}),
		sidebarCollapsed,
		sidebarWidth,
	};
}