Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat: draft hero landing on the index route (#4055)
Yordis Prieto1bd2fa25e221
diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex aefa9ab9f..07ec0dc90 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -1,5 +1,5 @@import { useAtomValue } from "@effect/atom-react";-import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";+import { useEffect, useState, type CSSProperties, type ReactNode } from "react";import { useLocation, useNavigate } from "@tanstack/react-router";import { isElectron } from "../env";@@ -56,8 +56,6 @@ function SidebarControl() {export function AppSidebarLayout({ children }: { children: ReactNode }) {const navigate = useNavigate();const pathname = useLocation({ select: (location) => location.pathname });- const pathnameRef = useRef(pathname);- pathnameRef.current = pathname;const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;@@ -95,7 +93,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {const unsubscribe = onMenuAction((action) => {if (action === "open-settings") {- const isSettingsRoute = /^\/settings(\/|$)/.test(pathnameRef.current);+ const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);if (!isSettingsRoute) {void navigate({ to: "/settings" });}@@ -105,7 +103,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {return () => {unsubscribe?.();};- }, [navigate]);+ }, [navigate, pathname]);return (<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={macosWindowControlsStyle}>diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex f5ea5bb1e..77951e707 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -53,6 +53,7 @@ import {useRef,useState,} from "react";+import { flushSync } from "react-dom";import { useNavigate } from "@tanstack/react-router";import { useShallow } from "zustand/react/shallow";import {@@ -201,6 +202,7 @@ import {} from "../state/entities";import { environmentShell } from "../state/shell";import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";+import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";import { PullRequestThreadDialog } from "./PullRequestThreadDialog";import { MessagesTimeline } from "./chat/MessagesTimeline";@@ -212,6 +214,14 @@ import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";+import {+ DRAFT_HERO_TRANSITION_ANIMATION_ID,+ DRAFT_HERO_TRANSITION_DURATION_MS,+ DRAFT_HERO_TRANSITION_EASING,+ MOBILE_COMPOSER_VIEW_TRANSITION_NAME,+ MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,+ runMobileComposerTransition,+} from "./chat/draftHeroTransition";import {MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,buildExpiredTerminalContextToastCopy,@@ -256,6 +266,78 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];const EMPTY_PROVIDERS: ServerProvider[] = [];const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};+function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {+ const transitionGroupRef = useRef<HTMLDivElement | null>(null);+ const composerAnchorRef = useRef<HTMLDivElement | null>(null);+ const previousStateRef = useRef(isDraftHeroState);+ const previousComposerRectRef = useRef<DOMRect | null>(null);+ const animationRef = useRef<Animation | null>(null);+ const attachTransitionGroupRef = (element: HTMLDivElement | null) => {+ transitionGroupRef.current = element;+ };+ const attachComposerAnchorRef = (element: HTMLDivElement | null) => {+ composerAnchorRef.current = element;+ };+ const captureComposerRect = () => {+ previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;+ };++ useLayoutEffect(() => {+ const transitionGroup = transitionGroupRef.current;+ const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;+ const stateChanged = previousStateRef.current !== isDraftHeroState;+ const prefersReducedMotion =+ typeof window !== "undefined" &&+ window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;+ const mobileComposerTransitionActive =+ typeof document !== "undefined" &&+ document.documentElement.dataset.mobileComposerRouteTransition === "true";++ animationRef.current?.cancel();+ animationRef.current = null;++ const previousComposerRect = previousComposerRectRef.current;+ if (+ stateChanged &&+ !prefersReducedMotion &&+ !mobileComposerTransitionActive &&+ transitionGroup &&+ previousComposerRect &&+ nextComposerRect &&+ typeof transitionGroup.animate === "function"+ ) {+ const translateX = previousComposerRect.left - nextComposerRect.left;+ const translateY = previousComposerRect.top - nextComposerRect.top;+ if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {+ const animation = transitionGroup.animate(+ [+ { transform: `translate3d(${translateX}px, ${translateY}px, 0)` },+ { transform: "translate3d(0, 0, 0)" },+ ],+ {+ duration: DRAFT_HERO_TRANSITION_DURATION_MS,+ easing: DRAFT_HERO_TRANSITION_EASING,+ },+ );+ animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;+ animationRef.current = animation;+ void animation.finished+ .catch(() => undefined)+ .then(() => {+ if (animationRef.current !== animation) {+ return;+ }+ animationRef.current = null;+ });+ }+ }++ previousStateRef.current = isDraftHeroState;+ previousComposerRectRef.current = nextComposerRect;+ }, [isDraftHeroState]);++ return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const;+}const PreviewPanel = lazy(() =>import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })),);@@ -339,6 +421,7 @@ type ChatViewProps =threadId: ThreadId;onDiffPanelOpen?: () => void;reserveTitleBarControlInset?: boolean;+ forceExpandedMobileComposer?: boolean;routeKind: "server";draftId?: never;}@@ -347,6 +430,7 @@ type ChatViewProps =threadId: ThreadId;onDiffPanelOpen?: () => void;reserveTitleBarControlInset?: boolean;+ forceExpandedMobileComposer?: boolean;routeKind: "draft";draftId: DraftId;};@@ -979,6 +1063,14 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane);});+// Errors surface through two maps (draft-keyed and thread-keyed) whose entries+// can race around promotion, so each write carries its time to let the latest+// one win when they collide.+type LocalThreadErrorEntry = {+ readonly message: string | null;+ readonly at: number;+};+function ChatViewContent(props: ChatViewProps) {const {environmentId,@@ -986,6 +1078,7 @@ function ChatViewContent(props: ChatViewProps) {routeKind,onDiffPanelOpen,reserveTitleBarControlInset = true,+ forceExpandedMobileComposer = false,} = props;const draftId = routeKind === "draft" ? props.draftId : null;const routeThreadRef = useMemo(@@ -1035,10 +1128,10 @@ function ChatViewContent(props: ChatViewProps) {);const composerDraftTarget: ScopedThreadRef | DraftId =routeKind === "server" ? routeThreadRef : props.draftId;- const serverThread = useThread(routeKind === "server" ? routeThreadRef : null);+ const serverThread = useThread(routeThreadRef);const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);- const activeThreadLastVisitedAt = useUiStateStore((store) =>- routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,+ const activeThreadLastVisitedAt = useUiStateStore(+ (store) => store.threadLastVisitedAtById[routeThreadKey],);const settings = useEnvironmentSettings(environmentId);const setStickyComposerModelSelection = useComposerDraftStore(@@ -1103,10 +1196,10 @@ function ChatViewContent(props: ChatViewProps) {const optimisticUserMessagesRef = useRef(optimisticUserMessages);optimisticUserMessagesRef.current = optimisticUserMessages;const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<- Record<string, string | null>+ Record<string, LocalThreadErrorEntry>>({});const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState<- Record<string, string | null>+ Record<string, LocalThreadErrorEntry>>({});const [isConnecting, _setIsConnecting] = useState(false);const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);@@ -1218,11 +1311,45 @@ function ChatViewContent(props: ChatViewProps) {? scopeProjectRef(draftThread.environmentId, draftThread.projectId): null;const fallbackDraftProject = useProject(fallbackDraftProjectRef);- const localDraftError =- routeKind === "server" && serverThread- ? null- : ((draftId ? localDraftErrorsByDraftId[draftId] : null) ?? null);- const localServerError = localServerErrorsByThreadKey[routeThreadKey] ?? null;+ const localDraftError = serverThread+ ? null+ : ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);+ const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;+ // Draft errors are keyed by draftId while server errors are keyed by thread+ // key, so a pending draft entry must migrate when the server thread loads or+ // a failed send would silently disappear on promotion. When both keys hold+ // an entry, the most recent write wins.+ useEffect(() => {+ if (!serverThread || !draftId) {+ return;+ }+ const pendingDraftEntry = localDraftErrorsByDraftId[draftId];+ if (pendingDraftEntry === undefined) {+ return;+ }+ setLocalDraftErrorsByDraftId((existing) => {+ if (existing[draftId] === undefined) {+ return existing;+ }+ const next = { ...existing };+ delete next[draftId];+ return next;+ });+ setLocalServerErrorsByThreadKey((existing) => {+ const currentEntry = existing[routeThreadKey];+ if (+ currentEntry !== undefined &&+ (currentEntry.at > pendingDraftEntry.at ||+ currentEntry.message === pendingDraftEntry.message)+ ) {+ return existing;+ }+ return {+ ...existing,+ [routeThreadKey]: pendingDraftEntry,+ };+ });+ }, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]);const localDraftThread = useMemo(() =>draftThread@@ -1237,7 +1364,10 @@ function ChatViewContent(props: ChatViewProps) {: undefined,[draftThread, fallbackDraftProject?.defaultModelSelection, threadId],);- const isServerThread = routeKind === "server" && serverThread !== null;+ // Promotion is data-driven: the draft route keeps rendering while the+ // server thread (same pre-allocated ref) starts, so live state must not+ // depend on which route is mounted.+ const isServerThread = serverThread !== null;const activeThread = isServerThread ? serverThread : localDraftThread;const threadError = isServerThread? (localServerError ?? serverThread?.session?.lastError ?? null)@@ -2063,6 +2193,16 @@ function ChatViewContent(props: ChatViewProps) {deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),[activeThread?.proposedPlans, timelineMessages, workLogEntries],);+ const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);+ const draftHeroDockRequested =+ activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;+ const isDraftHeroState =+ isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested;+ const [+ attachDraftHeroTransitionGroupRef,+ attachDraftHeroComposerAnchorRef,+ captureDraftHeroComposerRect,+ ] = useDraftHeroLayoutTransition(isDraftHeroState);const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =useTurnDiffSummaries(activeThread);const turnDiffSummaryByAssistantMessageId = useMemo(() => {@@ -2226,6 +2366,7 @@ function ChatViewContent(props: ChatViewProps) {(targetThreadId: ThreadId | null, error: string | null) => {if (!targetThreadId) return;const nextError = sanitizeThreadErrorMessage(error);+ const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };if (serverThread &&targetThreadId === routeThreadRef.threadId &&@@ -2233,24 +2374,24 @@ function ChatViewContent(props: ChatViewProps) {serverThread.id === targetThreadId) {setLocalServerErrorsByThreadKey((existing) => {- if ((existing[routeThreadKey] ?? null) === nextError) {+ if ((existing[routeThreadKey]?.message ?? null) === nextError) {return existing;}return {...existing,- [routeThreadKey]: nextError,+ [routeThreadKey]: nextEntry,};});return;}const localDraftErrorKey = draftId ?? targetThreadId;setLocalDraftErrorsByDraftId((existing) => {- if ((existing[localDraftErrorKey] ?? null) === nextError) {+ if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {return existing;}return {...existing,- [localDraftErrorKey]: nextError,+ [localDraftErrorKey]: nextEntry,};});},@@ -3963,7 +4104,16 @@ function ChatViewContent(props: ChatViewProps) {}return;}- if (!activeProject) return;+ if (!activeProject) {+ toastManager.add(+ stackedThreadToast({+ type: "warning",+ title: "Choose a project first",+ description: "This draft no longer points to an available project.",+ }),+ );+ return;+ }const threadIdForSend = activeThread.id;const isFirstMessage = !isServerThread || activeThread.messages.length === 0;const baseBranchForWorktree =@@ -3981,6 +4131,21 @@ function ChatViewContent(props: ChatViewProps) {}sendInFlightRef.current = true;+ if (isDraftHeroState && activeThreadKey) {+ let resolveDockStarted: (() => void) | undefined;+ const dockStarted = new Promise<void>((resolve) => {+ resolveDockStarted = resolve;+ });+ const dockTransition = runMobileComposerTransition(() => {+ flushSync(() => {+ captureDraftHeroComposerRect();+ setDockedDraftHeroThreadKey(activeThreadKey);+ });+ resolveDockStarted?.();+ });+ void dockTransition.catch(() => resolveDockStarted?.());+ await dockStarted;+ }beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });const composerImagesSnapshot = [...composerImages];@@ -4234,6 +4399,9 @@ function ChatViewContent(props: ChatViewProps) {}sendInFlightRef.current = false;if (!turnStartSucceeded) {+ setDockedDraftHeroThreadKey((currentThreadKey) =>+ currentThreadKey === activeThreadKey ? null : currentThreadKey,+ );resetLocalDispatch();}};@@ -5101,6 +5269,7 @@ function ChatViewContent(props: ChatViewProps) {contentInsetEndAdjustment={composerOverlayHeight}onIsAtEndChange={onIsAtEndChange}onManualNavigation={cancelTimelineLiveFollowForUserNavigation}+ hideEmptyPlaceholder={isDraftHeroState}/>{/* scroll to end pill — shown when user has scrolled away from the live edge */}@@ -5123,134 +5292,187 @@ function ChatViewContent(props: ChatViewProps) {)}</div>- {/* Input bar */}+ {/* Input bar — centered hero while a draft has no messages, docked at the bottom otherwise */}<divref={setComposerOverlayElement}data-chat-composer-overlay="true"- className="pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"+ className={+ isDraftHeroState+ ? "pointer-events-none absolute inset-0 z-20 flex items-center"+ : "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"+ }>- <div- aria-hidden="true"- className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"- >- <div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">- <div className="chat-composer-shared-blur absolute -inset-8" />- </div>- </div>- <div className="chat-composer-horizontal-inset">- <div className="pointer-events-auto relative z-10 isolate">- <ComposerBannerStack className="relative z-0" items={composerBannerItems} />- <div className="relative z-10">- <ChatComposer- composerRef={composerRef}- composerDraftTarget={composerDraftTarget}- environmentId={environmentId}- routeKind={routeKind}- routeThreadRef={routeThreadRef}- draftId={draftId}- activeThreadId={activeThreadId}- activeThreadEnvironmentId={activeThread?.environmentId}- activeThread={activeThread}- isServerThread={isServerThread}- isLocalDraftThread={isLocalDraftThread}- phase={phase}- isConnecting={isConnecting}- isSendBusy={isSendBusy}- isPreparingWorktree={isPreparingWorktree}- environmentUnavailable={activeEnvironmentUnavailableState}- activePendingApproval={activePendingApproval}- pendingApprovals={pendingApprovals}- pendingUserInputs={pendingUserInputs}- activePendingProgress={activePendingProgress}- activePendingResolvedAnswers={activePendingResolvedAnswers}- activePendingIsResponding={activePendingIsResponding}- activePendingDraftAnswers={activePendingDraftAnswers}- activePendingQuestionIndex={activePendingQuestionIndex}- respondingRequestIds={respondingRequestIds}- showPlanFollowUpPrompt={showPlanFollowUpPrompt}- activeProposedPlan={activeProposedPlan}- activePlan={activePlan as { turnId?: TurnId } | null}- sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}- planSidebarLabel={planSidebarLabel}- planSidebarOpen={planSidebarOpen}- runtimeMode={runtimeMode}- interactionMode={interactionMode}- lockedProvider={lockedProvider}- providerStatuses={providerStatuses as ServerProvider[]}- activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}- activeThreadModelSelection={activeThread?.modelSelection}- activeThreadActivities={activeThread?.activities}- resolvedTheme={resolvedTheme}- settings={settings}- keybindings={keybindings}- terminalOpen={Boolean(terminalUiState.terminalOpen)}- gitCwd={gitCwd}- promptRef={promptRef}- composerImagesRef={composerImagesRef}- composerTerminalContextsRef={composerTerminalContextsRef}- composerElementContextsRef={composerElementContextsRef}- onSend={onSend}- onInterrupt={onInterrupt}- onImplementPlanInNewThread={onImplementPlanInNewThread}- onRespondToApproval={onRespondToApproval}- onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}- onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}- onPreviousActivePendingUserInputQuestion={- onPreviousActivePendingUserInputQuestion- }- onChangeActivePendingUserInputCustomAnswer={- onChangeActivePendingUserInputCustomAnswer- }- onProviderModelSelect={onProviderModelSelect}- getModelDisabledReason={getModelDisabledReason}- toggleInteractionMode={toggleInteractionMode}- handleRuntimeModeChange={handleRuntimeModeChange}- handleInteractionModeChange={handleInteractionModeChange}- togglePlanSidebar={togglePlanSidebar}- focusComposer={focusComposer}- scheduleComposerFocus={scheduleComposerFocus}- setThreadError={setThreadError}- onExpandImage={onExpandTimelineImage}- />+ {!isDraftHeroState ? (+ <div+ key="docked-composer-blur"+ aria-hidden="true"+ className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"+ >+ <div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">+ <div className="chat-composer-shared-blur absolute -inset-8" /></div></div>- </div>+ ) : null}<div- className={cn(- "chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10",- isGitRepo- ? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"- : "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",- )}+ ref={attachDraftHeroTransitionGroupRef}+ className="chat-composer-horizontal-inset w-full">- {isGitRepo && (- <div className="pointer-events-auto">- <BranchToolbar- environmentId={activeThread.environmentId}- threadId={activeThread.id}- {...(routeKind === "draft" && draftId ? { draftId } : {})}- onEnvModeChange={onEnvModeChange}- startFromOrigin={startFromOrigin}- onStartFromOriginChange={onStartFromOriginChange}- {...(canOverrideServerThreadEnvMode- ? { effectiveEnvModeOverride: envMode }- : {})}- {...(canOverrideServerThreadEnvMode- ? {- activeThreadBranchOverride: activeThreadBranch,- onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,- }- : {})}- envLocked={envLocked}- onComposerFocusRequest={scheduleComposerFocus}- {...(canCheckoutPullRequestIntoThread- ? { onCheckoutPullRequestRequest: openPullRequestDialog }- : {})}- {...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}- availableEnvironments={logicalProjectEnvironments}- />+ <div className="pointer-events-auto relative z-10 isolate">+ {isDraftHeroState ? (+ <div className="absolute inset-x-0 bottom-full z-0">+ <div+ className="pb-8"+ style={+ forceExpandedMobileComposer+ ? {+ viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,+ }+ : undefined+ }+ >+ <DraftHeroHeadline+ activeProjectRef={activeProjectRef}+ activeProjectTitle={activeProject?.title ?? null}+ />+ </div>+ <ComposerBannerStack className="relative z-0" items={composerBannerItems} />+ </div>+ ) : (+ <ComposerBannerStack className="relative z-0" items={composerBannerItems} />+ )}+ <div+ className="relative"+ style={+ forceExpandedMobileComposer+ ? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME }+ : undefined+ }+ >+ <div+ ref={attachDraftHeroComposerAnchorRef}+ className="relative z-10 mx-auto w-full max-w-3xl"+ >+ <ChatComposer+ composerRef={composerRef}+ composerDraftTarget={composerDraftTarget}+ environmentId={environmentId}+ routeKind={routeKind}+ routeThreadRef={routeThreadRef}+ draftId={draftId}+ activeThreadId={activeThreadId}+ activeThreadEnvironmentId={activeThread?.environmentId}+ activeThread={activeThread}+ isServerThread={isServerThread}+ isLocalDraftThread={isLocalDraftThread}+ forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}+ projectSelectionRequired={isLocalDraftThread && activeProject === null}+ phase={phase}+ isConnecting={isConnecting}+ isSendBusy={isSendBusy}+ isPreparingWorktree={isPreparingWorktree}+ environmentUnavailable={activeEnvironmentUnavailableState}+ activePendingApproval={activePendingApproval}+ pendingApprovals={pendingApprovals}+ pendingUserInputs={pendingUserInputs}+ activePendingProgress={activePendingProgress}+ activePendingResolvedAnswers={activePendingResolvedAnswers}+ activePendingIsResponding={activePendingIsResponding}+ activePendingDraftAnswers={activePendingDraftAnswers}+ activePendingQuestionIndex={activePendingQuestionIndex}+ respondingRequestIds={respondingRequestIds}+ showPlanFollowUpPrompt={showPlanFollowUpPrompt}+ activeProposedPlan={activeProposedPlan}+ activePlan={activePlan as { turnId?: TurnId } | null}+ sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}+ planSidebarLabel={planSidebarLabel}+ planSidebarOpen={planSidebarOpen}+ runtimeMode={runtimeMode}+ interactionMode={interactionMode}+ lockedProvider={lockedProvider}+ providerStatuses={providerStatuses as ServerProvider[]}+ activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}+ activeThreadModelSelection={activeThread?.modelSelection}+ activeThreadActivities={activeThread?.activities}+ resolvedTheme={resolvedTheme}+ settings={settings}+ keybindings={keybindings}+ terminalOpen={Boolean(terminalUiState.terminalOpen)}+ gitCwd={gitCwd}+ promptRef={promptRef}+ composerImagesRef={composerImagesRef}+ composerTerminalContextsRef={composerTerminalContextsRef}+ composerElementContextsRef={composerElementContextsRef}+ onSend={onSend}+ onInterrupt={onInterrupt}+ onImplementPlanInNewThread={onImplementPlanInNewThread}+ onRespondToApproval={onRespondToApproval}+ onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}+ onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}+ onPreviousActivePendingUserInputQuestion={+ onPreviousActivePendingUserInputQuestion+ }+ onChangeActivePendingUserInputCustomAnswer={+ onChangeActivePendingUserInputCustomAnswer+ }+ onProviderModelSelect={onProviderModelSelect}+ getModelDisabledReason={getModelDisabledReason}+ toggleInteractionMode={toggleInteractionMode}+ handleRuntimeModeChange={handleRuntimeModeChange}+ handleInteractionModeChange={handleInteractionModeChange}+ togglePlanSidebar={togglePlanSidebar}+ focusComposer={focusComposer}+ scheduleComposerFocus={scheduleComposerFocus}+ setThreadError={setThreadError}+ onExpandImage={onExpandTimelineImage}+ />+ </div>+ <div+ className={cn(+ "min-h-0",+ isDraftHeroState ? "absolute inset-x-0 top-full" : null,+ )}+ >+ <div+ className={cn(+ "chat-composer-lower-chrome relative z-10",+ isGitRepo+ ? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"+ : "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",+ )}+ >+ {isGitRepo && (+ <div className="pointer-events-auto">+ <BranchToolbar+ environmentId={activeThread.environmentId}+ threadId={activeThread.id}+ {...(routeKind === "draft" && draftId ? { draftId } : {})}+ onEnvModeChange={onEnvModeChange}+ startFromOrigin={startFromOrigin}+ onStartFromOriginChange={onStartFromOriginChange}+ {...(canOverrideServerThreadEnvMode+ ? { effectiveEnvModeOverride: envMode }+ : {})}+ {...(canOverrideServerThreadEnvMode+ ? {+ activeThreadBranchOverride: activeThreadBranch,+ onActiveThreadBranchOverrideChange:+ setPendingServerThreadBranch,+ }+ : {})}+ envLocked={envLocked}+ onComposerFocusRequest={scheduleComposerFocus}+ {...(canCheckoutPullRequestIntoThread+ ? { onCheckoutPullRequestRequest: openPullRequestDialog }+ : {})}+ {...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}+ availableEnvironments={logicalProjectEnvironments}+ />+ </div>+ )}+ </div>+ </div></div>- )}+ </div></div></div>diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex 574e33d4d..5f6c234e5 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -19,6 +19,7 @@ import {resolveThreadStatusPill,shouldClearThreadSelectionOnMouseDown,sortProjectsForSidebar,+ sortScopedProjectsForSidebar,THREAD_JUMP_HINT_SHOW_DELAY_MS,} from "./Sidebar.logic";import {@@ -1066,3 +1067,73 @@ describe("sortProjectsForSidebar", () => {expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));});});++describe("sortScopedProjectsForSidebar", () => {+ it("keeps identical project ids in different environments separate", () => {+ const remoteEnvironmentId = EnvironmentId.make("environment-remote");+ const sharedProjectId = ProjectId.make("shared-project");+ const projects = [+ makeProject({+ environmentId: localEnvironmentId,+ id: sharedProjectId,+ title: "Local project",+ }),+ makeProject({+ environmentId: remoteEnvironmentId,+ id: sharedProjectId,+ title: "Remote project",+ }),+ ];+ const threads = [+ makeThread({+ environmentId: localEnvironmentId,+ projectId: sharedProjectId,+ updatedAt: "2026-03-09T10:02:00.000Z",+ }),+ makeThread({+ environmentId: remoteEnvironmentId,+ projectId: sharedProjectId,+ updatedAt: "2026-03-09T10:10:00.000Z",+ }),+ ];++ const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");++ expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);+ });++ it("does not use archived threads as project activity", () => {+ const projects = [+ makeProject({+ id: ProjectId.make("project-visible"),+ title: "Visible project",+ updatedAt: "2026-03-09T10:01:00.000Z",+ }),+ makeProject({+ id: ProjectId.make("project-archived"),+ title: "Archived-only project",+ updatedAt: "2026-03-09T10:00:00.000Z",+ }),+ ];+ const threads = [+ makeThread({+ id: ThreadId.make("thread-visible"),+ projectId: ProjectId.make("project-visible"),+ updatedAt: "2026-03-09T10:02:00.000Z",+ }),+ makeThread({+ id: ThreadId.make("thread-archived"),+ projectId: ProjectId.make("project-archived"),+ updatedAt: "2026-03-09T10:10:00.000Z",+ archivedAt: "2026-03-09T10:11:00.000Z",+ }),+ ];++ const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");++ expect(sorted.map((project) => project.title)).toEqual([+ "Visible project",+ "Archived-only project",+ ]);+ });+});diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 4e7614ed5..91a61cc15 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -24,6 +24,16 @@ type SidebarProject = {updatedAt?: string | undefined;};+type ScopedSidebarProject = SidebarProject & {+ environmentId: string;+};++type ScopedSidebarThread = ThreadSortInput & {+ environmentId: string;+ projectId: string;+ archivedAt: string | null;+};+export type ThreadTraversalDirection = "previous" | "next";export interface ThreadStatusPill {@@ -534,6 +544,25 @@ export function getProjectSortTimestamp(return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;}+function sortProjectsByActivity<TProject extends SidebarProject>(+ projects: readonly TProject[],+ sortOrder: SidebarProjectSortOrder,+ getProjectThreads: (project: TProject) => readonly ThreadSortInput[],+ compareTies: (left: TProject, right: TProject) => number,+): TProject[] {+ if (sortOrder === "manual") {+ return [...projects];+ }++ return [...projects].toSorted((left, right) => {+ const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);+ const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);+ const byTimestamp =+ rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;+ return byTimestamp || compareTies(left, right);+ });+}+export function sortProjectsForSidebar<TProject extends SidebarProject,TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,@@ -542,10 +571,6 @@ export function sortProjectsForSidebar<threads: readonly TThread[],sortOrder: SidebarProjectSortOrder,): TProject[] {- if (sortOrder === "manual") {- return [...projects];- }-const threadsByProjectId = new Map<string, TThread[]>();for (const thread of threads) {const existing = threadsByProjectId.get(thread.projectId) ?? [];@@ -553,20 +578,47 @@ export function sortProjectsForSidebar<threadsByProjectId.set(thread.projectId, existing);}- return [...projects].toSorted((left, right) => {- const rightTimestamp = getProjectSortTimestamp(- right,- threadsByProjectId.get(right.id) ?? [],- sortOrder,- );- const leftTimestamp = getProjectSortTimestamp(- left,- threadsByProjectId.get(left.id) ?? [],- sortOrder,- );- const byTimestamp =- rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;- if (byTimestamp !== 0) return byTimestamp;- return left.title.localeCompare(right.title) || left.id.localeCompare(right.id);- });+ return sortProjectsByActivity(+ projects,+ sortOrder,+ (project) => threadsByProjectId.get(project.id) ?? [],+ (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),+ );+}++/**+ * Sorts the cross-environment project collection used by landing surfaces.+ * Project ids are only unique within an environment, and archived threads+ * must not make a project appear recently active.+ */+export function sortScopedProjectsForSidebar<+ TProject extends ScopedSidebarProject,+ TThread extends ScopedSidebarThread,+>(+ projects: readonly TProject[],+ threads: readonly TThread[],+ sortOrder: SidebarProjectSortOrder,+): TProject[] {+ const scopedKey = (environmentId: string, projectId: string) =>+ `${environmentId}\u0000${projectId}`;+ const threadsByProject = new Map<string, TThread[]>();+ for (const thread of threads) {+ if (thread.archivedAt !== null) {+ continue;+ }+ const key = scopedKey(thread.environmentId, thread.projectId);+ const existing = threadsByProject.get(key) ?? [];+ existing.push(thread);+ threadsByProject.set(key, existing);+ }++ return sortProjectsByActivity(+ projects,+ sortOrder,+ (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],+ (left, right) =>+ left.title.localeCompare(right.title) ||+ left.environmentId.localeCompare(right.environmentId) ||+ left.id.localeCompare(right.id),+ );}diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex c9d5d4957..ad9a364bd 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -442,6 +442,8 @@ export interface ChatComposerProps {activeThread: Thread | undefined;isServerThread: boolean;isLocalDraftThread: boolean;+ forceExpandedOnMobile: boolean;+ projectSelectionRequired: boolean;// Session phasephase: SessionPhase;@@ -553,6 +555,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)activeThread,isServerThread: _isServerThread,isLocalDraftThread: _isLocalDraftThread,+ forceExpandedOnMobile,+ projectSelectionRequired,phase,isConnecting,isSendBusy,@@ -883,7 +887,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);const [isComposerFocused, setIsComposerFocused] = useState(false);const isMobileViewport = useMediaQuery("max-sm");- const isComposerCollapsedMobile = isMobileViewport && !isComposerFocused;+ const isComposerCollapsedMobile =+ isMobileViewport && !forceExpandedOnMobile && !isComposerFocused;// ------------------------------------------------------------------// Refs@@ -1136,7 +1141,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],);const collapsedComposerPrimaryActionDisabled =- phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent;+ phase === "running" ||+ isSendBusy ||+ isConnecting ||+ projectSelectionRequired ||+ !composerSendState.hasSendableContent;const collapsedComposerPrimaryActionLabel = "Send message";const showMobilePendingAnswerActions =isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null;@@ -1928,6 +1937,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)isConnecting ||isComposerApprovalState ||pendingUserInputs.length > 0 ||+ projectSelectionRequired ||(environmentUnavailable !== null && activePendingProgress === null)) {return false;@@ -2028,6 +2038,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)isConnecting,isComposerApprovalState,pendingUserInputs.length,+ projectSelectionRequired,environmentUnavailable,activePendingProgress,applyPromptReplacement,@@ -2065,9 +2076,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)ref={composerSurfaceRef}data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}className={cn(- "chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",+ "chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",- environmentUnavailable ? "opacity-75" : null,+ environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,composerProviderState.composerSurfaceClassName,)}onFocusCapture={(event) => {@@ -2179,7 +2190,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)promptHasText={false}isSendBusy={isSendBusy}isConnecting={isConnecting}- isEnvironmentUnavailable={environmentUnavailable !== null}+ isEnvironmentUnavailable={+ environmentUnavailable !== null || projectSelectionRequired+ }isPreparingWorktree={false}hasSendableContent={false}preserveComposerFocusOnPointerDown@@ -2413,17 +2426,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)? "Type your own answer, or leave this blank to use the selected option": showPlanFollowUpPrompt && activeProposedPlan? "Add feedback to refine the plan, or leave this blank to implement it"- : environmentUnavailable- ? `${environmentUnavailable.label}: ${connectionStatusText(- environmentUnavailable.connection,- )}`- : phase === "disconnected"- ? "Ask for follow-up changes or attach images"- : "Ask anything, @tag files/folders, $use skills, or / for commands"+ : projectSelectionRequired+ ? "Choose a project above to start a thread"+ : environmentUnavailable+ ? `${environmentUnavailable.label}: ${connectionStatusText(+ environmentUnavailable.connection,+ )}`+ : phase === "disconnected"+ ? "Ask for follow-up changes or attach images"+ : "Ask anything, @tag files/folders, $use skills, or / for commands"}disabled={isConnecting ||isComposerApprovalState ||+ projectSelectionRequired ||(environmentUnavailable !== null && activePendingProgress === null)}/>@@ -2440,7 +2456,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)promptHasText={false}isSendBusy={isSendBusy}isConnecting={isConnecting}- isEnvironmentUnavailable={environmentUnavailable !== null}+ isEnvironmentUnavailable={+ environmentUnavailable !== null || projectSelectionRequired+ }isPreparingWorktree={false}hasSendableContent={false}preserveComposerFocusOnPointerDown@@ -2551,7 +2569,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)promptHasText={prompt.trim().length > 0}isSendBusy={isSendBusy}isConnecting={isConnecting}- isEnvironmentUnavailable={environmentUnavailable !== null}+ isEnvironmentUnavailable={+ environmentUnavailable !== null || projectSelectionRequired+ }isPreparingWorktree={isPreparingWorktree}hasSendableContent={composerSendState.hasSendableContent}preserveComposerFocusOnPointerDown={isMobileViewport}diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsxnew file mode 100644index 000000000..32d195d7b--- /dev/null+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx@@ -0,0 +1,114 @@+import type { ScopedProjectRef } from "@t3tools/contracts";+import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";+import { FolderPlusIcon } from "lucide-react";+import { useMemo } from "react";++import { useOpenAddProjectCommandPalette } from "~/commandPaletteContext";+import { useNewThreadHandler } from "~/hooks/useHandleNewThread";+import { useProjects, useThreadShells } from "~/state/entities";+import { sortScopedProjectsForSidebar } from "../Sidebar.logic";+import {+ Menu,+ MenuItem,+ MenuPopup,+ MenuRadioGroup,+ MenuRadioItem,+ MenuSeparator,+ MenuTrigger,+} from "../ui/menu";++interface DraftHeroHeadlineProps {+ readonly activeProjectRef: ScopedProjectRef | null;+ readonly activeProjectTitle: string | null;+}++export function DraftHeroHeadline({+ activeProjectRef,+ activeProjectTitle,+}: DraftHeroHeadlineProps) {+ const projects = useProjects();+ const threads = useThreadShells();+ const handleNewThread = useNewThreadHandler();+ const openAddProject = useOpenAddProjectCommandPalette();++ const orderedProjects = useMemo(+ () => sortScopedProjectsForSidebar(projects, threads, "updated_at"),+ [projects, threads],+ );+ const projectByKey = useMemo(+ () =>+ new Map(+ orderedProjects.map(+ (project) =>+ [+ scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),+ project,+ ] as const,+ ),+ ),+ [orderedProjects],+ );+ const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);+ const hasResolvedProject = activeProjectTitle !== null;+ const canChooseProject = orderedProjects.length > 0;+ const shouldShowProjectMenu = canChooseProject;++ const projectSelector = shouldShowProjectMenu ? (+ <Menu>+ <MenuTrigger+ aria-label={hasResolvedProject ? "Change project" : "Choose a project"}+ className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"+ >+ {activeProjectTitle ?? "Choose a project"}+ </MenuTrigger>+ <MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">+ <MenuRadioGroup+ value={activeProjectKey}+ onValueChange={(value) => {+ const project = projectByKey.get(value as string);+ if (!project || value === activeProjectKey) {+ return;+ }+ void handleNewThread(scopeProjectRef(project.environmentId, project.id), {+ replace: true,+ });+ }}+ >+ {orderedProjects.map((project) => {+ const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));+ return (+ <MenuRadioItem key={key} value={key} closeOnClick>+ <span className="min-w-0 truncate">{project.title}</span>+ </MenuRadioItem>+ );+ })}+ </MenuRadioGroup>+ <MenuSeparator />+ <MenuItem onClick={openAddProject}>+ <FolderPlusIcon />+ New project+ </MenuItem>+ </MenuPopup>+ </Menu>+ ) : (+ <button+ type="button"+ onClick={openAddProject}+ className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-muted-foreground/60 underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"+ >+ {activeProjectTitle ?? "Add a project"}+ </button>+ );++ return (+ <h1 className="mx-auto w-full max-w-5xl text-center font-normal text-3xl text-foreground tracking-tight sm:text-5xl">+ {hasResolvedProject ? (+ <>What should we build in {projectSelector}?</>+ ) : canChooseProject ? (+ <>{projectSelector} to start</>+ ) : (+ <>Add a project to start</>+ )}+ </h1>+ );+}diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 61d785584..d67dd286f 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -179,6 +179,7 @@ interface MessagesTimelineProps {contentInsetEndAdjustment: number;onIsAtEndChange: (isAtEnd: boolean) => void;onManualNavigation: () => void;+ hideEmptyPlaceholder?: boolean;}// ---------------------------------------------------------------------------@@ -212,6 +213,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({contentInsetEndAdjustment,onIsAtEndChange,onManualNavigation,+ hideEmptyPlaceholder = false,}: MessagesTimelineProps) {const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());@@ -458,6 +460,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({);if (rows.length === 0 && !isWorking) {+ if (hideEmptyPlaceholder) {+ return null;+ }return (<div className="flex h-full items-center justify-center"><p className="text-sm text-muted-foreground/30">diff --git a/apps/web/src/components/chat/draftHeroTransition.test.ts b/apps/web/src/components/chat/draftHeroTransition.test.tsnew file mode 100644index 000000000..c9d43d541--- /dev/null+++ b/apps/web/src/components/chat/draftHeroTransition.test.ts@@ -0,0 +1,123 @@+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import {+ DRAFT_HERO_TRANSITION_ANIMATION_ID,+ runMobileComposerTransition,+ waitForDraftHeroTransition,+} from "./draftHeroTransition";++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("waitForDraftHeroTransition", () => {+ it("waits for active draft hero animations and ignores unrelated animations", async () => {+ let finishTransition: (() => void) | undefined;+ const transitionFinished = new Promise<void>((resolve) => {+ finishTransition = resolve;+ });+ vi.stubGlobal("document", {+ getAnimations: () => [+ { id: "unrelated-animation", finished: new Promise<void>(() => undefined) },+ { id: DRAFT_HERO_TRANSITION_ANIMATION_ID, finished: transitionFinished },+ ],+ });++ let handoffComplete = false;+ const handoff = waitForDraftHeroTransition().then(() => {+ handoffComplete = true;+ });+ await Promise.resolve();+ expect(handoffComplete).toBe(false);++ finishTransition?.();+ await handoff;+ expect(handoffComplete).toBe(true);+ });++ it("allows the handoff when an active transition is cancelled", async () => {+ vi.stubGlobal("document", {+ getAnimations: () => [+ {+ id: DRAFT_HERO_TRANSITION_ANIMATION_ID,+ finished: Promise.reject(new Error("cancelled")),+ },+ ],+ });++ await expect(waitForDraftHeroTransition()).resolves.toBeUndefined();+ });+});++describe("runMobileComposerTransition", () => {+ it("keeps the route handoff waiting while the mobile composer morph is active", async () => {+ let finishTransition: (() => void) | undefined;+ const transitionFinished = new Promise<void>((resolve) => {+ finishTransition = resolve;+ });+ const dataset: Record<string, string> = {};+ vi.stubGlobal("document", {+ documentElement: { dataset },+ getAnimations: () => [],+ startViewTransition: (update: () => void | Promise<void>) => {+ void update();+ return { finished: transitionFinished };+ },+ });+ vi.stubGlobal("window", {+ matchMedia: (query: string) => ({ matches: query === "(max-width: 639px)" }),+ });++ const transition = runMobileComposerTransition(() => undefined);+ await Promise.resolve();++ let handoffComplete = false;+ const handoff = waitForDraftHeroTransition().then(() => {+ handoffComplete = true;+ });+ await Promise.resolve();+ expect(handoffComplete).toBe(false);++ finishTransition?.();+ await Promise.all([transition, handoff]);+ expect(handoffComplete).toBe(true);+ });++ it("uses a scoped view transition on mobile", async () => {+ const dataset: Record<string, string> = {};+ const startViewTransition = vi.fn((update: () => void | Promise<void>) => ({+ finished: Promise.resolve(update()).then(() => undefined),+ }));+ vi.stubGlobal("document", {+ documentElement: { dataset },+ startViewTransition,+ });+ vi.stubGlobal("window", {+ matchMedia: (query: string) => ({ matches: query === "(max-width: 639px)" }),+ });+ const update = vi.fn();++ await runMobileComposerTransition(update);++ expect(startViewTransition).toHaveBeenCalledOnce();+ expect(update).toHaveBeenCalledOnce();+ expect(dataset).not.toHaveProperty("mobileComposerRouteTransition");+ });++ it("updates without a view transition when reduced motion is preferred", async () => {+ const startViewTransition = vi.fn();+ vi.stubGlobal("document", {+ documentElement: { dataset: {} },+ startViewTransition,+ });+ vi.stubGlobal("window", {+ matchMedia: () => ({ matches: true }),+ });+ const update = vi.fn();++ await runMobileComposerTransition(update);++ expect(startViewTransition).not.toHaveBeenCalled();+ expect(update).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/components/chat/draftHeroTransition.ts b/apps/web/src/components/chat/draftHeroTransition.tsnew file mode 100644index 000000000..0773407cf--- /dev/null+++ b/apps/web/src/components/chat/draftHeroTransition.ts@@ -0,0 +1,82 @@+export const DRAFT_HERO_TRANSITION_ANIMATION_ID = "t3-draft-hero-transition";+export const DRAFT_HERO_TRANSITION_DURATION_MS = 180;+export const DRAFT_HERO_TRANSITION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";+export const MOBILE_COMPOSER_VIEW_TRANSITION_NAME = "t3-mobile-composer";+export const MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME = "t3-mobile-draft-headline";++type ComposerViewTransition = {+ readonly finished: Promise<void>;+};++let activeMobileComposerTransition: Promise<void> | null = null;++type ComposerViewTransitionDocument = Document & {+ startViewTransition?: (update: () => void | Promise<void>) => ComposerViewTransition;+};++export async function waitForDraftHeroTransition(): Promise<void> {+ const mobileComposerTransition = activeMobileComposerTransition;+ if (typeof document === "undefined" || typeof document.getAnimations !== "function") {+ await mobileComposerTransition;+ return;+ }++ const activeTransitions = document+ .getAnimations()+ .filter((animation) => animation.id === DRAFT_HERO_TRANSITION_ANIMATION_ID);++ await Promise.all([+ mobileComposerTransition,+ ...activeTransitions.map(async (animation) => {+ try {+ await animation.finished;+ } catch {+ // A cancelled transition is already safe to hand off.+ }+ }),+ ]);+}++export async function runMobileComposerTransition(+ update: () => void | Promise<void>,+): Promise<void> {+ if (typeof document === "undefined" || typeof window === "undefined") {+ await update();+ return;+ }++ const transitionDocument = document as ComposerViewTransitionDocument;+ const mobileViewport = window.matchMedia?.("(max-width: 639px)").matches ?? false;+ const prefersReducedMotion =+ window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;+ if (!mobileViewport || prefersReducedMotion || !transitionDocument.startViewTransition) {+ await update();+ return;+ }++ let updateStarted = false;+ const runUpdate = async () => {+ if (updateStarted) return;+ updateStarted = true;+ await update();+ };+ let transitionFinished: Promise<void> | null = null;+ transitionDocument.documentElement.dataset.mobileComposerRouteTransition = "true";+ try {+ const transition = transitionDocument.startViewTransition(runUpdate);+ transitionFinished = transition.finished.catch(() => undefined);+ activeMobileComposerTransition = transitionFinished;+ try {+ await transition.finished;+ } catch {+ await runUpdate();+ }+ } catch {+ await runUpdate();+ } finally {+ if (activeMobileComposerTransition === transitionFinished) {+ activeMobileComposerTransition = null;+ }+ delete transitionDocument.documentElement.dataset.mobileComposerRouteTransition;+ }+}diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.tsindex 1b1c07b31..232551349 100644--- a/apps/web/src/hooks/useHandleNewThread.ts+++ b/apps/web/src/hooks/useHandleNewThread.ts@@ -47,6 +47,7 @@ export function useNewThreadHandler() {worktreePath?: string | null;envMode?: DraftThreadEnvMode;startFromOrigin?: boolean;+ replace?: boolean;},): Promise<void> => {const {@@ -120,6 +121,7 @@ export function useNewThreadHandler() {await router.navigate({to: "/draft/$draftId",params: { draftId: reusableStoredDraftThread.draftId },+ replace: options?.replace ?? false,});})();}@@ -180,6 +182,7 @@ export function useNewThreadHandler() {await router.navigate({to: "/draft/$draftId",params: { draftId },+ replace: options?.replace ?? false,});})();},diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 4aa7a64fc..c500eb68d 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -4,6 +4,77 @@/* Window Controls Overlay: active when Electron exposes native titlebar control geometry. */@custom-variant wco (&:is(.wco, .wco *));+/* On mobile, morph the expanded hero composer into the compact docked+ composer while it moves; the rest of the app remains visually stationary. */+html[data-mobile-composer-route-transition="true"]::view-transition-old(root),+html[data-mobile-composer-route-transition="true"]::view-transition-new(root) {+ animation: none;+}++html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-composer) {+ animation-duration: 180ms;+ animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);+}++html[data-mobile-composer-route-transition="true"]::view-transition-image-pair(t3-mobile-composer) {+ isolation: isolate;+}++html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-composer) {+ animation: t3-mobile-composer-old 180ms linear both;+ mix-blend-mode: normal;+}++html[data-mobile-composer-route-transition="true"]::view-transition-new(t3-mobile-composer) {+ animation: t3-mobile-composer-new 180ms linear both;+ mix-blend-mode: normal;+}++/* The expanded and compact composers have different internal layouts. Use a+ brief crossfade while their shared wrapper moves so the layout change does+ not read as a single-frame cut. */+@keyframes t3-mobile-composer-old {+ 0%,+ 35% {+ opacity: 1;+ }+ 65%,+ 100% {+ opacity: 0;+ }+}++@keyframes t3-mobile-composer-new {+ 0%,+ 35% {+ opacity: 0;+ }+ 65%,+ 100% {+ opacity: 1;+ }+}++html[data-mobile-composer-route-transition="true"]::view-transition-group(t3-mobile-draft-headline) {+ animation-duration: 130ms;+}++html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobile-draft-headline) {+ animation: t3-mobile-draft-headline-exit 130ms cubic-bezier(0.4, 0, 1, 1) both;+ mix-blend-mode: normal;+}++@keyframes t3-mobile-draft-headline-exit {+ from {+ opacity: 1;+ transform: translateY(0);+ }+ to {+ opacity: 0;+ transform: translateY(-6px);+ }+}+:root {--app-scrollbar-width: 6px;--desktop-window-right-resize-inset: 0px;diff --git a/apps/web/src/routes/_chat.draft.$draftId.tsx b/apps/web/src/routes/_chat.draft.$draftId.tsxindex dd152ce1a..74c1b15c0 100644--- a/apps/web/src/routes/_chat.draft.$draftId.tsx+++ b/apps/web/src/routes/_chat.draft.$draftId.tsx@@ -8,6 +8,7 @@ import {useComposerDraftStore,} from "../composerDraftStore";import { SidebarInset } from "../components/ui/sidebar";+import { waitForDraftHeroTransition } from "../components/chat/draftHeroTransition";import { buildThreadRouteParams } from "../threadRoutes";import { useThread, useThreadRefs } from "../state/entities";@@ -40,11 +41,22 @@ function DraftChatThreadRouteView() {if (!canonicalThreadRef) {return;}- void navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(canonicalThreadRef),- replace: true,++ let cancelled = false;+ void waitForDraftHeroTransition().then(() => {+ if (cancelled) {+ return;+ }+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(canonicalThreadRef),+ replace: true,+ });});++ return () => {+ cancelled = true;+ };}, [canonicalThreadRef, navigate]);useEffect(() => {@@ -54,18 +66,6 @@ function DraftChatThreadRouteView() {void navigate({ to: "/", replace: true });}, [canonicalThreadRef, draftSession, navigate]);- if (canonicalThreadRef) {- return (- <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">- <ChatView- environmentId={canonicalThreadRef.environmentId}- threadId={canonicalThreadRef.threadId}- routeKind="server"- />- </SidebarInset>- );- }-if (!draftSession) {return null;}@@ -77,6 +77,7 @@ function DraftChatThreadRouteView() {environmentId={draftSession.environmentId}threadId={draftSession.threadId}routeKind="draft"+ forceExpandedMobileComposer/></SidebarInset>);diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsxindex 94d49d00a..8aadbf9ea 100644--- a/apps/web/src/routes/_chat.index.tsx+++ b/apps/web/src/routes/_chat.index.tsx@@ -1,10 +1,19 @@+import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { createFileRoute, Link } from "@tanstack/react-router";-import { LinkIcon, PlusIcon } from "lucide-react";+import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";-import { NoActiveThreadState } from "../components/NoActiveThreadState";+import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";+import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";import { Button } from "../components/ui/button";import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";import { SidebarInset } from "../components/ui/sidebar";+import { useNewThreadHandler } from "../hooks/useHandleNewThread";+import {+ useAllEnvironmentShellsBootstrapped,+ useProjects,+ useThreadShells,+} from "../state/entities";import { useEnvironments } from "../state/environments";import { APP_DISPLAY_NAME } from "~/branding";import { hasCloudPublicConfig } from "~/cloud/publicConfig";@@ -19,7 +28,109 @@ function ChatIndexRouteView() {return <HostedStaticOnboardingState />;}- return <NoActiveThreadState />;+ return <IndexDraftLanding />;+}++/**+ * Landing on the index route drops straight into a draft thread for the most+ * recently active project, so the first screen is a prompt instead of a dead+ * end. Falls back to an add-project hero when no project exists yet.+ */+function IndexDraftLanding() {+ const projects = useProjects();+ const threads = useThreadShells();+ const bootstrapped = useAllEnvironmentShellsBootstrapped();+ const handleNewThread = useNewThreadHandler();+ const startingRef = useRef(false);+ const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });++ const mostRecentProject = useMemo(+ () =>+ bootstrapped+ ? (sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null)+ : null,+ [bootstrapped, projects, threads],+ );++ useEffect(() => {+ if (mostRecentProject === null || startingRef.current) {+ return;+ }+ startingRef.current = true;+ void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {+ replace: true,+ }).catch(() => {+ startingRef.current = false;+ setStartState((state) => ({ ...state, failed: true }));+ });+ }, [handleNewThread, mostRecentProject, startState.retryRequest]);++ if (!bootstrapped) {+ return null;+ }+ if (mostRecentProject !== null) {+ return startState.failed ? (+ <DraftStartError+ onRetry={() => {+ setStartState((state) => ({+ failed: false,+ retryRequest: state.retryRequest + 1,+ }));+ }}+ />+ ) : null;+ }+ return <NoProjectsHero />;+}++function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {+ return (+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">+ <Empty className="flex-1">+ <EmptyHeader className="max-w-md">+ <EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>+ <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">+ The project is still available. Try opening the draft again.+ </EmptyDescription>+ <div className="mt-5 flex justify-center">+ <Button size="sm" onClick={onRetry}>+ <RotateCcwIcon className="size-4" />+ Try again+ </Button>+ </div>+ </EmptyHeader>+ </Empty>+ </SidebarInset>+ );+}++function NoProjectsHero() {+ const openAddProject = useOpenAddProjectCommandPalette();++ return (+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">+ <Empty className="flex-1">+ <div className="w-full max-w-lg px-8 py-12">+ <EmptyHeader className="max-w-none">+ <EmptyTitle className="text-foreground text-2xl sm:text-3xl">+ What should we work on?+ </EmptyTitle>+ <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">+ Add a project to start your first thread.+ </EmptyDescription>+ <div className="mt-6 flex justify-center">+ <Button size="sm" onClick={openAddProject}>+ <PlusIcon className="size-4" />+ Add project+ </Button>+ </div>+ </EmptyHeader>+ </div>+ </Empty>+ </div>+ </SidebarInset>+ );}export const Route = createFileRoute("/_chat/")({diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex b4fc8cc5e..db895e37c 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -20,6 +20,7 @@ import { useMemo } from "react";import { appAtomRegistry } from "../rpc/atomRegistry";import { environmentProjects } from "./projects";import { environmentServerConfigsAtom } from "./server";+import { allEnvironmentShellsBootstrappedAtom } from "./shell";import { environmentThreadDetails, environmentThreadShells } from "./threads";const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);@@ -113,6 +114,10 @@ export function useThreadShells(): ReadonlyArray<EnvironmentThreadShell> {return useAtomValue(environmentThreadShells.threadShellsAtom);}+export function useAllEnvironmentShellsBootstrapped(): boolean {+ return useAtomValue(allEnvironmentShellsBootstrappedAtom);+}+export function useThreadShellsForProjectRefs(refs: ReadonlyArray<ScopedProjectRef>,): ReadonlyArray<EnvironmentThreadShell> {diff --git a/apps/web/src/state/shell.ts b/apps/web/src/state/shell.tsindex e879dd25e..dfb104e5c 100644--- a/apps/web/src/state/shell.ts+++ b/apps/web/src/state/shell.ts@@ -1,9 +1,15 @@+import {+ AVAILABLE_CONNECTION_STATE,+ connectionProjectionPhase,+} from "@t3tools/client-runtime/connection";import {createEnvironmentShellAtoms,createEnvironmentShellSummaryAtom,createEnvironmentSnapshotAtom,createShellEnvironmentAtoms,} from "@t3tools/client-runtime/state/shell";+import * as Option from "effect/Option";+import { AsyncResult, Atom } from "effect/unstable/reactivity";import { environmentCatalog } from "../connection/catalog";import { connectionAtomRuntime } from "../connection/runtime";@@ -15,3 +21,28 @@ export const environmentShellSummaryAtom = createEnvironmentShellSummaryAtom({catalogValueAtom: environmentCatalog.catalogValueAtom,shellStateValueAtom: environmentShell.stateValueAtom,});++export const allEnvironmentShellsBootstrappedAtom = Atom.make((get) => {+ const catalog = AsyncResult.value(get(environmentCatalog.catalogAtom));+ if (Option.isNone(catalog)) {+ return false;+ }+ for (const environmentId of catalog.value.entries.keys()) {+ if (Option.isSome(get(environmentShell.stateValueAtom(environmentId)).snapshot)) {+ continue;+ }+ const connection = Option.getOrElse(+ AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),+ () => AVAILABLE_CONNECTION_STATE,+ );+ if (connectionProjectionPhase(connection) !== "disconnected") {+ return false;+ }+ // A retrying environment is only transiently disconnected; give it its+ // first retries before letting the landing settle without its snapshot.+ if (connection.phase === "backoff" && connection.desired && connection.attempt <= 2) {+ return false;+ }+ }+ return true;+}).pipe(Atom.withLabel("web-all-environment-shells-bootstrapped"));