From 92e340d80cff793bdb06ed9d6761dfb1bde35c52 Mon Sep 17 00:00:00 2001 From: Hiram Chirino Date: Sun, 3 May 2026 22:48:10 -0400 Subject: [PATCH 1/9] feat(web): collapse mobile composer by default (#1263) Co-authored-by: Julius Marminge Co-authored-by: codex Co-authored-by: Julius Marminge --- apps/web/src/components/chat/ChatComposer.tsx | 401 +++++++++++++++--- .../chat/ComposerPrimaryActions.tsx | 20 +- 2 files changed, 372 insertions(+), 49 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2b7f62e8af..6be51f5d83 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -111,6 +111,7 @@ import type { PendingApproval, PendingUserInput } from "../../session-logic"; import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow"; import { formatProviderSkillDisplayName } from "../../providerSkillPresentation"; import { searchProviderSkills } from "../../providerSkillSearch"; +import { useMediaQuery } from "../../hooks/useMediaQuery"; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; @@ -138,6 +139,13 @@ const runtimeModeConfig: Record< const runtimeModeOptions = Object.keys(runtimeModeConfig) as RuntimeMode[]; const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120; const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = []; +const COMPOSER_FLOATING_LAYER_SELECTOR = [ + '[data-slot="popover-popup"]', + '[data-slot="menu-popup"]', + '[data-slot="select-popup"]', + '[data-slot="combobox-popup"]', + '[data-slot="autocomplete-popup"]', +].join(","); const extendReplacementRangeForTrailingSpace = ( text: string, @@ -167,6 +175,10 @@ const terminalContextIdListsEqual = ( ): boolean => contexts.length === ids.length && contexts.every((context, index) => context.id === ids[index]); +function isInsideComposerFloatingLayer(element: Element): boolean { + return element.closest(COMPOSER_FLOATING_LAYER_SELECTOR) !== null; +} + const ComposerFooterModeControls = memo(function ComposerFooterModeControls(props: { showInteractionModeToggle: boolean; interactionMode: ProviderInteractionMode; @@ -290,6 +302,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( isSendBusy: boolean; isConnecting: boolean; hasSendableContent: boolean; + preserveComposerFocusOnPointerDown?: boolean; onPreviousPendingQuestion: () => void; onInterrupt: () => void; onImplementPlanInNewThread: () => void; @@ -310,6 +323,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( isConnecting={props.isConnecting} isPreparingWorktree={props.isPreparingWorktree} hasSendableContent={props.hasSendableContent} + preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false} onPreviousPendingQuestion={props.onPreviousPendingQuestion} onInterrupt={props.onInterrupt} onImplementPlanInNewThread={props.onImplementPlanInNewThread} @@ -389,7 +403,7 @@ export interface ChatComposerProps { isLastQuestion: boolean; canAdvance: boolean; customAnswer: string; - activeQuestion: { id: string } | null; + activeQuestion: { id: string; multiSelect?: boolean | undefined } | null; } | null; activePendingResolvedAnswers: Record | null; activePendingIsResponding: boolean; @@ -774,17 +788,25 @@ export const ChatComposer = memo( const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false); + const [isComposerFocused, setIsComposerFocused] = useState(false); + const isMobileViewport = useMediaQuery("max-sm"); + const isComposerCollapsedMobile = isMobileViewport && !isComposerFocused; // ------------------------------------------------------------------ // Refs // ------------------------------------------------------------------ const composerEditorRef = useRef(null); const composerFormRef = useRef(null); + const composerSurfaceRef = useRef(null); const composerFormHeightRef = useRef(0); const composerSelectLockRef = useRef(false); const composerMenuOpenRef = useRef(false); const composerMenuItemsRef = useRef([]); const activeComposerMenuItemRef = useRef(null); + const composerBlurFrameRef = useRef(null); + const mobileComposerExpandFrameRef = useRef(null); + const mobileComposerExpandReleaseFrameRef = useRef(null); + const mobileComposerExpandInFlightRef = useRef(false); const dragDepthRef = useRef(0); // ------------------------------------------------------------------ @@ -929,6 +951,8 @@ export const ChatComposer = memo( isComposerApprovalState || pendingUserInputs.length > 0 || (showPlanFollowUpPrompt && activeProposedPlan !== null); + const showCollapsedMobilePromptRow = + isComposerCollapsedMobile && !isComposerApprovalState && pendingUserInputs.length === 0; const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; const showPlanSidebarToggle = Boolean(activePlan || sidebarProposedPlan || planSidebarOpen); @@ -1021,6 +1045,11 @@ export const ChatComposer = memo( : null, [activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers], ); + const collapsedComposerPrimaryActionDisabled = + phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent; + const collapsedComposerPrimaryActionLabel = "Send message"; + const showMobilePendingAnswerActions = + isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; // ------------------------------------------------------------------ // Prompt helpers @@ -1550,6 +1579,69 @@ export const ChatComposer = memo( [composerHighlightedItemId, composerMenuItems], ); + const blurMobileComposerAfterSend = useCallback(() => { + if (!isMobileViewport) return; + if (composerBlurFrameRef.current !== null) { + window.cancelAnimationFrame(composerBlurFrameRef.current); + composerBlurFrameRef.current = null; + } + const activeElement = document.activeElement; + if (activeElement instanceof HTMLElement) { + activeElement.blur(); + } + setIsComposerFocused(false); + }, [isMobileViewport]); + + const shouldBlurMobileComposerOnSubmit = useCallback(() => { + if (!isMobileViewport) return false; + if (isSendBusy || isConnecting || phase === "running") return false; + if (activePendingProgress) { + return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); + } + return showPlanFollowUpPrompt || composerSendState.hasSendableContent; + }, [ + activePendingProgress, + activePendingResolvedAnswers, + composerSendState.hasSendableContent, + isConnecting, + isMobileViewport, + isSendBusy, + phase, + showPlanFollowUpPrompt, + ]); + + const submitComposer = useCallback( + (event?: { preventDefault: () => void }) => { + onSend(event); + if (shouldBlurMobileComposerOnSubmit()) { + blurMobileComposerAfterSend(); + } + }, + [blurMobileComposerAfterSend, onSend, shouldBlurMobileComposerOnSubmit], + ); + const expandMobileComposer = useCallback(() => { + if (composerBlurFrameRef.current !== null) { + window.cancelAnimationFrame(composerBlurFrameRef.current); + composerBlurFrameRef.current = null; + } + if (mobileComposerExpandFrameRef.current !== null) { + window.cancelAnimationFrame(mobileComposerExpandFrameRef.current); + } + if (mobileComposerExpandReleaseFrameRef.current !== null) { + window.cancelAnimationFrame(mobileComposerExpandReleaseFrameRef.current); + } + mobileComposerExpandInFlightRef.current = true; + setIsComposerFocused(true); + mobileComposerExpandFrameRef.current = window.requestAnimationFrame(() => { + mobileComposerExpandFrameRef.current = null; + composerEditorRef.current?.focusAtEnd(); + mobileComposerExpandReleaseFrameRef.current = window.requestAnimationFrame(() => { + mobileComposerExpandReleaseFrameRef.current = null; + mobileComposerExpandInFlightRef.current = false; + }); + }); + }, []); + // ------------------------------------------------------------------ // Callbacks: command key // ------------------------------------------------------------------ @@ -1580,7 +1672,7 @@ export const ChatComposer = memo( } } if (key === "Enter" && !event.shiftKey) { - void onSend(); + submitComposer(); return true; } return false; @@ -1690,6 +1782,50 @@ export const ChatComposer = memo( const handleImplementPlanInNewThreadPrimaryAction = useCallback(() => { void onImplementPlanInNewThread(); }, [onImplementPlanInNewThread]); + const scheduleComposerCollapseCheck = useCallback(() => { + if (!isMobileViewport) { + return; + } + if (mobileComposerExpandInFlightRef.current) { + return; + } + if (composerBlurFrameRef.current !== null) { + window.cancelAnimationFrame(composerBlurFrameRef.current); + } + composerBlurFrameRef.current = window.requestAnimationFrame(() => { + composerBlurFrameRef.current = null; + if (mobileComposerExpandInFlightRef.current) { + return; + } + const composerSurface = composerSurfaceRef.current; + const activeElement = document.activeElement; + if (activeElement instanceof Element && isInsideComposerFloatingLayer(activeElement)) { + return; + } + if ( + composerSurface && + activeElement instanceof Node && + composerSurface.contains(activeElement) + ) { + return; + } + setIsComposerFocused(false); + }); + }, [isMobileViewport]); + + useEffect(() => { + return () => { + if (composerBlurFrameRef.current !== null) { + window.cancelAnimationFrame(composerBlurFrameRef.current); + } + if (mobileComposerExpandFrameRef.current !== null) { + window.cancelAnimationFrame(mobileComposerExpandFrameRef.current); + } + if (mobileComposerExpandReleaseFrameRef.current !== null) { + window.cancelAnimationFrame(mobileComposerExpandReleaseFrameRef.current); + } + }; + }, []); // ------------------------------------------------------------------ // Imperative handle @@ -1803,7 +1939,7 @@ export const ChatComposer = memo( return (
@@ -1818,21 +1954,82 @@ export const ChatComposer = memo( onDrop={onComposerDrop} >
{ + const activeElement = event.target; + if ( + isComposerCollapsedMobile && + activeElement instanceof HTMLElement && + activeElement.closest('[data-chat-composer-collapsed-controls="true"]') + ) { + return; + } + if (composerBlurFrameRef.current !== null) { + window.cancelAnimationFrame(composerBlurFrameRef.current); + composerBlurFrameRef.current = null; + } + setIsComposerFocused(true); + }} + onBlurCapture={() => { + scheduleComposerCollapseCheck(); + }} > - {activePendingApproval ? ( -
+ {!isComposerCollapsedMobile && + (activePendingApproval ? ( +
+ +
+ ) : pendingUserInputs.length > 0 ? ( +
+ +
+ ) : showPlanFollowUpPrompt && activeProposedPlan ? ( +
+ +
+ ) : null)} + + {isComposerCollapsedMobile && activePendingApproval ? ( +
+
+ +
- ) : pendingUserInputs.length > 0 ? ( -
+ ) : isComposerCollapsedMobile && pendingUserInputs.length > 0 ? ( +
+
+
+ + {activePendingProgress?.activeQuestion?.multiSelect ? ( + + ) : null} +
+
- ) : showPlanFollowUpPrompt && activeProposedPlan ? ( -
- + ) : null} + + {showCollapsedMobilePromptRow ? ( +
+ +
) : null} @@ -1855,6 +2130,7 @@ export const ChatComposer = memo( className={cn( "relative px-3 pb-2 sm:px-4", hasComposerHeader ? "pt-2.5 sm:pt-3" : "pt-3.5 sm:pt-4", + isComposerCollapsedMobile && "hidden", )} > {composerMenuOpen && !isComposerApprovalState && ( @@ -1876,7 +2152,8 @@ export const ChatComposer = memo(
)} - {!isComposerApprovalState && + {!isComposerCollapsedMobile && + !isComposerApprovalState && pendingUserInputs.length === 0 && composerImages.length > 0 && (
@@ -1943,43 +2220,69 @@ export const ChatComposer = memo(
)} - +
+ + {showMobilePendingAnswerActions ? ( +
+ +
+ ) : null} +
{/* Bottom toolbar */} - {activePendingApproval ? ( + {isComposerCollapsedMobile ? null : activePendingApproval ? (
@@ -2082,6 +2386,7 @@ export const ChatComposer = memo( isConnecting={isConnecting} isPreparingWorktree={isPreparingWorktree} hasSendableContent={composerSendState.hasSendableContent} + preserveComposerFocusOnPointerDown={isMobileViewport} onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} onInterrupt={handleInterruptPrimaryAction} onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction} diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 2bc40fe6ae..9e60671ab5 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -1,4 +1,4 @@ -import { memo } from "react"; +import { memo, type PointerEventHandler } from "react"; import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; @@ -22,6 +22,7 @@ interface ComposerPrimaryActionsProps { isConnecting: boolean; isPreparingWorktree: boolean; hasSendableContent: boolean; + preserveComposerFocusOnPointerDown?: boolean; onPreviousPendingQuestion: () => void; onInterrupt: () => void; onImplementPlanInNewThread: () => void; @@ -45,6 +46,10 @@ export const formatPendingPrimaryActionLabel = (input: { return input.questionIndex > 0 ? "Submit answers" : "Submit answer"; }; +const preventPointerFocus: PointerEventHandler = (event) => { + event.preventDefault(); +}; + export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ compact, pendingAction, @@ -55,10 +60,15 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ isConnecting, isPreparingWorktree, hasSendableContent, + preserveComposerFocusOnPointerDown = false, onPreviousPendingQuestion, onInterrupt, onImplementPlanInNewThread, }: ComposerPrimaryActionsProps) { + const pointerFocusProps = preserveComposerFocusOnPointerDown + ? { onPointerDown: preventPointerFocus } + : undefined; + if (pendingAction) { return (
@@ -68,6 +78,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ size="icon-sm" variant="outline" className="rounded-full" + {...pointerFocusProps} onClick={onPreviousPendingQuestion} disabled={pendingAction.isResponding} aria-label="Previous question" @@ -79,6 +90,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ size="sm" variant="outline" className="rounded-full" + {...pointerFocusProps} onClick={onPreviousPendingQuestion} disabled={pendingAction.isResponding} > @@ -90,6 +102,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ type="submit" size="sm" className={cn("rounded-full", compact ? "px-3" : "px-4")} + {...pointerFocusProps} disabled={ pendingAction.isResponding || (pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance) @@ -111,6 +124,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ + + + ), + }); + } + if (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey) { + items.push({ + id: `version-mismatch:${versionMismatchDismissKey}`, + variant: "warning", + icon: , + title: "Client and server versions differ", + description: ( + <> + Client {versionMismatch.clientVersion} is connected to {versionMismatchServerLabel}{" "} + {versionMismatch.serverVersion}. Sync them if RPC calls or reconnects fail. + + ), + dismissLabel: "Dismiss version mismatch warning", + onDismiss: () => { + dismissVersionMismatch(versionMismatchDismissKey); + setDismissedVersionMismatchKey(versionMismatchDismissKey); + }, + }); + } + return items; + }, [ + activeEnvironmentUnavailableState, + handleReconnectActiveEnvironment, + navigate, + reconnectingEnvironmentId, + showVersionMismatchBanner, + versionMismatch, + versionMismatchDismissKey, + versionMismatchServerLabel, + ]); const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, @@ -2354,6 +2554,13 @@ export default function ChatView(props: ChatViewProps) { const localApi = readLocalApi(); if (!api || !localApi || !activeThread || isRevertingCheckpoint) return; + if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { + setThreadError( + activeThread.id, + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, + ); + return; + } if (phase === "running" || isSendBusy || isConnecting) { setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); return; @@ -2389,6 +2596,8 @@ export default function ChatView(props: ChatViewProps) { }, [ activeThread, + activeEnvironmentUnavailable, + activeEnvironmentUnavailableLabel, environmentId, isConnecting, isRevertingCheckpoint, @@ -2401,7 +2610,15 @@ export default function ChatView(props: ChatViewProps) { const onSend = async (e?: { preventDefault: () => void }) => { e?.preventDefault(); const api = readEnvironmentApi(environmentId); - if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return; + if ( + !api || + !activeThread || + isSendBusy || + isConnecting || + activeEnvironmentUnavailable || + sendInFlightRef.current + ) + return; if (activePendingProgress) { onAdvanceActivePendingUserInput(); return; @@ -3022,6 +3239,7 @@ export default function ChatView(props: ChatViewProps) { !isServerThread || isSendBusy || isConnecting || + activeEnvironmentUnavailable || sendInFlightRef.current ) { return; @@ -3136,6 +3354,7 @@ export default function ChatView(props: ChatViewProps) { activeThreadBranch, activeThread, beginLocalDispatch, + activeEnvironmentUnavailable, isConnecting, isSendBusy, isServerThread, @@ -3382,74 +3601,82 @@ export default function ChatView(props: ChatViewProps) { : "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]", )} > - +
+ +
+ +
+
{isGitRepo && ( )}
diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index c9d081b3fa..b6df9712bb 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -289,7 +289,7 @@ function sendServerConfigUpdatedPush(issues: ServerConfig["issues"]) { rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, { version: 1, type: "keybindingsUpdated", - payload: { issues }, + payload: { keybindings: fixture.serverConfig.keybindings, issues }, }); } diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index 38e07f59ce..ad47e01bb1 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -10,15 +10,29 @@ export function ProjectFavicon(input: { cwd: string; className?: string; }) { - const src = resolveEnvironmentHttpUrl({ - environmentId: input.environmentId, - pathname: "/api/project-favicon", - searchParams: { cwd: input.cwd }, - }); + const src = (() => { + try { + return resolveEnvironmentHttpUrl({ + environmentId: input.environmentId, + pathname: "/api/project-favicon", + searchParams: { cwd: input.cwd }, + }); + } catch { + return null; + } + })(); const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => - loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", + src && loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", ); + if (!src) { + return ( + + ); + } + return ( <> {status !== "loaded" ? ( diff --git a/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts b/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts index aed81ab01c..9a7e484dc2 100644 --- a/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts +++ b/apps/web/src/components/WebSocketConnectionSurface.logic.test.ts @@ -8,6 +8,7 @@ function makeStatus(overrides: Partial = {}): WsConnectionSt attemptCount: 0, closeCode: null, closeReason: null, + connectionLabel: null, connectedAt: null, disconnectedAt: null, hasConnected: false, diff --git a/apps/web/src/components/WebSocketConnectionSurface.tsx b/apps/web/src/components/WebSocketConnectionSurface.tsx index e0bb560980..b54bd865c8 100644 --- a/apps/web/src/components/WebSocketConnectionSurface.tsx +++ b/apps/web/src/components/WebSocketConnectionSurface.tsx @@ -53,8 +53,16 @@ function describeExhaustedToast(): string { return "Retries exhausted trying to reconnect"; } -function buildReconnectTitle(_status: WsConnectionStatus): string { - return "Disconnected from T3 Server"; +function getConnectionDisplayName(status: WsConnectionStatus): string { + return status.connectionLabel?.trim() || "T3 Server"; +} + +function buildReconnectTitle(status: WsConnectionStatus): string { + return `Disconnected from ${getConnectionDisplayName(status)}`; +} + +function buildRecoveredTitle(status: WsConnectionStatus): string { + return `Reconnected to ${getConnectionDisplayName(status)}`; } function describeRecoveredToast( @@ -297,7 +305,7 @@ export function WebSocketConnectionCoordinator() { }, description: describeExhaustedToast(), timeout: 0, - title: "Disconnected from T3 Server", + title: buildReconnectTitle(status), type: "error", }) : stackedThreadToast({ @@ -334,7 +342,7 @@ export function WebSocketConnectionCoordinator() { ) { const successToast = { description: describeRecoveredToast(previousDisconnectedAt, status.connectedAt), - title: "Reconnected to T3 Server", + title: buildRecoveredTitle(status), type: "success" as const, timeout: 0, data: { diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index f583af72ec..65e9c6dd8e 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -2,11 +2,13 @@ import type { AuthSessionState } from "@t3tools/contracts"; import React, { startTransition, useEffect, useRef, useState, useCallback } from "react"; import { APP_DISPLAY_NAME } from "../../branding"; +import { addSavedEnvironment } from "../../environments/runtime"; import { peekPairingTokenFromUrl, stripPairingTokenFromUrl, submitServerAuthCredential, } from "../../environments/primary"; +import { readHostedPairingRequest } from "../../hostedPairing"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -159,6 +161,127 @@ export function PairingRouteSurface({ ); } +export function HostedPairingRouteSurface() { + const hostedPairingRequestRef = useRef(readHostedPairingRequest()); + const [status, setStatus] = useState<"pairing" | "paired" | "error">(() => + hostedPairingRequestRef.current ? "pairing" : "error", + ); + const [message, setMessage] = useState(() => + hostedPairingRequestRef.current + ? "Connecting to this backend." + : "This pairing link is missing its backend host or token.", + ); + const [canRetry, setCanRetry] = useState(false); + const submitAttemptedRef = useRef(false); + const tokenSubmittedRef = useRef(false); + + const submitHostedPairingRequest = useCallback(async () => { + const request = hostedPairingRequestRef.current; + + if (!request) { + setStatus("error"); + setMessage("This pairing link is missing its backend host or token."); + setCanRetry(false); + return; + } + + if (tokenSubmittedRef.current) { + setStatus("error"); + setMessage("This one-time pairing token was already submitted. Request a new pairing link."); + setCanRetry(false); + return; + } + + setStatus("pairing"); + setMessage("Connecting to this backend."); + setCanRetry(false); + tokenSubmittedRef.current = true; + + try { + const record = await addSavedEnvironment({ + label: request.label, + host: request.host, + pairingCode: request.token, + }); + setStatus("paired"); + setMessage(`${record.label} is saved in this browser.`); + } catch (error) { + tokenSubmittedRef.current = false; + setStatus("error"); + setCanRetry(true); + setMessage( + `${errorMessageFromUnknown(error)} If the backend accepted this one-time token, request a new pairing link before retrying.`, + ); + } + }, []); + + useEffect(() => { + if (submitAttemptedRef.current) { + return; + } + submitAttemptedRef.current = true; + + stripPairingTokenFromUrl(); + void submitHostedPairingRequest(); + }, [submitHostedPairingRequest]); + + const request = hostedPairingRequestRef.current; + + return ( +
+
+
+
+
+
+ +
+

+ {APP_DISPLAY_NAME} +

+

+ {status === "paired" + ? "Backend paired" + : status === "error" + ? "Pairing failed" + : "Pairing backend"} +

+

{message}

+ + {request ? ( +
+ Host: {request.host} +
+ ) : null} + + {status === "error" ? ( +
+ Verify the backend is reachable from this browser, supports CORS for hosted clients, and + is served over HTTPS when opening this page from HTTPS. +
+ ) : null} + +
+ {status === "pairing" ? ( + + ) : canRetry ? ( + + ) : null} + {status === "paired" ? ( + + ) : null} +
+
+
+ ); +} + function errorMessageFromUnknown(error: unknown): string { if (error instanceof Error && error.message.trim().length > 0) { return error.message; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6be51f5d83..d64d031668 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -301,6 +301,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( promptHasText: boolean; isSendBusy: boolean; isConnecting: boolean; + isEnvironmentUnavailable: boolean; hasSendableContent: boolean; preserveComposerFocusOnPointerDown?: boolean; onPreviousPendingQuestion: () => void; @@ -321,6 +322,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions( promptHasText={props.promptHasText} isSendBusy={props.isSendBusy} isConnecting={props.isConnecting} + isEnvironmentUnavailable={props.isEnvironmentUnavailable} isPreparingWorktree={props.isPreparingWorktree} hasSendableContent={props.hasSendableContent} preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false} @@ -393,6 +395,10 @@ export interface ChatComposerProps { isConnecting: boolean; isSendBusy: boolean; isPreparingWorktree: boolean; + environmentUnavailable: { + readonly label: string; + readonly connectionState: "connecting" | "disconnected" | "error"; + } | null; // Pending approvals / inputs activePendingApproval: PendingApproval | null; @@ -500,6 +506,7 @@ export const ChatComposer = memo( isConnecting, isSendBusy, isPreparingWorktree, + environmentUnavailable, activePendingApproval, pendingApprovals, pendingUserInputs, @@ -1959,6 +1966,7 @@ export const ChatComposer = memo( className={cn( "rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45", isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border", + environmentUnavailable ? "opacity-75" : null, composerProviderState.composerSurfaceClassName, )} onFocusCapture={(event) => { @@ -2070,6 +2078,7 @@ export const ChatComposer = memo( promptHasText={false} isSendBusy={isSendBusy} isConnecting={isConnecting} + isEnvironmentUnavailable={environmentUnavailable !== null} isPreparingWorktree={false} hasSendableContent={false} preserveComposerFocusOnPointerDown @@ -2250,11 +2259,21 @@ export const ChatComposer = memo( ? "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" - : phase === "disconnected" - ? "Ask for follow-up changes or attach images" - : "Ask anything, @tag files/folders, or use / to show available commands" + : environmentUnavailable + ? `${environmentUnavailable.label} is ${ + environmentUnavailable.connectionState === "connecting" + ? "connecting" + : "disconnected" + }` + : phase === "disconnected" + ? "Ask for follow-up changes or attach images" + : "Ask anything, @tag files/folders, or use / to show available commands" + } + disabled={ + isConnecting || + isComposerApprovalState || + (environmentUnavailable !== null && activePendingProgress === null) } - disabled={isConnecting || isComposerApprovalState} /> {showMobilePendingAnswerActions ? (
0} isSendBusy={isSendBusy} isConnecting={isConnecting} + isEnvironmentUnavailable={environmentUnavailable !== null} isPreparingWorktree={isPreparingWorktree} hasSendableContent={composerSendState.hasSendableContent} preserveComposerFocusOnPointerDown={isMobileViewport} diff --git a/apps/web/src/components/chat/ChatHeader.test.ts b/apps/web/src/components/chat/ChatHeader.test.ts new file mode 100644 index 0000000000..1b7b219bdb --- /dev/null +++ b/apps/web/src/components/chat/ChatHeader.test.ts @@ -0,0 +1,48 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; + +import { shouldShowOpenInPicker } from "./ChatHeader"; + +describe("shouldShowOpenInPicker", () => { + const primaryEnvironmentId = EnvironmentId.make("environment-primary"); + + it("shows the picker for projects in the primary environment", () => { + expect( + shouldShowOpenInPicker({ + activeProjectName: "codething-mvp", + activeThreadEnvironmentId: primaryEnvironmentId, + primaryEnvironmentId, + }), + ).toBe(true); + }); + + it("hides the picker when hosted static mode has no primary environment", () => { + expect( + shouldShowOpenInPicker({ + activeProjectName: "codething-mvp", + activeThreadEnvironmentId: EnvironmentId.make("environment-remote"), + primaryEnvironmentId: null, + }), + ).toBe(false); + }); + + it("hides the picker for remote environments", () => { + expect( + shouldShowOpenInPicker({ + activeProjectName: "codething-mvp", + activeThreadEnvironmentId: EnvironmentId.make("environment-remote"), + primaryEnvironmentId, + }), + ).toBe(false); + }); + + it("hides the picker when there is no active project", () => { + expect( + shouldShowOpenInPicker({ + activeProjectName: undefined, + activeThreadEnvironmentId: primaryEnvironmentId, + primaryEnvironmentId, + }), + ).toBe(false); + }); +}); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 5d7c929247..3cd4576ab8 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -44,6 +44,18 @@ interface ChatHeaderProps { onToggleDiff: () => void; } +export function shouldShowOpenInPicker(input: { + readonly activeProjectName: string | undefined; + readonly activeThreadEnvironmentId: EnvironmentId; + readonly primaryEnvironmentId: EnvironmentId | null; +}): boolean { + return ( + Boolean(input.activeProjectName) && + input.primaryEnvironmentId !== null && + input.activeThreadEnvironmentId === input.primaryEnvironmentId + ); +} + export const ChatHeader = memo(function ChatHeader({ activeThreadEnvironmentId, activeThreadId, @@ -70,8 +82,11 @@ export const ChatHeader = memo(function ChatHeader({ onToggleDiff, }: ChatHeaderProps) { const primaryEnvironmentId = usePrimaryEnvironmentId(); - const isRemoteEnvironment = - primaryEnvironmentId !== null && activeThreadEnvironmentId !== primaryEnvironmentId; + const showOpenInPicker = shouldShowOpenInPicker({ + activeProjectName, + activeThreadEnvironmentId, + primaryEnvironmentId, + }); return (
@@ -106,7 +121,7 @@ export const ChatHeader = memo(function ChatHeader({ onDeleteScript={onDeleteProjectScript} /> )} - {activeProjectName && !isRemoteEnvironment && ( + {showOpenInPicker && ( void; +} + +interface ComposerBannerStackProps { + readonly className?: string; + readonly items: ReadonlyArray; +} + +export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) { + const [exitingItemId, setExitingItemId] = useState(null); + const dismissTimeoutRef = useRef | null>(null); + + useEffect(() => { + if (exitingItemId && !items.some((item) => item.id === exitingItemId)) { + setExitingItemId(null); + } + }, [exitingItemId, items]); + + useEffect(() => { + return () => { + if (dismissTimeoutRef.current) { + clearTimeout(dismissTimeoutRef.current); + } + }; + }, []); + + if (items.length === 0) { + return null; + } + + const frontItem = items[0]; + if (!frontItem) { + return null; + } + const stackedItems = items.slice(1); + const hasStack = stackedItems.length > 0; + const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id; + + const requestDismiss = (item: ComposerBannerStackItem) => { + if (!item.onDismiss || exitingItemId) { + return; + } + setExitingItemId(item.id); + if (dismissTimeoutRef.current) { + clearTimeout(dismissTimeoutRef.current); + } + dismissTimeoutRef.current = setTimeout(() => { + dismissTimeoutRef.current = null; + item.onDismiss?.(); + }, DISMISS_TRANSITION_MS); + }; + + return ( +
+
+ {showCollapsedStackCap ? ( + +
+ ); +} + +function ComposerBannerStackAlert({ + item, + exiting, + onDismissRequest, +}: { + readonly item: ComposerBannerStackItem; + readonly exiting: boolean; + readonly onDismissRequest: () => void; +}) { + const dismissOnly = item.onDismiss && !item.actions; + + return ( + + {item.icon} + {item.title} + {item.description ? {item.description} : null} + {item.actions || item.onDismiss ? ( + + {item.actions} + {item.onDismiss ? ( + + ) : null} + + ) : null} + + ); +} diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx index 9e60671ab5..fbeb9de30b 100644 --- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -20,6 +20,7 @@ interface ComposerPrimaryActionsProps { promptHasText: boolean; isSendBusy: boolean; isConnecting: boolean; + isEnvironmentUnavailable: boolean; isPreparingWorktree: boolean; hasSendableContent: boolean; preserveComposerFocusOnPointerDown?: boolean; @@ -58,6 +59,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ promptHasText, isSendBusy, isConnecting, + isEnvironmentUnavailable, isPreparingWorktree, hasSendableContent, preserveComposerFocusOnPointerDown = false, @@ -104,6 +106,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ className={cn("rounded-full", compact ? "px-3" : "px-4")} {...pointerFocusProps} disabled={ + isEnvironmentUnavailable || pendingAction.isResponding || (pendingAction.isLastQuestion ? !pendingAction.isComplete : !pendingAction.canAdvance) } @@ -143,7 +146,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ size="sm" className={cn("rounded-full", compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8")} {...pointerFocusProps} - disabled={isSendBusy || isConnecting} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable} > {isConnecting || isSendBusy ? "Sending..." : "Refine"} @@ -157,7 +160,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ size="sm" className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8" {...pointerFocusProps} - disabled={isSendBusy || isConnecting} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable} > {isConnecting || isSendBusy ? "Sending..." : "Implement"} @@ -170,7 +173,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8" aria-label="Implementation actions" {...pointerFocusProps} - disabled={isSendBusy || isConnecting} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable} /> } > @@ -178,7 +181,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ void onImplementPlanInNewThread()} > Implement in a new thread @@ -194,15 +197,17 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ type="submit" className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8" {...pointerFocusProps} - disabled={isSendBusy || isConnecting || !hasSendableContent} + disabled={isSendBusy || isConnecting || isEnvironmentUnavailable || !hasSendableContent} aria-label={ - isConnecting - ? "Connecting" - : isPreparingWorktree - ? "Preparing worktree" - : isSendBusy - ? "Sending" - : "Send message" + isEnvironmentUnavailable + ? "Environment disconnected" + : isConnecting + ? "Connecting" + : isPreparingWorktree + ? "Preparing worktree" + : isSendBusy + ? "Sending" + : "Send message" } > {isConnecting || isSendBusy ? ( diff --git a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx new file mode 100644 index 0000000000..7a20badf02 --- /dev/null +++ b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx @@ -0,0 +1,221 @@ +import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts"; +import { useEffect, useId, useRef, useState } from "react"; + +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; + +function describeSshTarget(request: DesktopSshPasswordPromptRequest): string { + return request.username ? `${request.username}@${request.destination}` : request.destination; +} + +function formatRemainingSeconds(seconds: number): string { + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; +} + +function getPromptErrorMessage(error: unknown): string { + const message = error instanceof Error ? error.message : "SSH password prompt failed."; + return message.includes("expired") || message.includes("no longer pending") + ? "This SSH password prompt expired. Try connecting again." + : message; +} + +export function SshPasswordPromptDialog() { + const [queue, setQueue] = useState([]); + const [password, setPassword] = useState(""); + const [isResponding, setIsResponding] = useState(false); + const [now, setNow] = useState(() => Date.now()); + const [responseError, setResponseError] = useState(null); + const currentRequest = queue[0] ?? null; + const inputRef = useRef(null); + const isRespondingRef = useRef(false); + const formId = useId(); + + useEffect(() => { + const bridge = window.desktopBridge; + if (!bridge?.onSshPasswordPrompt) { + return; + } + + return bridge.onSshPasswordPrompt((request) => { + setQueue((currentQueue) => [...currentQueue, request]); + }); + }, []); + + useEffect(() => { + setPassword(""); + setResponseError(null); + if (!currentRequest) { + return; + } + + setNow(Date.now()); + const frame = window.requestAnimationFrame(() => { + inputRef.current?.focus(); + inputRef.current?.select(); + }); + return () => { + window.cancelAnimationFrame(frame); + }; + }, [currentRequest]); + + useEffect(() => { + if (!currentRequest) { + return; + } + + const interval = window.setInterval(() => { + setNow(Date.now()); + }, 1_000); + return () => { + window.clearInterval(interval); + }; + }, [currentRequest]); + + const expiresAtMs = currentRequest ? Date.parse(currentRequest.expiresAt) : Number.NaN; + const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null; + const isExpired = remainingMs !== null && remainingMs <= 0; + const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000); + const remainingLabel = + remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds); + + useEffect(() => { + if (isExpired) { + setResponseError("This SSH password prompt expired. Try connecting again."); + } + }, [isExpired]); + + const removeCurrentPrompt = (requestId: string) => { + setQueue((currentQueue) => + currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue, + ); + setPassword(""); + setResponseError(null); + }; + + const respond = async (nextPassword: string | null) => { + if (!currentRequest || isRespondingRef.current) { + return; + } + + const requestId = currentRequest.requestId; + if (nextPassword !== null && isExpired) { + setResponseError("This SSH password prompt expired. Try connecting again."); + return; + } + + isRespondingRef.current = true; + setIsResponding(true); + setResponseError(null); + try { + await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword); + removeCurrentPrompt(requestId); + } catch (error) { + if (nextPassword === null) { + removeCurrentPrompt(requestId); + } else { + setResponseError(getPromptErrorMessage(error)); + } + } finally { + isRespondingRef.current = false; + setIsResponding(false); + } + }; + + const dismissExpiredPrompt = () => { + if (currentRequest) { + removeCurrentPrompt(currentRequest.requestId); + } + }; + + const cancelPrompt = () => { + if (isExpired) { + dismissExpiredPrompt(); + return; + } + void respond(null); + }; + + const target = currentRequest ? describeSshTarget(currentRequest) : null; + + return ( + { + if (!open) { + cancelPrompt(); + } + }} + > + + + SSH Password Required + + T3 needs your SSH password to connect to{" "} + {target ? {target} : "the remote host"}. The password is passed to the + local SSH process for this connection attempt and is not saved by T3 Code. + + + + { + event.preventDefault(); + void respond(password); + }} + > +
+
+

{currentRequest?.prompt}

+ {remainingLabel ? ( + + {isExpired ? "Expired" : remainingLabel} + + ) : null} +
+ setPassword(event.target.value)} + /> +
+ {responseError ? ( +

{responseError}

+ ) : ( +

+ Use SSH keys to avoid repeated password prompts on new SSH sessions. +

+ )} + +
+ + + + +
+
+ ); +} diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 880c4376e2..fe0a0cb581 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -1,8 +1,28 @@ -import { PlusIcon, QrCodeIcon } from "lucide-react"; -import { memo, useCallback, useEffect, useMemo, useState } from "react"; +import { + ChevronDownIcon, + ChevronsLeftRightEllipsisIcon, + PlusIcon, + QrCodeIcon, + RefreshCwIcon, + TerminalIcon, + TriangleAlertIcon, +} from "lucide-react"; +import { + type ReactNode, + memo, + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; import { type AuthClientSession, type AuthPairingLink, + type AdvertisedEndpoint, + type DesktopDiscoveredSshHost, + type DesktopSshEnvironmentTarget, type DesktopServerExposureState, type EnvironmentId, } from "@t3tools/contracts"; @@ -11,6 +31,7 @@ import { DateTime } from "effect"; import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; import { cn } from "../../lib/utils"; import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat"; +import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls"; import { SettingsPageContainer, SettingsRow, @@ -20,6 +41,7 @@ import { import { Input } from "../ui/input"; import { Dialog, + DialogClose, DialogFooter, DialogDescription, DialogHeader, @@ -28,6 +50,7 @@ import { DialogTitle, DialogTrigger, } from "../ui/dialog"; +import { ScrollArea } from "../ui/scroll-area"; import { AlertDialog, AlertDialogClose, @@ -44,8 +67,19 @@ import { Switch } from "../ui/switch"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { Button } from "../ui/button"; +import { Group, GroupSeparator } from "../ui/group"; +import { + Menu, + MenuGroup, + MenuGroupLabel, + MenuItem, + MenuPopup, + MenuSeparator, + MenuTrigger, +} from "../ui/menu"; import { Textarea } from "../ui/textarea"; -import { setPairingTokenOnUrl } from "../../pairingUrl"; +import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl"; +import { readHostedPairingRequest } from "../../hostedPairing"; import { createServerPairingCredential, fetchSessionState, @@ -63,10 +97,17 @@ import { useSavedEnvironmentRegistryStore, useSavedEnvironmentRuntimeStore, addSavedEnvironment, + connectDesktopSshEnvironment, + disconnectSavedEnvironment, getPrimaryEnvironmentConnection, reconnectSavedEnvironment, removeSavedEnvironment, } from "~/environments/runtime"; +import { useUiStateStore } from "~/uiStateStore"; +import { resolveServerConfigVersionMismatch } from "~/versionSkew"; +import { useServerConfig } from "~/rpc/serverState"; + +const DEFAULT_TAILSCALE_SERVE_PORT = 443; const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", @@ -135,6 +176,62 @@ function ConnectionStatusDot({ ); } +function AnimatedHeight({ children }: { readonly children: ReactNode }) { + const contentRef = useRef(null); + const [height, setHeight] = useState(null); + + useLayoutEffect(() => { + const element = contentRef.current; + if (!element) return; + let firstFrameId: number | null = null; + let secondFrameId: number | null = null; + + const updateHeight = () => { + const nextHeight = Math.ceil(element.scrollHeight || element.getBoundingClientRect().height); + setHeight((currentHeight) => (currentHeight === nextHeight ? currentHeight : nextHeight)); + }; + const cancelPendingFrames = () => { + if (firstFrameId !== null) { + window.cancelAnimationFrame(firstFrameId); + firstFrameId = null; + } + if (secondFrameId !== null) { + window.cancelAnimationFrame(secondFrameId); + secondFrameId = null; + } + }; + const updateHeightAfterPaint = () => { + cancelPendingFrames(); + updateHeight(); + firstFrameId = window.requestAnimationFrame(() => { + firstFrameId = null; + updateHeight(); + secondFrameId = window.requestAnimationFrame(() => { + secondFrameId = null; + updateHeight(); + }); + }); + }; + + updateHeightAfterPaint(); + const resizeObserver = new ResizeObserver(updateHeightAfterPaint); + resizeObserver.observe(element); + return () => { + resizeObserver.disconnect(); + cancelPendingFrames(); + }; + }, []); + + return ( +
+
{children}
+
+ ); +} + function getSavedBackendStatusTooltip( runtime: SavedEnvironmentRuntimeState | null, record: SavedEnvironmentRecord, @@ -160,12 +257,153 @@ function getSavedBackendStatusTooltip( : "Not connected yet."; } +function formatDesktopSshTarget(target: NonNullable): string { + const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname; + return target.port ? `${authority}:${target.port}` : authority; +} + +function parseManualDesktopSshTarget(input: { + readonly host: string; + readonly username: string; + readonly port: string; +}): DesktopSshEnvironmentTarget { + const rawHost = input.host.trim(); + if (rawHost.length === 0) { + throw new Error("SSH host or alias is required."); + } + + let hostname = rawHost; + let username = input.username.trim() || null; + let port: number | null = null; + + const atIndex = hostname.lastIndexOf("@"); + if (atIndex > 0) { + const inlineUsername = hostname.slice(0, atIndex).trim(); + hostname = hostname.slice(atIndex + 1).trim(); + if (!username && inlineUsername.length > 0) { + username = inlineUsername; + } + } + + const bracketedHostMatch = /^\[([^\]]+)\](?::(\d+))?$/u.exec(hostname); + if (bracketedHostMatch) { + hostname = bracketedHostMatch[1]!.trim(); + if (bracketedHostMatch[2]) { + port = Number.parseInt(bracketedHostMatch[2], 10); + } + } else { + const colonSegments = hostname.split(":"); + if (colonSegments.length === 2 && /^\d+$/u.test(colonSegments[1] ?? "")) { + hostname = colonSegments[0]!.trim(); + port = Number.parseInt(colonSegments[1]!, 10); + } + } + + const rawPort = input.port.trim(); + if (rawPort.length > 0) { + port = Number.parseInt(rawPort, 10); + } + + if (hostname.length === 0) { + throw new Error("SSH host or alias is required."); + } + + if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65_535)) { + throw new Error("SSH port must be between 1 and 65535."); + } + + return { + alias: hostname, + hostname, + username, + port, + }; +} + +function parsePairingUrlFields( + input: string, +): { readonly host: string; readonly pairingCode: string } | null { + const trimmed = input.trim(); + if (!trimmed) return null; + + try { + const urlLikeInput = + /^[a-zA-Z][a-zA-Z\d+.-]*:\/\//u.test(trimmed) || trimmed.startsWith("//") + ? trimmed + : `https://${trimmed}`; + const url = new URL(urlLikeInput, window.location.origin); + const hostedPairingRequest = readHostedPairingRequest(url); + if (hostedPairingRequest) { + return { + host: hostedPairingRequest.host, + pairingCode: hostedPairingRequest.token, + }; + } + + const pairingCode = getPairingTokenFromUrl(url); + if (!pairingCode) return null; + return { + host: url.origin, + pairingCode, + }; + } catch { + return null; + } +} + +function parseRemotePairingFields(input: { readonly host: string; readonly pairingCode: string }): { + readonly host: string; + readonly pairingCode: string; +} { + const parsedPairingUrl = parsePairingUrlFields(input.host); + if (parsedPairingUrl) return parsedPairingUrl; + + const host = input.host.trim(); + const pairingCode = input.pairingCode.trim(); + if (!host) { + throw new Error("Enter a backend host."); + } + if (!pairingCode) { + throw new Error("Enter a pairing code."); + } + return { host, pairingCode }; +} + +function formatDesktopSshConnectionError(error: unknown): string { + const fallback = "Failed to connect SSH host."; + const rawMessage = error instanceof Error ? error.message : fallback; + const withoutIpcPrefix = rawMessage.replace( + /^Error invoking remote method 'desktop:ensure-ssh-environment':\s*/u, + "", + ); + const withoutTaggedErrorPrefix = withoutIpcPrefix.replace(/^Ssh[A-Za-z]+Error:\s*/u, ""); + return withoutTaggedErrorPrefix.trim() || fallback; +} + /** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */ const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5"; +const ENDPOINT_ROW_CLASSNAME = "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5"; const ITEM_ROW_INNER_CLASSNAME = "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"; +type AccessSectionPresentation = "current" | "endpoint-rail"; + +function accessRowClassName(_presentation: AccessSectionPresentation) { + return ITEM_ROW_CLASSNAME; +} + +function endpointRowClassName(presentation: AccessSectionPresentation, isAvailable: boolean) { + if (presentation === "endpoint-rail") { + return cn( + "relative border-t border-border/60 px-4 py-3 first:border-t-0 sm:px-5", + !isAvailable && "bg-muted/20", + ); + } + + return cn(ENDPOINT_ROW_CLASSNAME, !isAvailable && "bg-muted/24"); +} + function sortDesktopPairingLinks(links: ReadonlyArray) { return [...links].toSorted( (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(), @@ -243,10 +481,66 @@ function removeDesktopClientSession( return current.filter((clientSession) => clientSession.sessionId !== sessionId); } -function resolveDesktopPairingUrl(endpointUrl: string, credential: string): string { - const url = new URL(endpointUrl); - url.pathname = "/pair"; - return setPairingTokenOnUrl(url, credential).toString(); +function selectPairingEndpoint( + endpoints: ReadonlyArray, + defaultEndpointKey?: string | null, +): AdvertisedEndpoint | null { + const availableEndpoints = endpoints.filter((endpoint) => endpoint.status !== "unavailable"); + if (defaultEndpointKey) { + const selectedEndpoint = availableEndpoints.find( + (endpoint) => endpointDefaultPreferenceKey(endpoint) === defaultEndpointKey, + ); + if (selectedEndpoint) { + return selectedEndpoint; + } + } + return ( + availableEndpoints.find((endpoint) => endpoint.isDefault) ?? + availableEndpoints.find((endpoint) => endpoint.reachability !== "loopback") ?? + availableEndpoints.find((endpoint) => endpoint.compatibility.hostedHttpsApp === "compatible") ?? + null + ); +} + +function isTailscaleHttpsEndpoint(endpoint: AdvertisedEndpoint): boolean { + return endpoint.id.startsWith("tailscale-magicdns:"); +} + +function endpointDefaultPreferenceKey(endpoint: AdvertisedEndpoint): string { + if (endpoint.id.startsWith("desktop-loopback:")) { + return "desktop-core:loopback:http"; + } + if (endpoint.id.startsWith("desktop-lan:")) { + return "desktop-core:lan:http"; + } + if (endpoint.id.startsWith("tailscale-ip:")) { + return "tailscale:ip:http"; + } + if (isTailscaleHttpsEndpoint(endpoint)) { + return "tailscale:magicdns:https"; + } + + let scheme = "unknown"; + try { + scheme = new URL(endpoint.httpBaseUrl).protocol.replace(/:$/u, ""); + } catch { + // Keep the stored preference stable even if a custom endpoint is malformed. + } + + return `${endpoint.provider.id}:${endpoint.reachability}:${scheme}:${endpoint.label}`; +} + +function resolveAdvertisedEndpointPairingUrl( + endpoint: AdvertisedEndpoint, + credential: string, +): string { + if (endpoint.compatibility.hostedHttpsApp === "compatible") { + return ( + resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ?? + resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential) + ); + } + return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential); } function resolveCurrentOriginPairingUrl(credential: string): string { @@ -254,9 +548,21 @@ function resolveCurrentOriginPairingUrl(credential: string): string { return setPairingTokenOnUrl(url, credential).toString(); } +function isHostedAppPairingUrl(value: string): boolean { + try { + const url = new URL(value); + return url.pathname === "/pair" && url.searchParams.has("host"); + } catch { + return false; + } +} + type PairingLinkListRowProps = { pairingLink: ServerPairingLinkRecord; endpointUrl: string | null | undefined; + endpoints: ReadonlyArray; + defaultEndpointKey: string | null; + presentation?: AccessSectionPresentation; revokingPairingLinkId: string | null; onRevoke: (id: string) => void; }; @@ -264,6 +570,9 @@ type PairingLinkListRowProps = { const PairingLinkListRow = memo(function PairingLinkListRow({ pairingLink, endpointUrl, + endpoints, + defaultEndpointKey, + presentation = "current", revokingPairingLinkId, onRevoke, }: PairingLinkListRowProps) { @@ -278,55 +587,197 @@ const PairingLinkListRow = memo(function PairingLinkListRow({ () => resolveCurrentOriginPairingUrl(pairingLink.credential), [pairingLink.credential], ); + const hostedPairingUrl = useMemo( + () => + endpointUrl != null && endpointUrl !== "" + ? resolveHostedPairingUrl(endpointUrl, pairingLink.credential) + : null, + [endpointUrl, pairingLink.credential], + ); + const endpointPairingUrl = useMemo(() => { + const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey); + return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null; + }, [defaultEndpointKey, endpoints, pairingLink.credential]); + const endpointCopyOptions = useMemo( + () => + endpoints + .filter((endpoint) => endpoint.status !== "unavailable") + .map((endpoint) => { + const url = resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential); + return { + key: endpointDefaultPreferenceKey(endpoint), + label: endpoint.label, + url, + detail: isHostedAppPairingUrl(url) ? "Hosted app link" : "Backend pairing URL", + }; + }), + [endpoints, pairingLink.credential], + ); const shareablePairingUrl = - endpointUrl != null && endpointUrl !== "" - ? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential) + endpointPairingUrl ?? + (endpointUrl != null && endpointUrl !== "" + ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential)) : isLoopbackHostname(window.location.hostname) ? null - : currentOriginPairingUrl; - const copyValue = shareablePairingUrl ?? pairingLink.credential; + : currentOriginPairingUrl); + const revealValue = shareablePairingUrl ?? pairingLink.credential; + const isShareableHostedAppPairingUrl = + shareablePairingUrl !== null && isHostedAppPairingUrl(shareablePairingUrl); const canCopyToClipboard = typeof window !== "undefined" && window.isSecureContext && navigator.clipboard?.writeText != null; - const { copyToClipboard, isCopied } = useCopyToClipboard({ - onCopy: () => { + const { copyToClipboard } = useCopyToClipboard<"code" | "hosted-link" | "link">({ + onCopy: (kind) => { toastManager.add({ type: "success", - title: shareablePairingUrl ? "Pairing URL copied" : "Pairing token copied", - description: shareablePairingUrl - ? "Open it in the client you want to pair to this environment." - : "Paste it into another client with this backend's reachable host.", + title: + kind === "hosted-link" + ? "Hosted app link copied" + : kind === "link" + ? "Pairing URL copied" + : "Pairing code copied", + description: + kind === "hosted-link" + ? "Open it in the browser on the device you want to connect." + : kind === "link" + ? "Open it in the client you want to pair to this environment." + : "Paste it into another client to finish pairing.", }); }, - onError: (error) => { + onError: (error, kind) => { setIsRevealDialogOpen(true); toastManager.add( stackedThreadToast({ type: "error", - title: canCopyToClipboard ? "Could not copy pairing URL" : "Clipboard copy unavailable", + title: canCopyToClipboard + ? kind === "hosted-link" + ? "Could not copy hosted app link" + : kind === "link" + ? "Could not copy pairing URL" + : "Could not copy pairing code" + : "Clipboard copy unavailable", description: canCopyToClipboard ? error.message : "Showing the full value instead.", }), ); }, }); - const handleCopy = useCallback(() => { - copyToClipboard(copyValue, undefined); - }, [copyToClipboard, copyValue]); + const copyPairingValue = useCallback( + (value: string, kind: "code" | "hosted-link" | "link") => { + copyToClipboard(value, kind); + }, + [copyToClipboard], + ); + + const copyKindForUrl = useCallback( + (url: string): "hosted-link" | "link" => (isHostedAppPairingUrl(url) ? "hosted-link" : "link"), + [], + ); + + const handleCopyCode = useCallback(() => { + copyPairingValue(pairingLink.credential, "code"); + }, [copyPairingValue, pairingLink.credential]); + + const handleCopyDefaultLink = useCallback(() => { + if (!shareablePairingUrl) return; + copyPairingValue(shareablePairingUrl, copyKindForUrl(shareablePairingUrl)); + }, [copyKindForUrl, copyPairingValue, shareablePairingUrl]); const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt); const roleLabel = pairingLink.role === "owner" ? "Owner" : "Client"; const primaryLabel = pairingLink.label ?? `${roleLabel} link`; + const defaultEndpointCopyOption = + endpointCopyOptions.find((option) => option.key === defaultEndpointKey) ?? + endpointCopyOptions[0] ?? + null; + const defaultEndpointCopyLabel = defaultEndpointCopyOption?.label ?? "URL"; + const backendEndpointCopyOptions = endpointCopyOptions.filter( + (option) => !isHostedAppPairingUrl(option.url), + ); + const hostedEndpointCopyOptions = endpointCopyOptions.filter((option) => + isHostedAppPairingUrl(option.url), + ); + const renderEndpointMenuItems = ( + options: typeof endpointCopyOptions = endpointCopyOptions, + renderDetail = true, + ) => + options.map((option) => ( + copyPairingValue(option.url, copyKindForUrl(option.url))} + > + + {option.label} + {renderDetail ? ( + + {option.detail} + + ) : null} + + + )); + const renderPairingCodeMenuItem = (renderDetail = true) => ( + + + Copy code + {renderDetail ? ( + Token only + ) : null} + + + ); + const renderCompactEndpointGroup = ( + label: string, + options: typeof endpointCopyOptions, + includeSeparator: boolean, + ) => + options.length > 0 ? ( + <> + {includeSeparator ? : null} + + {label} + {renderEndpointMenuItems(options, false)} + + + ) : null; + const renderGroupedCopyMenuItems = (options?: { codeFirst?: boolean }) => ( + <> + {options?.codeFirst ? ( + <> + + Pairing code + {renderPairingCodeMenuItem(false)} + + {endpointCopyOptions.length > 0 ? : null} + + ) : null} + {renderCompactEndpointGroup("Pairing URLs", backendEndpointCopyOptions, false)} + {renderCompactEndpointGroup( + "Hosted app link", + hostedEndpointCopyOptions, + backendEndpointCopyOptions.length > 0, + )} + {!options?.codeFirst ? ( + <> + {endpointCopyOptions.length > 0 ? : null} + + Pairing code + {renderPairingCodeMenuItem(false)} + + + ) : null} + + ); if (expiresAtMs <= nowMs) { return null; } return ( -
+
@@ -377,27 +828,70 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
{canCopyToClipboard ? ( - + <> + {shareablePairingUrl ? ( + + + + + + } + > + + + + {renderGroupedCopyMenuItems()} + + + + ) : ( + + )} + ) : ( }> - {shareablePairingUrl ? "Show link" : "Show token"} + {shareablePairingUrl ? "Show link" : "Show code"} )} - {shareablePairingUrl ? "Pairing link" : "Pairing token"} + + {shareablePairingUrl + ? isShareableHostedAppPairingUrl + ? "Hosted app pairing link" + : "Pairing link" + : "Pairing code"} + {shareablePairingUrl - ? "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect." - : "Clipboard copy is unavailable here. Manually copy this token and pair from another client using this backend's reachable host."} + ? isShareableHostedAppPairingUrl + ? "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect." + : "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect." + : "Clipboard copy is unavailable here. Manually copy this code into another client."}