"use client" import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from "react" import { usePathname, useRouter } from "next/navigation" import { Menu, MessageSquare, PanelLeft, X } from "lucide-react" import { bindSessionLocalProject, createSession, decideApproval, decideHarnessInteraction, getAgent, getSession, listApprovals, listConnectors, listSessions, streamTurn, syncSession, type FileProposalDto, type LocalProjectDto, } from "@/modules/nova-web/api" import { applyFileProposalsLocally, recoverProposalsFromBody, stripProposalTrailer, } from "@/modules/nova-web/apply-proposals" import { AgentsView } from "@/modules/nova-web/components/agents" import { ApprovalsView } from "@/modules/nova-web/components/approvals" import { AutomationsView } from "@/modules/nova-web/components/automations" import { ConnectionsView } from "@/modules/nova-web/components/connections" import { EmptyHome } from "@/modules/nova-web/components/home" import { MoreView } from "@/modules/nova-web/components/more" import { PullDetailView } from "@/modules/nova-web/components/pull-detail" import { PullsView } from "@/modules/nova-web/components/pulls" import { SettingsView } from "@/modules/nova-web/components/settings" import { normalizeSettingsSection, type SettingsSectionId, } from "@/modules/nova-web/settings-sections" import { NovaSidebar } from "@/modules/nova-web/components/sidebar" import { NovaMark } from "@/modules/nova-web/components/timeline" import { ThreadView } from "@/modules/nova-web/components/thread" import { SideThreadGroup } from "@/modules/nova-web/components/side-thread-group" import { Composer } from "@/modules/nova-web/components/composer" import { DEFAULT_NOVA_AGENT_MODE, DEFAULT_NOVA_MODEL, DEFAULT_NOVA_PROVIDER, type HarnessProvider, type NovaAgentMode, type NovaEffort, } from "@/modules/nova-web/models" import { parseModelSelection } from "@/modules/nova-web/model-settings" import { CodexCatalogContext, useAccountCodexCatalog } from "@/modules/nova-web/codex-catalog" import { MachineSettingsContext, useAccountMachineSettings } from "@/modules/nova-web/machine-settings" import { machineSizeSchema, type MachineSize } from "@/modules/nova/sandbox/machine-sizes" import { resolveNovaTurnMode } from "@/modules/nova-web/resolve-mode" import type { AgentSessionSummary, ApprovalRequest, ConnectorStatus, NovaUser, SessionDetail, TimelineActivity, TimelineEntry, WorkspaceView, } from "@/modules/nova-web/types" import { reduceWorkingSteps, tickWorkingSteps, type WorkingStep, } from "@/modules/nova-web/working-steps" import { getActiveLocalProjectId, restoreLocalWorkspace, setVirtualProjectIndex, type LocalWorkspaceState, } from "@/modules/nova-web/local-workspace" import { packLocalProjectForTurn } from "@/modules/nova-web/project-pack" import { useGitWorkspace } from "@/modules/nova-web/use-git-workspace" import { workspacePublishIntent } from "@/modules/nova-web/git-workspace" import { GitWorkspaceControls } from "@/modules/nova-web/components/git-workspace-controls" import type { ProjectSelection } from "@/modules/nova-web/components/project-picker" import type { LocalAttachment } from "@/modules/nova/attachments/contracts" import type { NovaReference } from "@/modules/nova/references/contracts" import { ACTIVE_REFRESH_MS, IDLE_REFRESH_MS, CONNECTOR_FRESH_MS, createRefreshGate } from "./refresh-policy" import { useVisiblePolling } from "./use-visible-polling" const PENDING_TURN_KEY = "nova:pending-turn" function mergeProposals(current: FileProposalDto[], incoming: FileProposalDto[]): FileProposalDto[] { const map = new Map(current.map((item) => [item.path, item])) for (const item of incoming) map.set(item.path, item) return [...map.values()] } type PendingTurn = { sessionId: string content: string model: string provider: HarnessProvider effort: NovaEffort mode: NovaAgentMode machineSize?: MachineSize references?: NovaReference[] localAttachments?: LocalAttachment[] } type NovaAppProps = { initialSessions: AgentSessionSummary[] user: NovaUser initialSessionId?: string | null initialPullId?: string | null initialView?: WorkspaceView initialSettingsSection?: string | null embedded?: boolean parentSessionId?: string onSideSessionCreated?: (session: AgentSessionSummary) => void } function readPendingTurn(): PendingTurn | null { if (typeof window === "undefined") return null try { const raw = sessionStorage.getItem(PENDING_TURN_KEY) if (!raw) return null const parsed = JSON.parse(raw) as PendingTurn if (!parsed?.sessionId || !parsed?.content) return null return parsed } catch { return null } } function writePendingTurn(turn: PendingTurn) { sessionStorage.setItem(PENDING_TURN_KEY, JSON.stringify(turn)) } function clearPendingTurn() { sessionStorage.removeItem(PENDING_TURN_KEY) } function parseRoute(pathname: string): { view: WorkspaceView sessionId: string | null agentId: string | null pullId: string | null } { const clean = pathname.replace(/\/nova-app-internal/g, "") || "/" if (clean.startsWith("/s/")) { return { view: "session", sessionId: clean.slice(3).split("/")[0] || null, agentId: null, pullId: null, } } const agentChatMatch = clean.match(/^\/agents\/([^/]+)\/chats\/([^/]+)/) if (agentChatMatch) { return { view: "agent-chat", sessionId: decodeURIComponent(agentChatMatch[2]), agentId: decodeURIComponent(agentChatMatch[1]), pullId: null, } } if (clean.startsWith("/pulls/")) { return { view: "pull", sessionId: null, agentId: null, pullId: decodeURIComponent(clean.slice("/pulls/".length).split("/")[0] || ""), } } if (clean.startsWith("/pulls")) return { view: "pulls", sessionId: null, agentId: null, pullId: null } if (clean.startsWith("/agents")) return { view: "agents", sessionId: null, agentId: null, pullId: null } if (clean.startsWith("/automations")) return { view: "automations", sessionId: null, agentId: null, pullId: null } if (clean.startsWith("/approvals")) return { view: "approvals", sessionId: null, agentId: null, pullId: null } if (clean.startsWith("/connections")) return { view: "connections", sessionId: null, agentId: null, pullId: null } if (clean.startsWith("/more")) return { view: "more", sessionId: null, agentId: null, pullId: null } if (clean.startsWith("/settings")) return { view: "settings", sessionId: null, agentId: null, pullId: null } return { view: "home", sessionId: null, agentId: null, pullId: null } } function mergeTimeline( current: TimelineEntry[], messages: TimelineEntry[], activities: TimelineEntry[], ): TimelineEntry[] { const map = new Map() for (const entry of [...current, ...messages, ...activities]) { map.set(`${entry.kind}-${entry.id}`, entry) } return [...map.values()].sort((a, b) => a.sequence - b.sequence) } export function NovaApp({ initialSessions, user, initialSessionId = null, initialPullId = null, initialView = "home", initialSettingsSection = null, embedded = false, parentSessionId, onSideSessionCreated, }: NovaAppProps) { const [embeddedSessionId, setEmbeddedSessionId] = useState(initialSessionId) const [embeddedPendingTurn, setEmbeddedPendingTurn] = useState(null) const [projectLocked, setProjectLocked] = useState(false) const router = useRouter() const pathname = usePathname() const search = typeof window !== "undefined" ? window.location.search : "" const settingsSection = useMemo(() => { const raw = initialSettingsSection ?? (typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("section") : null) return normalizeSettingsSection(raw) }, [initialSettingsSection, search]) const route = useMemo(() => { if (embedded) return { view: "session" as const, sessionId: embeddedSessionId, agentId: null, pullId: null } const parsed = parseRoute(pathname) if (!pathname || pathname === "/") { if (initialPullId) { return { view: "pull" as const, sessionId: null, agentId: null, pullId: initialPullId } } return { view: initialSessionId ? "session" as const : initialView, sessionId: initialSessionId, agentId: null, pullId: null, } } return parsed }, [embedded, embeddedSessionId, pathname, initialPullId, initialSessionId, initialView]) const selectedId = route.sessionId const selectedAgentId = route.agentId const isAgentChat = route.view === "agent-chat" const [refresh] = useState(() => createRefreshGate()) const [sessions, setSessions] = useState(initialSessions) const [session, setSession] = useState(null) const [agentChatAgent, setAgentChatAgent] = useState(null) const [timeline, setTimeline] = useState([]) const [cursor, setCursor] = useState(0) const [approvals, setApprovals] = useState([]) const [connectors, setConnectors] = useState([]) const [query, setQuery] = useState("") const [sidebarOpen, setSidebarOpen] = useState(false) const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true) useEffect(() => { if (!isAgentChat || !selectedAgentId) { setAgentChatAgent(null) return } let active = true void getAgent(selectedAgentId).then(({ agent }) => { if (!active) return setAgentChatAgent(agent) setProvider(agent.provider as HarnessProvider) setModel(agent.model) setEffort(agent.effort as NovaEffort) setAgentMode("chat") }).catch(() => { if (active) setAgentChatAgent(null) }) return () => { active = false } }, [isAgentChat, selectedAgentId]) useEffect(() => { try { const saved = localStorage.getItem(`nova:sidebar:v1:${user.id}`) if (saved !== null) queueMicrotask(() => setDesktopSidebarOpen(saved !== "closed")) } catch { /* Optional preference. */ } }, [user.id]) function toggleDesktopSidebar(open: boolean) { setDesktopSidebarOpen(open) try { localStorage.setItem(`nova:sidebar:v1:${user.id}`, open ? "open" : "closed") } catch { /* Optional preference. */ } } const [detailsOpen, setDetailsOpen] = useState(!embedded) const [draft, setDraft] = useState("") const [references, setReferences] = useState([]) const [localFiles, setLocalFiles] = useState([]) const [localProject, setLocalProject] = useState(null) const gitWorkspace = useGitWorkspace(user.id, selectedId, localProject?.id ?? null, !embedded && !isAgentChat) const { ensure: ensureGitWorkspace, client: gitClient, requestPublish } = gitWorkspace const [model, setModel] = useState(DEFAULT_NOVA_MODEL) const [provider, setProvider] = useState(DEFAULT_NOVA_PROVIDER) const [effort, setEffort] = useState("high") const [agentMode, setAgentMode] = useState(DEFAULT_NOVA_AGENT_MODE) const [streaming, setStreaming] = useState(false) const [streamingText, setStreamingText] = useState("") const [streamPhase, setStreamPhase] = useState(null) const [workingSteps, setWorkingSteps] = useState([]) const [workingSince, setWorkingSince] = useState(null) const [completedWorkByRunId, setCompletedWorkByRunId] = useState>({}) /** Pending / applied agent file proposals for the active thread. */ const [fileProposals, setFileProposals] = useState([]) const [applyStatus, setApplyStatus] = useState(null) const [decidingApprovalId, setDecidingApprovalId] = useState(null) const [decidingInteractionId, setDecidingInteractionId] = useState(null) const [error, setError] = useState(null) const [isPending, startTransition] = useTransition() const abortRef = useRef(false) const cursorRef = useRef(0) const streamingRef = useRef(false) const turnStartedRef = useRef(null) const activeRunIdRef = useRef(null) const workingSinceRef = useRef(null) const workingStepsRef = useRef([]) const selectedSessionRef = useRef(selectedId) useEffect(() => { selectedSessionRef.current = selectedId }, [selectedId]) const selectedPullId = route.pullId const view = route.view const codexCatalog = useAccountCodexCatalog(user.id) const machineSettings = useAccountMachineSettings(user.id) const { size: machineSize, select: selectMachineSize } = machineSettings const pendingApprovals = approvals.filter((item) => item.status === "pending").length const navigate = useCallback( (href: string) => { setSidebarOpen(href.startsWith("/agents")) setReferences([]) setLocalFiles([]) router.push(href) }, [router], ) useEffect(() => { if (isAgentChat) return let cancelled = false void Promise.resolve().then(() => { if (cancelled || readPendingTurn()) return try { const selection = parseModelSelection(localStorage.getItem(`nova:model-selection:v2:${user.id}`)) ?? parseModelSelection(sessionStorage.getItem(`nova:model-selection:v1:${user.id}`)) if (selection) { setProvider(selection.provider) setModel(selection.model) if (selection.effort) setEffort(selection.effort) localStorage.setItem(`nova:model-selection:v2:${user.id}`, JSON.stringify(selection)) } } catch { // Storage can be unavailable in restricted browsers. } }) return () => { cancelled = true } }, [isAgentChat, user.id]) const openSettingsSection = useCallback((next: SettingsSectionId) => { const href = next === "general" ? "/settings" : `/settings?section=${next}` navigate(href) }, [navigate]) useEffect(() => { if (view !== "settings") return const raw = typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("section") : initialSettingsSection if (raw && normalizeSettingsSection(raw) !== raw) { navigate("/settings") } }, [initialSettingsSection, navigate, view]) const setSyncCursor = useCallback((value: number | ((current: number) => number)) => { setCursor((current) => { const next = typeof value === "function" ? value(current) : value cursorRef.current = next return next }) }, []) const hasActiveWork = streaming || pendingApprovals > 0 || sessions.some((item) => Boolean(item.activeRunId)) const refreshInterval = hasActiveWork ? ACTIVE_REFRESH_MS : IDLE_REFRESH_MS const refreshConnectors = useCallback((force = false) => refresh(`${user.id}:connectors`, async () => { const result = await listConnectors() setConnectors(result.connectors) }, CONNECTOR_FRESH_MS, force), [refresh, user.id]) const loadSharedState = useCallback(async (force = true) => { const results = await Promise.allSettled([ refresh(`${user.id}:sessions`, async () => { const result = await listSessions() setSessions(result.sessions) }, refreshInterval, force), refresh(`${user.id}:approvals`, async () => { const result = await listApprovals() setApprovals(Array.isArray(result) ? result : result.approvals) }, refreshInterval, force), refreshConnectors(), ]) const failure = results.find((result) => result.status === "rejected") if (failure?.status === "rejected") { setError(failure.reason instanceof Error ? failure.reason.message : "Could not refresh Nova") } }, [refresh, refreshConnectors, refreshInterval, user.id]) const refreshSharedState = useCallback(() => loadSharedState(false), [loadSharedState]) useVisiblePolling(refreshSharedState, refreshInterval, true) const forceRefreshConnectors = useCallback(() => { void refreshConnectors(true).catch((error) => { setError(error instanceof Error ? error.message : "Could not refresh connectors") }) }, [refreshConnectors]) const loadSession = useCallback(async (sessionId: string, reset = false) => { const [detailResponse, sync] = await Promise.all([ getSession(sessionId), syncSession(sessionId, reset ? 0 : cursorRef.current, 500), ]) if (selectedSessionRef.current !== sessionId) return detailResponse.session setSession(detailResponse.session) setLocalProject(detailResponse.session.localProject ?? null) if (!embedded && detailResponse.session.localProject) { const project = detailResponse.session.localProject setVirtualProjectIndex({ projectId: project.id, displayName: project.displayName, rootName: project.rootName, paths: project.paths ?? [], repositoryFullName: project.repositoryFullName, }) if (!project.repositoryFullName) { void restoreLocalWorkspace(project.id).catch(() => undefined) } } else if (!embedded) { setVirtualProjectIndex(null) } if (reset) { setTimeline( mergeTimeline( [], sync.messages.map((entry) => ({ ...entry, kind: "message" as const })), sync.activities.map((entry) => ({ ...entry, kind: "activity" as const })), ), ) setSyncCursor(sync.nextSequence) } else { setTimeline((current) => mergeTimeline( current, sync.messages.map((entry) => ({ ...entry, kind: "message" as const })), sync.activities.map((entry) => ({ ...entry, kind: "activity" as const })), ), ) setSyncCursor((value) => Math.max(value, sync.nextSequence)) } return detailResponse.session }, [embedded, setSyncCursor]) const pullSync = useCallback((sessionId: string, force = true) => refresh(`${user.id}:sync:${sessionId}`, async () => { if (selectedSessionRef.current !== sessionId) return let after = cursorRef.current let guard = 0 while (guard < 20) { guard += 1 const page = await syncSession(sessionId, after, 200) if (selectedSessionRef.current !== sessionId) return setTimeline((current) => mergeTimeline( current, page.messages.map((entry) => ({ ...entry, kind: "message" as const })), page.activities.map((entry) => ({ ...entry, kind: "activity" as const })), ), ) after = page.nextSequence setSyncCursor(after) if (!page.hasMore) break } const detail = await getSession(sessionId) if (selectedSessionRef.current === sessionId) setSession(detail.session) }, refreshInterval, force), [refresh, refreshInterval, setSyncCursor, user.id]) const refreshSelectedSession = useCallback(async () => { if (!selectedId || streamingRef.current) return await pullSync(selectedId, false) }, [pullSync, selectedId]) useVisiblePolling(refreshSelectedSession, refreshInterval) useEffect(() => { if (!selectedId) { setSession(null) setTimeline([]) setSyncCursor(0) turnStartedRef.current = null return } let active = true startTransition(async () => { try { // While a harness turn is streaming, only refresh session metadata — // never reset the live timeline. if (streamingRef.current) { const detail = await getSession(selectedId) if (active) setSession(detail.session) } else { await loadSession(selectedId, true) } if (active) setError(null) } catch (loadError) { if (active) setError(loadError instanceof Error ? loadError.message : "Could not load session") } }) return () => { active = false } }, [loadSession, selectedId, setSyncCursor]) async function applyProjectSelection(selection: ProjectSelection) { if (embedded || projectLocked) return if (selection.kind === "none") { setLocalProject(null) setVirtualProjectIndex(null) if (selectedId) { try { await bindSessionLocalProject(selectedId, null) setSession((current) => current ? { ...current, localProjectId: null, localProject: null } : current, ) } catch (error) { setError(error instanceof Error ? error.message : "Could not clear project") } } return } const summary = selection.project // Prefer live workspace index when the browser still has folder access. const fromWorkspace = selection.kind === "local" && selection.workspace ? { ...summary, id: selection.workspace.projectId || summary.id, displayName: selection.workspace.displayName || summary.displayName, rootName: selection.workspace.rootName || summary.rootName, fileCount: selection.workspace.entries.length || summary.fileCount, truncated: selection.workspace.truncated, paths: selection.workspace.entries.map((entry) => entry.path), } : summary setLocalProject(fromWorkspace) setVirtualProjectIndex({ projectId: fromWorkspace.id, displayName: fromWorkspace.displayName, rootName: fromWorkspace.rootName, paths: fromWorkspace.paths ?? [], repositoryFullName: fromWorkspace.repositoryFullName, }) const projectId = fromWorkspace.id if (!projectId || projectId.startsWith("local-")) return if (selectedId) { try { const bound = await bindSessionLocalProject(selectedId, projectId) if (bound.project) { setLocalProject(bound.project) setVirtualProjectIndex({ projectId: bound.project.id, displayName: bound.project.displayName, rootName: bound.project.rootName, paths: bound.project.paths ?? fromWorkspace.paths ?? [], repositoryFullName: bound.project.repositoryFullName, }) } setSession((current) => current ? { ...current, localProjectId: bound.localProjectId, localProject: bound.project, } : current, ) } catch (error) { setError(error instanceof Error ? error.message : "Could not link project to this thread") } } } /** @deprecated path from composer folder open — normalize to ProjectSelection */ async function handleLocalProjectChange(workspace: LocalWorkspaceState) { const projectId = workspace.projectId if (!projectId) { setLocalProject(null) return } await applyProjectSelection({ kind: "local", workspace, project: { id: projectId, displayName: workspace.displayName, rootName: workspace.rootName, fileCount: workspace.entries.length, truncated: workspace.truncated, repositoryFullName: null, status: "active", lastUsedAt: new Date().toISOString(), updatedAt: new Date().toISOString(), paths: workspace.entries.map((entry) => entry.path), }, }) } async function startThread( objective: string, selectedReferences: NovaReference[] = [], selectedLocalFiles: LocalAttachment[] = [], ) { startTransition(async () => { try { const projectId = getActiveLocalProjectId() || localProject?.id || null const response = await createSession(objective, { localProjectId: projectId, mode: agentMode || DEFAULT_NOVA_AGENT_MODE, parentSessionId, }) setSessions((current) => [ response.session, ...current.filter((item) => item.id !== response.session.id), ]) if (!embedded) { try { await ensureGitWorkspace(response.session.id, true) } catch (cause) { navigate(`/s/${response.session.id}`); throw cause } } // Survive the home → /s/:id remount so the harness turn actually starts. const pending: PendingTurn = { sessionId: response.session.id, content: objective, model, provider, effort, mode: agentMode, machineSize, references: selectedReferences, localAttachments: selectedLocalFiles, } if (embedded) { setEmbeddedPendingTurn(pending) setEmbeddedSessionId(response.session.id) onSideSessionCreated?.(response.session) } else { writePendingTurn(pending) navigate(`/s/${response.session.id}`) } setError(null) } catch (createError) { setError(createError instanceof Error ? createError.message : "Could not create thread") } }) } const runTurn = useCallback(async ( sessionId: string, content: string, opts?: { model?: string provider?: HarnessProvider effort?: NovaEffort mode?: NovaAgentMode machineSize?: MachineSize references?: NovaReference[] localAttachments?: LocalAttachment[] resumeRunId?: string }, ) => { if (!embedded && workspacePublishIntent(content)) { try { const workspace = await ensureGitWorkspace(sessionId) if (workspace) { requestPublish(workspacePublishIntent(content)); return } } catch (cause) { setError(cause instanceof Error ? cause.message : "Reconnect the local workspace"); return } } if (streamingRef.current) return streamingRef.current = true abortRef.current = false turnStartedRef.current = sessionId setStreaming(true) setStreamingText("") setStreamPhase("Starting…") setWorkingSteps([]) workingStepsRef.current = [] const since = Date.now() setWorkingSince(since) workingSinceRef.current = since activeRunIdRef.current = null setDraft("") setReferences([]) setLocalFiles([]) try { // Ensure the session is bound to the active project before the turn runs. const activeProjectId = isAgentChat ? null : embedded ? localProject?.id ?? null : getActiveLocalProjectId() || localProject?.id || null if (!embedded && activeProjectId && !activeProjectId.startsWith("local-")) { try { await bindSessionLocalProject(sessionId, activeProjectId) } catch { // Non-fatal: turn can still proceed with packed attachments. } } // Show packing progress immediately (Capy-style live log while work continues). setStreamPhase("Packing project files…") setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: "Packing project files" }) workingStepsRef.current = next return next }) const localGitWorkspace = !embedded && !isAgentChat ? await ensureGitWorkspace(sessionId) : null const packedAttachments = localGitWorkspace ? await gitClient.pack(localGitWorkspace, content, opts?.localAttachments ?? []) : isAgentChat ? [] : embedded && getActiveLocalProjectId() !== activeProjectId ? opts?.localAttachments ?? [] : await packLocalProjectForTurn(content, opts?.localAttachments ?? []) if (packedAttachments.length > (opts?.localAttachments?.length ?? 0)) { const added = packedAttachments.length - (opts?.localAttachments?.length ?? 0) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: `Packed ${added} local project file${added === 1 ? "" : "s"}`, }) workingStepsRef.current = next return next }) } const clientMessageId = crypto.randomUUID() // Auto-pick chat vs agent vs plan from the message (connected apps / file work → agent). const resolved = resolveNovaTurnMode({ message: content, explicitMode: isAgentChat ? "chat" : opts?.mode ?? agentMode, lockExplicit: false, hasProject: Boolean(activeProjectId), hasAttachments: (opts?.localAttachments?.length ?? 0) > 0 || packedAttachments.length > 0, hasConnectedApps: !isAgentChat, }) const turnMode = resolved.mode if (resolved.auto && turnMode !== agentMode) { setAgentMode(turnMode) } setStreamPhase( resolved.auto ? `${turnMode === "agent" ? "Agent" : turnMode === "plan" ? "Plan" : "Chat"} mode · ${resolved.reason}` : `Using ${turnMode} mode`, ) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: resolved.auto ? `Auto · ${turnMode} mode` : `${turnMode} mode`, }) workingStepsRef.current = next return next }) for await (const event of streamTurn(sessionId, content, { clientMessageId, model: opts?.model ?? model, provider: opts?.provider ?? provider, effort: opts?.effort ?? effort, machineSize: opts?.machineSize ?? machineSize, mode: turnMode, references: opts?.references ?? [], localAttachments: packedAttachments, localWorktree: localGitWorkspace ? { sourceRef: localGitWorkspace.sourceRef, baseSha: localGitWorkspace.baseSha, paths: (await gitClient.files(localGitWorkspace.id)).slice(0, 4_000) } : undefined, resumeRunId: opts?.resumeRunId, })) { if (abortRef.current) break if (event.type === "status") { if (event.runId) activeRunIdRef.current = event.runId setStreamPhase(event.message) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: event.message }) workingStepsRef.current = next return next }) } else if (event.type === "user_message") { if (event.runId) activeRunIdRef.current = event.runId setTimeline((current) => mergeTimeline(current, [{ ...event.message, kind: "message" as const }], []), ) setSyncCursor((value) => Math.max(value, event.latestSequence)) } else if (event.type === "text") { setStreamingText((value) => value + event.content) setStreamPhase(null) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "text" }) workingStepsRef.current = next return next }) } else if (event.type === "reasoning") { if (event.content.trim()) { setStreamPhase("Thinking…") setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "reasoning", content: event.content }) workingStepsRef.current = next return next }) } } else if (event.type === "activity") { if (event.activity.runId) activeRunIdRef.current = event.activity.runId setTimeline((current) => mergeTimeline(current, [], [{ ...event.activity, kind: "activity" as const }]), ) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "activity", activity: { type: event.activity.type, title: event.activity.title, body: event.activity.body, status: event.activity.status, }, }) workingStepsRef.current = next return next }) if (event.activity.type === "response") { setStreamingText("") // Recover proposals from trailer if stream event was missed. if (event.activity.body) { const recovered = recoverProposalsFromBody(event.activity.body) if (recovered.length) { setFileProposals((current) => mergeProposals(current, recovered)) } } } } else if (event.type === "file_proposals") { if (event.runId) activeRunIdRef.current = event.runId setFileProposals((current) => mergeProposals(current, event.proposals)) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: `Proposed ${event.proposals.length} file change${event.proposals.length === 1 ? "" : "s"}`, }) workingStepsRef.current = next return next }) // Browsers block write permission without a user gesture — don't auto-apply. // Probe quietly; if write is already granted, apply. Otherwise wait for the button. if (!embedded && !localGitWorkspace && (opts?.mode ?? agentMode) === "agent") { void applyFileProposalsLocally(event.proposals, { interactive: false }).then((batch) => { if (batch.applied > 0) { setApplyStatus(batch.message) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: batch.message }) workingStepsRef.current = next return next }) } else { setApplyStatus( `${event.proposals.length} file${event.proposals.length === 1 ? "" : "s"} ready — click Make these changes to write the whole project folder`, ) } }) } } else if (event.type === "error") { setError(event.message) } else if (event.type === "finish") { if (event.runId) activeRunIdRef.current = event.runId if (event.latestSequence != null) { setSyncCursor((value) => Math.max(value, event.latestSequence!)) } // Freeze the working log onto this run so it stays under "Worked for…" after the answer. const runId = event.runId || activeRunIdRef.current if (runId) { const until = Date.now() const frozen = reduceWorkingSteps(workingStepsRef.current, { type: "text" }) setCompletedWorkByRunId((map) => ({ ...map, [runId]: { steps: frozen, since: workingSinceRef.current ?? until, until, }, })) workingStepsRef.current = frozen setWorkingSteps(frozen) } } } await Promise.all([loadSharedState(), pullSync(sessionId)]) } catch (turnError) { setError(turnError instanceof Error ? turnError.message : "Turn failed") } finally { streamingRef.current = false setStreaming(false) setStreamingText("") setStreamPhase(null) // Keep workingSteps + workingSince so ThreadView can show the completed process // until the next turn starts (which clears them above). } }, [embedded, agentMode, effort, isAgentChat, loadSharedState, localProject?.id, machineSize, model, provider, pullSync, setSyncCursor, ensureGitWorkspace, gitClient, requestPublish]) // Keep "Thinking for Xs" labels live while reasoning is in flight. useEffect(() => { if (!streaming) return const id = window.setInterval(() => { setWorkingSteps((steps) => tickWorkingSteps(steps)) }, 1000) return () => window.clearInterval(id) }, [streaming]) // After navigating to a new thread, pick up the pending first turn. useEffect(() => { if (!selectedId || streamingRef.current || !session || isPending) return const pending = embedded ? embeddedPendingTurn : readPendingTurn() if (!pending || pending.sessionId !== selectedId) return if (turnStartedRef.current === selectedId) return if (embedded) setEmbeddedPendingTurn(null) else clearPendingTurn() if (pending.model) setModel(pending.model) if (pending.provider) setProvider(pending.provider) if (pending.effort) setEffort(pending.effort) if (pending.mode) setAgentMode(pending.mode) const pendingSize = machineSizeSchema.safeParse(pending.machineSize) const size = pendingSize.success ? pendingSize.data : "default" selectMachineSize(size) void runTurn(selectedId, pending.content, { machineSize: size, model: pending.model, provider: pending.provider, effort: pending.effort, mode: pending.mode, references: pending.references, localAttachments: pending.localAttachments, }) }, [embedded, embeddedPendingTurn, isPending, session, runTurn, selectedId, selectMachineSize]) function submitFollowUp() { if (!selectedId || streamingRef.current) return const content = draft.trim() if (!content && localFiles.length === 0) return void runTurn(selectedId, content || "Please review the attached local files.", { references, localAttachments: localFiles, }) } function saveSelection(selection: { provider: HarnessProvider; model: string; effort: NovaEffort }) { try { localStorage.setItem(`nova:model-selection:v2:${user.id}`, JSON.stringify(selection)) } catch { /* Selection remains usable when browser storage is disabled. */ } } function handleModelChange(selection: { provider: HarnessProvider; model: string }) { const entry = selection.provider === "codex" ? codexCatalog.models.find((item) => item.id === selection.model) : null const nextEffort = entry ? entry.efforts.includes(effort) ? effort : entry.defaultEffort ?? "high" : effort === "none" || effort === "minimal" ? "high" : effort setProvider(selection.provider) setModel(selection.model) setEffort(nextEffort) saveSelection({ ...selection, effort: nextEffort }) } function handleEffortChange(next: NovaEffort) { setEffort(next) saveSelection({ provider, model, effort: next }) } function onDecision(approval: ApprovalRequest, decision: "approved" | "denied") { setDecidingApprovalId(approval.id) void decideApproval(approval, decision) .then(() => loadSharedState()) .catch((decisionError) => { setError(decisionError instanceof Error ? decisionError.message : "Could not record decision") }) .finally(() => setDecidingApprovalId(null)) } function onInteractionAnswer(activity: TimelineActivity, answers: string[]) { if (!selectedId || !activity.runId || decidingInteractionId) return const runId = activity.runId const data = activity.data as { invocationId?: string; normalizedArgsHash?: string } | null if (!data?.invocationId || !data.normalizedArgsHash) return setDecidingInteractionId(activity.id) void decideHarnessInteraction(selectedId, { runId, invocationId: data.invocationId, hash: data.normalizedArgsHash, decision: "answer", answers, }) .then(() => runTurn(selectedId, "", { resumeRunId: runId, mode: isAgentChat ? "chat" : agentMode })) .then(() => loadSharedState()) .catch((decisionError) => { setError(decisionError instanceof Error ? decisionError.message : "Could not continue Nova") }) .finally(() => setDecidingInteractionId(null)) } const sidebar = ( navigate("/")} onClose={() => { if (window.matchMedia("(min-width: 768px)").matches) toggleDesktopSidebar(false) else setSidebarOpen(false) }} /> ) const content = ( {view === "connections" ? ( ) : view === "settings" ? ( { handleModelChange(selection) navigate("/") }} onSectionChange={openSettingsSection} onBack={() => navigate("/")} onNavigate={navigate} /> ) : view === "agents" ? ( ) : view === "automations" ? ( ) : view === "approvals" ? ( navigate(`/s/${sessionId}`)} /> ) : view === "pulls" ? ( navigate(`/pulls/${encodeURIComponent(id)}`)} /> ) : view === "pull" && selectedPullId ? ( navigate("/pulls")} /> ) : view === "more" ? ( ) : selectedId && session ? ( gitClient.read(gitWorkspace.workspace!.id, path) : undefined} workspaceControls={!embedded ? navigate(`/s/${id}`)} workspaceLabels={Object.fromEntries(sessions.map(item => [item.id, item.objective]))}/> : undefined} onLocalProjectChange={(workspace) => void handleLocalProjectChange(workspace)} onProjectChange={(selection) => void applyProjectSelection(selection)} onManageProjects={() => openSettingsSection("projects")} streamingText={streamingText} streamPhase={streamPhase} workingSteps={workingSteps} streaming={streaming} workingSince={workingSince} completedWorkByRunId={completedWorkByRunId} fileProposals={fileProposals} applyStatus={applyStatus} onApplyProposals={async () => { if (!fileProposals.length) return if (embedded && (!localProject?.id || getActiveLocalProjectId() !== localProject.id)) { setApplyStatus("Open the parent thread’s project folder before applying these changes.") return } setApplyStatus("Granting folder access and applying…") // interactive:true runs inside this click — browser allows write + picker. const managed = !embedded ? await ensureGitWorkspace(selectedId) : null const batch = managed ? await gitClient.apply(managed, fileProposals) : await applyFileProposalsLocally(fileProposals, { interactive: true }) setApplyStatus(batch.message) setWorkingSteps((steps) => { const next = reduceWorkingSteps(steps, { type: "status", message: batch.message }) workingStepsRef.current = next return next }) if (batch.applied > 0 && localProject) { // Refresh project meta so the panel sees new paths. setLocalProject({ ...localProject, fileCount: Math.max(localProject.fileCount, (localProject.paths?.length ?? 0)), }) } }} loading={isPending || (isAgentChat && !agentChatAgent)} decidingApprovalId={decidingApprovalId} detailsOpen={detailsOpen} model={model} provider={provider} effort={effort} mode={agentMode} onDraftChange={setDraft} onModelChange={handleModelChange} onEffortChange={handleEffortChange} onModeChange={setAgentMode} onSubmit={submitFollowUp} onRefresh={() => { void loadSession(selectedId, true) void loadSharedState() }} onToggleDetails={() => setDetailsOpen((value) => !value)} onDecision={onDecision} onInteractionAnswer={onInteractionAnswer} decidingInteractionId={decidingInteractionId} chatOnly={isAgentChat} agentName={agentChatAgent?.name ?? "Agent"} /> ) : selectedId && (isPending || streaming) ? (
{streaming ? "Nova is working…" : "Loading thread…"}
) : embedded ? (

Start a side thread

Explore a direction without adding it to this conversation.

{ if (draft.trim() || localFiles.length) void startThread(draft.trim() || "Please review the attached local files.", references, localFiles) }} disabled={isPending || Boolean(selectedId)} model={model} provider={provider} effort={effort} mode={agentMode} onModelChange={handleModelChange} onEffortChange={handleEffortChange} onModeChange={setAgentMode} references={references} onReferencesChange={setReferences} localFiles={localFiles} onLocalFilesChange={setLocalFiles} projectLocked placeholder="Message your side thread…" />
) : ( void applyProjectSelection(selection)} onManageProjects={() => openSettingsSection("projects")} localProject={localProject} workspaceControls={ navigate(`/s/${id}`)} workspaceLabels={Object.fromEntries(sessions.map(item => [item.id, item.objective]))}/>} /> )} ) if (embedded) return (
{content} {error ? : null}
) if (view === "settings") { return (
{content}
{error ? ( ) : null}
) } return (
{/* Desktop sidebar — flush left like Capy */} {desktopSidebarOpen ?
{sidebar}
: (
)} {/* Mobile drawer */} {sidebarOpen ? (
{sidebar}
) : null} {/* Main stage: inset rounded panel */}
{/* Mobile top bar */}
Nova
{selectedId && view === "session" ? ( }> {content} ) : content}
{error ? ( ) : null}
) }