diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index f26c8428fe..3e95a039c0 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import React, { useCallback, useMemo, useRef, useState } from "react"; import type { EnvironmentId, @@ -149,9 +149,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { [repositoryGroups], ); - const [selectedEnvironmentId, setSelectedEnvironmentId] = useState( - projects[0]?.environmentId ?? null, + const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState( + null, ); + const selectedEnvironmentId = + selectedEnvironmentIdOverride !== null && + projects.some((project) => project.environmentId === selectedEnvironmentIdOverride) + ? selectedEnvironmentIdOverride + : (projects[0]?.environmentId ?? null); const [selectedProjectKey, setSelectedProjectKey] = useState(null); const [selectedModelKey, setSelectedModelKey] = useState(null); const [workspaceMode, setWorkspaceMode] = useState("local"); @@ -170,11 +175,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { const [expandedProvider, setExpandedProvider] = useState(null); const reset = useCallback(() => { - console.log("[new task flow] reset", { - defaultEnvironmentId: projects[0]?.environmentId ?? null, - projectCount: projects.length, - }); - setSelectedEnvironmentId(projects[0]?.environmentId ?? null); + setSelectedEnvironmentId(null); setSelectedProjectKey(null); setSelectedModelKey(null); setWorkspaceMode("local"); @@ -186,18 +187,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE); setModelSelectionOverrides({}); setExpandedProvider(null); - }, [projects]); - - useEffect(() => { - if (selectedEnvironmentId !== null || projects.length === 0) { - return; - } - - console.log("[new task flow] initializing environment", { - environmentId: projects[0]!.environmentId, - }); - setSelectedEnvironmentId(projects[0]!.environmentId); - }, [projects, selectedEnvironmentId]); + }, []); const environments = useMemo( () => @@ -531,24 +521,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) { ], ); - useEffect(() => { - console.log("[new task flow] state", { - availableBranchCount: availableBranches.length, - environmentCount: environments.length, - logicalProjectCount: logicalProjects.length, - selectedEnvironmentId, - selectedProjectKey, - selectedProjectTitle: selectedProject?.title ?? null, - }); - }, [ - availableBranches.length, - environments.length, - logicalProjects.length, - selectedEnvironmentId, - selectedProject?.title, - selectedProjectKey, - ]); - return {props.children}; } diff --git a/apps/mobile/src/state/use-vcs-action-state.ts b/apps/mobile/src/state/use-vcs-action-state.ts index 4cba19fdb0..e169005a07 100644 --- a/apps/mobile/src/state/use-vcs-action-state.ts +++ b/apps/mobile/src/state/use-vcs-action-state.ts @@ -1,7 +1,9 @@ import { useAtomValue } from "@effect/atom-react"; import { type VcsActionState, type VcsActionTarget } from "@t3tools/client-runtime/state/vcs"; +import { Atom } from "effect/unstable/reactivity"; import { useCallback, useEffect, useRef, useState } from "react"; +import { appAtomRegistry } from "./atom-registry"; import { vcsActionManager } from "./vcs"; export function useVcsActionState(target: VcsActionTarget): VcsActionState { @@ -17,26 +19,28 @@ export interface GitActionResultNotification { const RESULT_DISMISS_MS = 5_000; -type ResultListener = (result: GitActionResultNotification | null) => void; -const resultListeners = new Set(); -let currentResult: GitActionResultNotification | null = null; +const gitActionResultAtom = Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel("mobile:git-action-result"), +); let dismissTimer: ReturnType | null = null; function broadcast(result: GitActionResultNotification | null): void { - currentResult = result; - for (const listener of resultListeners) { - listener(result); - } + appAtomRegistry.set(gitActionResultAtom, result); } export function showGitActionResult(result: GitActionResultNotification): void { if (dismissTimer) clearTimeout(dismissTimer); broadcast(result); - dismissTimer = setTimeout(() => broadcast(null), RESULT_DISMISS_MS); + dismissTimer = setTimeout(() => { + dismissTimer = null; + broadcast(null); + }, RESULT_DISMISS_MS); } export function dismissGitActionResult(): void { if (dismissTimer) clearTimeout(dismissTimer); + dismissTimer = null; broadcast(null); } @@ -44,16 +48,7 @@ export function useGitActionResultNotification(): { readonly result: GitActionResultNotification | null; readonly dismiss: () => void; } { - const [result, setResult] = useState(currentResult); - - useEffect(() => { - resultListeners.add(setResult); - setResult(currentResult); - return () => { - resultListeners.delete(setResult); - }; - }, []); - + const result = useAtomValue(gitActionResultAtom); return { result, dismiss: dismissGitActionResult }; } diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index e135d0813b..d9b0989b68 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -11,7 +11,7 @@ import { import { memo, useMemo } from "react"; import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; -import { useProject, useThreadDetail } from "../state/entities"; +import { useProject, useThread } from "../state/entities"; import { useIsMobile } from "../hooks/useMediaQuery"; import { type EnvMode, @@ -206,7 +206,7 @@ export const BranchToolbar = memo(function BranchToolbar({ () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); - const serverThread = useThreadDetail(threadRef); + const serverThread = useThread(threadRef); const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), ); diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 2296a7a298..fd2c2b8c25 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -20,7 +20,7 @@ import { import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; import { usePaginatedBranches } from "../state/queries"; -import { useProject, useThreadDetail } from "../state/entities"; +import { useProject, useThread } from "../state/entities"; import { useEnvironmentQuery } from "../state/query"; import { threadEnvironment } from "../state/threads"; import { useAtomCommand } from "../state/use-atom-command"; @@ -111,7 +111,7 @@ export function BranchToolbarBranchSelector({ () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); - const serverThread = useThreadDetail(threadRef); + const serverThread = useThread(threadRef); const serverSession = serverThread?.session ?? null; const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), @@ -476,14 +476,6 @@ export function BranchToolbarBranchSelector({ setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1); }, []); - useEffect(() => { - if (isBranchMenuOpen) { - return; - } - setShowTopBranchScrollFade(false); - setShowBottomBranchScrollFade(false); - }, [isBranchMenuOpen]); - useLayoutEffect(() => { if (!isBranchMenuOpen) { return; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e9cabf70a4..76ec8260b7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -180,10 +180,11 @@ import { useEnvironments, usePrimaryEnvironment } from "../state/environments"; import { useProject, useProjects, - useThreadDetail, + useThread, useThreadProposedPlans, useThreadRefs, } from "../state/entities"; +import { environmentShell } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; @@ -352,21 +353,6 @@ function useLocalDispatchState(input: { }) { const [localDispatch, setLocalDispatch] = useState(null); - const beginLocalDispatch = useCallback( - (options?: { preparingWorktree?: boolean }) => { - const preparingWorktree = Boolean(options?.preparingWorktree); - setLocalDispatch((current) => { - if (current) { - return current.preparingWorktree === preparingWorktree - ? current - : { ...current, preparingWorktree }; - } - return createLocalDispatchSnapshot(input.activeThread, options); - }); - }, - [input.activeThread], - ); - const resetLocalDispatch = useCallback(() => { setLocalDispatch(null); }, []); @@ -392,20 +378,29 @@ function useLocalDispatchState(input: { localDispatch, ], ); - - useEffect(() => { - if (!serverAcknowledgedLocalDispatch) { - return; - } - resetLocalDispatch(); - }, [resetLocalDispatch, serverAcknowledgedLocalDispatch]); + const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch; + const beginLocalDispatch = useCallback( + (options?: { preparingWorktree?: boolean }) => { + const preparingWorktree = Boolean(options?.preparingWorktree); + setLocalDispatch((current) => { + const active = serverAcknowledgedLocalDispatch ? null : current; + if (active) { + return active.preparingWorktree === preparingWorktree + ? active + : { ...active, preparingWorktree }; + } + return createLocalDispatchSnapshot(input.activeThread, options); + }); + }, + [input.activeThread, serverAcknowledgedLocalDispatch], + ); return { beginLocalDispatch, resetLocalDispatch, - localDispatchStartedAt: localDispatch?.startedAt ?? null, - isPreparingWorktree: localDispatch?.preparingWorktree ?? false, - isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch, + localDispatchStartedAt: activeLocalDispatch?.startedAt ?? null, + isPreparingWorktree: activeLocalDispatch?.preparingWorktree ?? false, + isSendBusy: activeLocalDispatch !== null, }; } @@ -478,7 +473,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); - const serverThread = useThreadDetail(threadRef); + const serverThread = useThread(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const projectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) @@ -834,7 +829,7 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane newShortcutLabel, closeShortcutLabel, }: PersistentThreadTerminalPanelProps) { - const serverThread = useThreadDetail(threadRef); + const serverThread = useThread(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const projectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) @@ -1024,7 +1019,7 @@ function ChatViewContent(props: ChatViewProps) { ); const composerDraftTarget: ScopedThreadRef | DraftId = routeKind === "server" ? routeThreadRef : props.draftId; - const serverThread = useThreadDetail(routeKind === "server" ? routeThreadRef : null); + const serverThread = useThread(routeKind === "server" ? routeThreadRef : null); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); const activeThreadLastVisitedAt = useUiStateStore((store) => routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined, @@ -1348,6 +1343,10 @@ function ChatViewContent(props: ChatViewProps) { ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null; const activeProject = useProject(activeProjectRef); + const activeEnvironmentShell = useEnvironmentQuery( + activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null, + ); + const activeEnvironmentBootstrapComplete = activeEnvironmentShell.data?.snapshot._tag === "Some"; const activeProjectKey = activeProject ? `${activeProject.environmentId}:${activeProject.workspaceRoot}` : null; @@ -1381,9 +1380,9 @@ function ChatViewContent(props: ChatViewProps) { ); useEffect(() => { - if (!activeThreadRef) return; + if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return; useRightPanelStore.getState().reconcileFileSurfaces(activeThreadRef, activeProject !== null); - }, [activeProject, activeThreadRef]); + }, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]); // Compute the list of environments this logical project spans, used to // drive the environment picker in BranchToolbar. @@ -3460,6 +3459,13 @@ function ChatViewContent(props: ChatViewProps) { return; } + if (command === "rightPanel.toggle") { + event.preventDefault(); + event.stopPropagation(); + toggleRightPanel(); + return; + } + if (command === "terminal.split") { event.preventDefault(); event.stopPropagation(); @@ -3554,6 +3560,7 @@ function ChatViewContent(props: ChatViewProps) { splitPanelTerminal, keybindings, onToggleDiff, + toggleRightPanel, toggleTerminalVisibility, composerRef, ]); @@ -5041,7 +5048,11 @@ function ChatViewContent(props: ChatViewProps) { ) : null} {expandedImage && ( - + )} ); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 79c02f3cf1..66a7cacef4 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -818,35 +818,6 @@ function OpenCommandPaletteDialog() { [browseEnvironmentId, buildAddProjectSourceGroups, sourceControlDiscovery.data], ); - useEffect(() => { - if (addProjectEnvironmentId === null) { - return; - } - sourceControlDiscovery.refresh(); - }, [addProjectEnvironmentId, sourceControlDiscovery.refresh]); - - useEffect(() => { - if (addProjectEnvironmentId === null || sourceControlDiscovery.data === null) { - return; - } - setViewStack((previousViews) => { - const currentTopView = previousViews.at(-1); - if (currentTopView?.groups[0]?.value !== `sources:${addProjectEnvironmentId}`) { - return previousViews; - } - return [ - ...previousViews.slice(0, -1), - { - addonIcon: , - groups: buildAddProjectSourceGroups( - addProjectEnvironmentId, - buildAddProjectRemoteSourceReadiness(sourceControlDiscovery.data), - ), - }, - ]; - }); - }, [addProjectEnvironmentId, buildAddProjectSourceGroups, sourceControlDiscovery.data]); - const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map( (option) => ({ kind: "action", @@ -993,7 +964,17 @@ function OpenCommandPaletteDialog() { }); const rootGroups = buildRootGroups({ actionItems, recentThreadItems }); - const activeGroups = currentView ? currentView.groups : rootGroups; + const sourceSelectionViewValue = + addProjectEnvironmentId === null ? null : `sources:${addProjectEnvironmentId}`; + const activeGroups = + addProjectEnvironmentId !== null && + currentView !== null && + currentView.groups[0]?.value === sourceSelectionViewValue + ? buildAddProjectSourceGroups( + addProjectEnvironmentId, + buildAddProjectRemoteSourceReadiness(sourceControlDiscovery.data), + ) + : (currentView?.groups ?? rootGroups); const filteredGroups = filterCommandPaletteGroups({ activeGroups, diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index de7c7a62c0..7ea2d58847 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -26,9 +26,9 @@ import { } from "react"; import { useOpenInPreferredEditor } from "../editorPreferences"; import { type DraftId } from "../composerDraftStore"; +import { openDiffFilePrimaryAction } from "../diffFileActions"; import { useCheckpointDiff } from "~/lib/checkpointDiffState"; import { cn } from "~/lib/utils"; -import { resolvePathLinkTarget } from "../terminal-links"; import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"; import { useTheme } from "../hooks/useTheme"; import { @@ -39,13 +39,14 @@ import { resolveFileDiffPath, } from "../lib/diffRendering"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; -import { useProject, useThreadDetail } from "../state/entities"; +import { useProject, useThread } from "../state/entities"; import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { useSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell"; import { AnnotatableFileDiff } from "./diffs/AnnotatableFileDiff"; import { ToggleGroup, Toggle } from "./ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { useEnvironmentQuery } from "../state/query"; import { serverEnvironment } from "../state/server"; import { vcsEnvironment } from "../state/vcs"; @@ -53,12 +54,21 @@ import { vcsEnvironment } from "../state/vcs"; type DiffRenderMode = "stacked" | "split"; type DiffThemeType = "light" | "dark"; +interface CollapsedDiffFilesState { + readonly scopeKey: string | null; + readonly fileKeys: ReadonlySet; +} + +const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet = new Set(); + const DIFF_PANEL_UNSAFE_CSS = ` [data-diffs-header], [data-diff], [data-file], [data-error-wrapper], [data-virtualizer-buffer] { + --diffs-header-font-family: var(--font-sans) !important; + --diffs-font-family: var(--font-mono) !important; --diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; --diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important; @@ -99,6 +109,37 @@ const DIFF_PANEL_UNSAFE_CSS = ` z-index: 4; background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important; border-bottom: 1px solid var(--border) !important; + align-items: center !important; + font-family: var(--font-sans) !important; + font-size: 12px !important; + line-height: 1 !important; + min-height: 32px !important; + padding-block: 6px !important; +} + +[data-diffs-header] [data-header-content] { + align-items: center !important; + line-height: 1 !important; +} + +[data-diffs-header] [data-metadata] { + align-items: center !important; + line-height: 1 !important; + font-variant-numeric: tabular-nums; +} + +[data-diffs-header] [data-additions-count], +[data-diffs-header] [data-deletions-count] { + font-family: var(--font-mono) !important; + font-size: 11px !important; + font-variant-numeric: tabular-nums; + line-height: 1 !important; +} + +[data-diffs-header] [data-change-icon], +[data-diffs-header] [data-rename-icon] { + display: block; + flex-shrink: 0; } [data-title] { @@ -109,6 +150,7 @@ const DIFF_PANEL_UNSAFE_CSS = ` text-decoration: underline; text-decoration-color: transparent; text-underline-offset: 2px; + font-family: var(--font-sans) !important; } [data-title]:hover { @@ -131,9 +173,10 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff const [diffRenderMode, setDiffRenderMode] = useState("stacked"); const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap); const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace); - const [collapsedDiffFileKeys, setCollapsedDiffFileKeys] = useState>( - () => new Set(), - ); + const [collapsedDiffFiles, setCollapsedDiffFiles] = useState(() => ({ + scopeKey: null, + fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS, + })); const patchViewportRef = useRef(null); const turnStripRef = useRef(null); const previousDiffOpenRef = useRef(false); @@ -146,7 +189,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) }); const diffOpen = diffSearch.diff === "1"; const activeThreadId = routeThreadRef?.threadId ?? null; - const activeThread = useThreadDetail(routeThreadRef); + const activeThread = useThread(routeThreadRef); const activeProjectId = activeThread?.projectId ?? null; const activeProject = useProject( activeThread && activeProjectId @@ -201,6 +244,13 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff selectedTurn && (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]); const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : "conversation"; + const collapseScopeKey = routeThreadRef + ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` + : null; + const collapsedDiffFileKeys = + collapsedDiffFiles.scopeKey === collapseScopeKey + ? collapsedDiffFiles.fileKeys + : EMPTY_COLLAPSED_DIFF_FILE_KEYS; const reviewSectionTitle = selectedTurn ? `Turn ${selectedCheckpointTurnCount ?? "?"}` : "All turns"; @@ -283,19 +333,6 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff ); }, [renderablePatch]); - useEffect(() => { - if (renderableFiles.length === 0) { - setCollapsedDiffFileKeys((current) => (current.size === 0 ? current : new Set())); - return; - } - - const visibleFileKeys = new Set(renderableFiles.map(buildFileDiffRenderKey)); - setCollapsedDiffFileKeys((current) => { - const next = new Set([...current].filter((fileKey) => visibleFileKeys.has(fileKey))); - return next.size === current.size ? current : next; - }); - }, [renderableFiles]); - useEffect(() => { if (diffOpen && !previousDiffOpenRef.current) { setDiffWordWrap(settings.diffWordWrap); @@ -316,27 +353,36 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff const openDiffFile = useCallback( (filePath: string) => { - const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath; - void (async () => { - const result = await openInPreferredEditor(targetPath); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - console.warn("Failed to open diff file in editor.", squashAtomCommandFailure(result)); - } - })(); + openDiffFilePrimaryAction({ + threadRef: routeThreadRef, + filePath, + activeCwd, + openInEditor: (targetPath) => { + void (async () => { + const result = await openInPreferredEditor(targetPath); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + console.warn("Failed to open diff file in editor.", squashAtomCommandFailure(result)); + } + })(); + }, + }); }, - [activeCwd, openInPreferredEditor], + [activeCwd, openInPreferredEditor, routeThreadRef], + ); + const toggleDiffFileCollapsed = useCallback( + (fileKey: string) => { + setCollapsedDiffFiles((current) => { + const next = new Set(current.scopeKey === collapseScopeKey ? current.fileKeys : []); + if (next.has(fileKey)) { + next.delete(fileKey); + } else { + next.add(fileKey); + } + return { scopeKey: collapseScopeKey, fileKeys: next }; + }); + }, + [collapseScopeKey], ); - const toggleDiffFileCollapsed = useCallback((fileKey: string) => { - setCollapsedDiffFileKeys((current) => { - const next = new Set(current); - if (next.has(fileKey)) { - next.delete(fileKey); - } else { - next.add(fileKey); - } - return next; - }); - }, []); const selectTurn = (turnId: TurnId) => { if (!activeThread) return; @@ -482,35 +528,41 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff {orderedTurnDiffSummaries.map((summary) => ( - + + {summary.turnId} + ))} @@ -534,30 +586,50 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff - { - setDiffWordWrap(Boolean(pressed)); - }} - > - - - { - setDiffIgnoreWhitespace(Boolean(pressed)); - }} - > - - + + { + setDiffWordWrap(Boolean(pressed)); + }} + /> + } + > + + + + {diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"} + + + + { + setDiffIgnoreWhitespace(Boolean(pressed)); + }} + /> + } + > + + + + {diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"} + + ); @@ -635,26 +707,36 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff sectionTitle={reviewSectionTitle} composerDraftTarget={composerDraftTarget} renderHeaderPrefix={() => ( - + + { + event.stopPropagation(); + toggleDiffFileCollapsed(fileKey); + }} + /> + } + > + {collapsed ? ( + + ) : ( + + )} + + + {collapsed ? "Expand diff" : "Collapse diff"} + + )} options={{ collapsed, diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d91e3794b9..af3f7b4728 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -76,7 +76,7 @@ import { useVcsInitAction, useVcsPullAction, } from "~/lib/sourceControlActions"; -import { useThreadDetail } from "~/state/entities"; +import { useThread } from "~/state/entities"; import { useEnvironmentQuery } from "~/state/query"; import { serverEnvironment } from "~/state/server"; import { sourceControlEnvironment } from "~/state/sourceControl"; @@ -135,6 +135,22 @@ interface RunGitActionWithToastInput { } const GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS = 250; + +type RefreshVcsStatus = (target: { + readonly environmentId: ScopedThreadRef["environmentId"]; + readonly input: { readonly cwd: string }; +}) => Promise; + +function requestVcsStatusRefresh( + refresh: RefreshVcsStatus, + environmentId: ScopedThreadRef["environmentId"] | null, + cwd: string | null, +): void { + if (environmentId === null || cwd === null) { + return; + } + void refresh({ environmentId, input: { cwd } }); +} const RUNNING_SOURCE_CONTROL_ACTIONS = ["runStackedAction", "pull", "publishRepository"] as const; const PUBLISH_PROVIDER_OPTIONS = [ @@ -363,8 +379,9 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { input: {}, }), ); - const [publishProvider, setPublishProvider] = useState("github"); - const [publishRepository, setPublishRepository] = useState(""); + const [selectedPublishProvider, setSelectedPublishProvider] = + useState(null); + const [publishRepositoryOverride, setPublishRepositoryOverride] = useState(null); const [publishVisibility, setPublishVisibility] = useState("private"); const [publishRemoteName, setPublishRemoteName] = useState("origin"); @@ -375,7 +392,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { const [publishResult, setPublishResult] = useState( null, ); - const [hasUserEditedPublishRepository, setHasUserEditedPublishRepository] = useState(false); const sourceControlScope = useMemo( () => ({ environmentId: props.environmentId, @@ -426,10 +442,18 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { }), [publishProviderReadiness], ); + const firstReadyPublishProvider = sortedPublishProviderOptions.find( + (option) => publishProviderReadiness[option.value].ready, + )?.value; + const publishProvider = + selectedPublishProvider !== null && publishProviderReadiness[selectedPublishProvider].ready + ? selectedPublishProvider + : (firstReadyPublishProvider ?? selectedPublishProvider ?? "github"); const selectedPublishProviderReadiness = publishProviderReadiness[publishProvider]; const publishRepositoryPrefill = publishAccountByProvider[publishProvider] ? `${publishAccountByProvider[publishProvider]}/` : ""; + const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill; const currentPublishProvider = publishProviderOption(publishProvider); const publishHost = currentPublishProvider.host; const publishPathPlaceholder = currentPublishProvider.pathPlaceholder; @@ -441,13 +465,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { null, ] as const; - useEffect(() => { - if (!props.open || hasUserEditedPublishRepository) { - return; - } - setPublishRepository(publishRepositoryPrefill); - }, [hasUserEditedPublishRepository, props.open, publishRepositoryPrefill]); - const canSubmitPublishRepository = useMemo(() => { if (!selectedPublishProviderReadiness.ready) return false; if (publishRepositoryAction.isPending) return false; @@ -458,21 +475,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { return owner.length > 0 && name.length > 0; }, [publishRepository, publishRepositoryAction.isPending, selectedPublishProviderReadiness]); - useEffect(() => { - if (!props.open) { - return; - } - if (publishProviderReadiness[publishProvider].ready) { - return; - } - const firstReadyProvider = PUBLISH_PROVIDER_OPTIONS.find( - (option) => publishProviderReadiness[option.value].ready, - ); - if (firstReadyProvider) { - setPublishProvider(firstReadyProvider.value); - } - }, [props.open, publishProvider, publishProviderReadiness]); - const submitPublishRepository = useCallback(() => { if (!canSubmitPublishRepository) { return; @@ -516,8 +518,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { const resetState = useCallback(() => { setPublishRemoteName("origin"); - setPublishRepository(""); - setHasUserEditedPublishRepository(false); + setPublishRepositoryOverride(null); setPublishWizardStep(0); setPublishAdvancedOpen(false); setPublishError(null); @@ -610,7 +611,10 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { setPublishProvider(value as PublishProviderKind)} + onValueChange={(value) => { + setSelectedPublishProvider(value as PublishProviderKind); + setPublishRepositoryOverride(null); + }} aria-labelledby="publish-provider-cards-label" className="grid grid-cols-2 gap-2.5" > @@ -696,8 +700,7 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { name="publish-repository-path" value={publishRepository} onChange={(event) => { - setPublishRepository(event.target.value); - setHasUserEditedPublishRepository(true); + setPublishRepositoryOverride(event.target.value); }} onKeyDown={(event) => { if (event.key === "Enter") { @@ -981,7 +984,7 @@ export default function GitActionsControl({ () => (activeThreadRef ? { threadRef: activeThreadRef } : undefined), [activeThreadRef], ); - const activeServerThread = useThreadDetail(activeThreadRef); + const activeServerThread = useThread(activeThreadRef); const activeDraftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) @@ -1081,6 +1084,9 @@ export default function GitActionsControl({ }) : null, ); + const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, { + reportFailure: false, + }); const { data: gitStatus, error: gitStatusError } = gitStatusQuery; const sourceControlPresentation = useMemo( () => getSourceControlPresentation(gitStatus?.sourceControlProvider), @@ -1183,7 +1189,7 @@ export default function GitActionsControl({ } refreshTimeout = window.setTimeout(() => { refreshTimeout = null; - gitStatusQuery.refresh(); + requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd); }, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS); }; const handleVisibilityChange = () => { @@ -1202,7 +1208,7 @@ export default function GitActionsControl({ window.removeEventListener("focus", scheduleRefreshCurrentGitStatus); document.removeEventListener("visibilitychange", handleVisibilityChange); }; - }, [gitCwd, gitStatusQuery.refresh]); + }, [activeEnvironmentId, gitCwd, refreshVcsStatus]); const openExistingPr = useCallback(async () => { const api = readLocalApi(); @@ -1719,7 +1725,7 @@ export default function GitActionsControl({ { if (open) { - gitStatusQuery.refresh(); + requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd); } }} > diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index 0b849bc563..481ddab05a 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -1,6 +1,6 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { FolderIcon } from "lucide-react"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { useAssetUrl } from "../assets/assetUrls"; const loadedProjectFaviconSrcs = new Set(); @@ -8,38 +8,42 @@ const loadedProjectFaviconSrcs = new Set(); export function ProjectFavicon(input: { environmentId: EnvironmentId; cwd: string; - className?: string; + className?: string | undefined; }) { const src = useAssetUrl(input.environmentId, { _tag: "project-favicon", cwd: input.cwd, }); - const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => - src && loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", - ); - useEffect(() => { - setStatus(src && loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading"); - }, [src]); if (!src) { - return ( - - ); + return ; } + return ; +} + +function ProjectFaviconFallback({ className }: { readonly className?: string | undefined }) { + return ; +} + +function ProjectFaviconImage({ + src, + className, +}: { + readonly src: string; + readonly className?: string | undefined; +}) { + const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => + loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", + ); + return ( <> - {status !== "loaded" ? ( - - ) : null} + {status !== "loaded" ? : null} { loadedProjectFaviconSrcs.add(src); setStatus("loaded"); diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsx index 8681e128ab..4004b4930c 100644 --- a/apps/web/src/components/PullRequestThreadDialog.tsx +++ b/apps/web/src/components/PullRequestThreadDialog.tsx @@ -69,13 +69,6 @@ export function PullRequestThreadDialog({ const terminology = sourceControlPresentation.terminology; const SourceControlIcon = sourceControlPresentation.Icon; - useEffect(() => { - if (!open) return; - setReference(initialReference ?? ""); - setReferenceDirty(false); - setPreparingMode(null); - }, [initialReference, open]); - useEffect(() => { if (!open) return; const frame = window.requestAnimationFrame(() => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 4f1e28e7e4..5816d4b417 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -40,7 +40,6 @@ import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd- import { CSS } from "@dnd-kit/utilities"; import { type ContextMenuItem, - type DesktopUpdateState, ProjectId, type ScopedThreadRef, type ResolvedKeybindingsConfig, @@ -103,6 +102,7 @@ import { useShortcutModifierState } from "../shortcutModifierState"; import { readLocalApi } from "../localApi"; import { useComposerDraftStore } from "../composerDraftStore"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; +import { useDesktopUpdateState } from "../lib/desktopUpdateReactQuery"; import { useThreadActions } from "../hooks/useThreadActions"; import { projectEnvironment } from "../state/projects"; @@ -3045,7 +3045,7 @@ export default function Sidebar() { const dragInProgressRef = useRef(false); const suppressProjectClickAfterDragRef = useRef(false); const suppressProjectClickForContextMenuRef = useRef(false); - const [desktopUpdateState, setDesktopUpdateState] = useState(null); + const { data: desktopUpdateState = null } = useDesktopUpdateState(); const clearSelection = useThreadSelectionStore((s) => s.clearSelection); const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const platform = navigator.platform; @@ -3494,39 +3494,6 @@ export default function Sidebar() { }; }, [clearSelection]); - useEffect(() => { - if (!isElectron) return; - const bridge = window.desktopBridge; - if ( - !bridge || - typeof bridge.getUpdateState !== "function" || - typeof bridge.onUpdateState !== "function" - ) { - return; - } - - let disposed = false; - let receivedSubscriptionUpdate = false; - const unsubscribe = bridge.onUpdateState((nextState) => { - if (disposed) return; - receivedSubscriptionUpdate = true; - setDesktopUpdateState(nextState); - }); - - void bridge - .getUpdateState() - .then((nextState) => { - if (disposed || receivedSubscriptionUpdate) return; - setDesktopUpdateState(nextState); - }) - .catch(() => undefined); - - return () => { - disposed = true; - unsubscribe(); - }; - }, []); - const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState); const desktopUpdateButtonAction = desktopUpdateState ? resolveDesktopUpdateButtonAction(desktopUpdateState) diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index f1128406de..1641bb6b10 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -22,6 +22,7 @@ import { Terminal, type ITheme } from "@xterm/xterm"; import { type PointerEvent as ReactPointerEvent, type ReactNode, + type SetStateAction, useCallback, useEffect, useEffectEvent, @@ -892,10 +893,32 @@ export default function ThreadTerminalDrawer({ terminalLaunchLocationsById, }: ThreadTerminalDrawerProps) { const isPanel = mode === "panel"; - const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height)); + const controlledDrawerHeight = clampDrawerHeight(height); + const [drawerHeightState, setDrawerHeightState] = useState(() => ({ + threadId, + height: controlledDrawerHeight, + })); + const drawerHeight = + drawerHeightState.threadId === threadId ? drawerHeightState.height : controlledDrawerHeight; + const setDrawerHeight = useCallback( + (update: SetStateAction) => { + setDrawerHeightState((current) => { + const currentHeight = + current.threadId === threadId ? current.height : controlledDrawerHeight; + const nextHeight = typeof update === "function" ? update(currentHeight) : update; + return nextHeight === currentHeight && current.threadId === threadId + ? current + : { threadId, height: nextHeight }; + }); + }, + [controlledDrawerHeight, threadId], + ); + const setDrawerHeightFromWindowResize = useEffectEvent((nextHeight: number) => { + setDrawerHeight(nextHeight); + }); const [resizeEpoch, setResizeEpoch] = useState(0); const drawerHeightRef = useRef(drawerHeight); - const lastSyncedHeightRef = useRef(clampDrawerHeight(height)); + const lastSyncedHeightRef = useRef(controlledDrawerHeight); const onHeightChangeRef = useRef(onHeightChange); const resizeStateRef = useRef<{ pointerId: number; @@ -1082,11 +1105,8 @@ export default function ThreadTerminalDrawer({ }, []); useEffect(() => { - const clampedHeight = clampDrawerHeight(height); - setDrawerHeight(clampedHeight); - drawerHeightRef.current = clampedHeight; - lastSyncedHeightRef.current = clampedHeight; - }, [height, threadId]); + lastSyncedHeightRef.current = controlledDrawerHeight; + }, [controlledDrawerHeight, threadId]); const handleResizePointerDown = useCallback((event: ReactPointerEvent) => { if (event.button !== 0) return; @@ -1100,20 +1120,23 @@ export default function ThreadTerminalDrawer({ }; }, []); - const handleResizePointerMove = useCallback((event: ReactPointerEvent) => { - const resizeState = resizeStateRef.current; - if (!resizeState || resizeState.pointerId !== event.pointerId) return; - event.preventDefault(); - const clampedHeight = clampDrawerHeight( - resizeState.startHeight + (resizeState.startY - event.clientY), - ); - if (clampedHeight === drawerHeightRef.current) { - return; - } - didResizeDuringDragRef.current = true; - drawerHeightRef.current = clampedHeight; - setDrawerHeight(clampedHeight); - }, []); + const handleResizePointerMove = useCallback( + (event: ReactPointerEvent) => { + const resizeState = resizeStateRef.current; + if (!resizeState || resizeState.pointerId !== event.pointerId) return; + event.preventDefault(); + const clampedHeight = clampDrawerHeight( + resizeState.startHeight + (resizeState.startY - event.clientY), + ); + if (clampedHeight === drawerHeightRef.current) { + return; + } + didResizeDuringDragRef.current = true; + drawerHeightRef.current = clampedHeight; + setDrawerHeight(clampedHeight); + }, + [setDrawerHeight], + ); const handleResizePointerEnd = useCallback( (event: ReactPointerEvent) => { @@ -1141,7 +1164,7 @@ export default function ThreadTerminalDrawer({ const clampedHeight = clampDrawerHeight(drawerHeightRef.current); const changed = clampedHeight !== drawerHeightRef.current; if (changed) { - setDrawerHeight(clampedHeight); + setDrawerHeightFromWindowResize(clampedHeight); drawerHeightRef.current = clampedHeight; } if (!resizeStateRef.current) { diff --git a/apps/web/src/components/chat/ComposerBannerStack.tsx b/apps/web/src/components/chat/ComposerBannerStack.tsx index 9901237fdf..4a2a8f29df 100644 --- a/apps/web/src/components/chat/ComposerBannerStack.tsx +++ b/apps/web/src/components/chat/ComposerBannerStack.tsx @@ -40,14 +40,12 @@ interface ComposerBannerStackProps { } export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) { - const [exitingItemId, setExitingItemId] = useState(null); + const [requestedExitingItemId, setExitingItemId] = useState(null); const dismissTimeoutRef = useRef | null>(null); - - useEffect(() => { - if (exitingItemId && !items.some((item) => item.id === exitingItemId)) { - setExitingItemId(null); - } - }, [exitingItemId, items]); + const exitingItemId = + requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId) + ? requestedExitingItemId + : null; useEffect(() => { return () => { diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 10031b48cd..fd14c68b0c 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -9,24 +9,14 @@ interface ExpandedImageDialogProps { } export const ExpandedImageDialog = memo(function ExpandedImageDialog({ - preview: initialPreview, + preview, onClose, }: ExpandedImageDialogProps) { - const [preview, setPreview] = useState(initialPreview); - - // Sync when the parent hands us a new preview reference. - useEffect(() => { - setPreview(initialPreview); - }, [initialPreview]); + const [imageOffset, setImageOffset] = useState(0); + const index = (preview.index + imageOffset + preview.images.length) % preview.images.length; const navigateImage = useCallback((direction: -1 | 1) => { - setPreview((existing) => { - if (existing.images.length <= 1) return existing; - const nextIndex = - (existing.index + direction + existing.images.length) % existing.images.length; - if (nextIndex === existing.index) return existing; - return { ...existing, index: nextIndex }; - }); + setImageOffset((current) => current + direction); }, []); useEffect(() => { @@ -53,7 +43,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ return () => window.removeEventListener("keydown", onKeyDown); }, [navigateImage, onClose, preview.images.length]); - const item = preview.images[preview.index]; + const item = preview.images[index]; if (!item) return null; return ( @@ -100,7 +90,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ />

{item.name} - {preview.images.length > 1 ? ` (${preview.index + 1}/${preview.images.length})` : ""} + {preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}

{preview.images.length > 1 && ( diff --git a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx index 7a20badf02..a6ff9d8c4e 100644 --- a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx +++ b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx @@ -30,14 +30,7 @@ function getPromptErrorMessage(error: unknown): string { 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; @@ -50,14 +43,39 @@ export function SshPasswordPromptDialog() { }); }, []); - useEffect(() => { - setPassword(""); - setResponseError(null); - if (!currentRequest) { - return; - } + if (!currentRequest) { + return null; + } - setNow(Date.now()); + return ( + { + setQueue((currentQueue) => + currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue, + ); + }} + /> + ); +} + +function ActiveSshPasswordPrompt({ + request, + onRemove, +}: { + readonly request: DesktopSshPasswordPromptRequest; + readonly onRemove: (requestId: string) => void; +}) { + const [password, setPassword] = useState(""); + const [isResponding, setIsResponding] = useState(false); + const [now, setNow] = useState(() => Date.now()); + const [responseError, setResponseError] = useState(null); + const inputRef = useRef(null); + const isRespondingRef = useRef(false); + const formId = useId(); + + useEffect(() => { const frame = window.requestAnimationFrame(() => { inputRef.current?.focus(); inputRef.current?.select(); @@ -65,48 +83,33 @@ export function SshPasswordPromptDialog() { 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 expiresAtMs = Date.parse(request.expiresAt); 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 visibleResponseError = isExpired + ? "This SSH password prompt expired. Try connecting again." + : responseError; const respond = async (nextPassword: string | null) => { - if (!currentRequest || isRespondingRef.current) { + if (isRespondingRef.current) { return; } - const requestId = currentRequest.requestId; + const requestId = request.requestId; if (nextPassword !== null && isExpired) { setResponseError("This SSH password prompt expired. Try connecting again."); return; @@ -117,10 +120,10 @@ export function SshPasswordPromptDialog() { setResponseError(null); try { await window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword); - removeCurrentPrompt(requestId); + onRemove(requestId); } catch (error) { if (nextPassword === null) { - removeCurrentPrompt(requestId); + onRemove(requestId); } else { setResponseError(getPromptErrorMessage(error)); } @@ -131,9 +134,7 @@ export function SshPasswordPromptDialog() { }; const dismissExpiredPrompt = () => { - if (currentRequest) { - removeCurrentPrompt(currentRequest.requestId); - } + onRemove(request.requestId); }; const cancelPrompt = () => { @@ -144,11 +145,11 @@ export function SshPasswordPromptDialog() { void respond(null); }; - const target = currentRequest ? describeSshTarget(currentRequest) : null; + const target = describeSshTarget(request); return ( { if (!open) { cancelPrompt(); @@ -159,9 +160,8 @@ export function SshPasswordPromptDialog() { 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. + T3 needs your SSH password to connect to {target}. The password is passed + to the local SSH process for this connection attempt and is not saved by T3 Code. @@ -175,7 +175,7 @@ export function SshPasswordPromptDialog() { >
-

{currentRequest?.prompt}

+

{request.prompt}

{remainingLabel ? ( setPassword(event.target.value)} />
- {responseError ? ( -

{responseError}

+ {visibleResponseError ? ( +

{visibleResponseError}

) : (

Use SSH keys to avoid repeated password prompts on new SSH sessions. diff --git a/apps/web/src/components/preview/AgentBrowserCursor.tsx b/apps/web/src/components/preview/AgentBrowserCursor.tsx index 2f12300400..dcaab1e3aa 100644 --- a/apps/web/src/components/preview/AgentBrowserCursor.tsx +++ b/apps/web/src/components/preview/AgentBrowserCursor.tsx @@ -1,5 +1,6 @@ "use client"; +import type { DesktopPreviewPointerEvent } from "@t3tools/contracts"; import { MousePointer2 } from "lucide-react"; import { useEffect, useState } from "react"; @@ -16,17 +17,32 @@ export function AgentBrowserCursor(props: { }) { const { tabId, zoomFactor, controller } = props; const event = useBrowserPointerStore((state) => state.byTabId[tabId] ?? null); - const [active, setActive] = useState(false); - - useEffect(() => { - if (!event) return; - setActive(true); - const timeout = window.setTimeout(() => setActive(false), CURSOR_ACTIVE_MS); - return () => window.clearTimeout(timeout); - }, [event]); if (!event) return null; + return ( + + ); +} + +function AgentBrowserCursorEvent(props: { + readonly event: DesktopPreviewPointerEvent; + readonly zoomFactor: number; + readonly controller: BrowserController; +}) { + const { event, zoomFactor, controller } = props; + const [active, setActive] = useState(true); + + useEffect(() => { + const timeout = window.setTimeout(() => setActive(false), CURSOR_ACTIVE_MS); + return () => window.clearTimeout(timeout); + }, []); + return (

{ - setDraft((previous) => (document.activeElement === inputRef.current ? previous : url)); - }, [url]); - useEffect(() => { if (focusUrlNonce == null) return; const node = inputRef.current; @@ -171,7 +165,7 @@ export function PreviewChromeRow({ render={ inputRef.current?.select()); }} onBlur={() => { - setDraft(url); setInputFocused(false); }} onKeyDown={(event) => { diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index 0d02e92f98..59f069c9e2 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -2,7 +2,7 @@ import { CheckIcon } from "lucide-react"; import { Radio as RadioPrimitive } from "@base-ui/react/radio"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import { ProviderInstanceId, ProviderDriverKind, @@ -121,8 +121,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns const [driver, setDriver] = useState(DEFAULT_DRIVER_KIND); const [label, setLabel] = useState(""); const [accentColor, setAccentColor] = useState(""); - const [instanceId, setInstanceId] = useState(""); - const [instanceIdDirty, setInstanceIdDirty] = useState(false); + const [instanceIdOverride, setInstanceIdOverride] = useState(null); // Driver-specific config drafts keyed by driver so toggling between drivers // during the same dialog session does not lose in-progress input. const [configByDriver, setConfigByDriver] = useState>>({}); @@ -135,28 +134,8 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns [settings.providerInstances], ); - // Reset the form every time the dialog opens so each creation starts - // from a clean slate. - useEffect(() => { - if (!open) return; - setDriver(DEFAULT_DRIVER_KIND); - setLabel(""); - setAccentColor(""); - setInstanceId(""); - setWizardStep(0); - setInstanceIdDirty(false); - setConfigByDriver({}); - setHasAttemptedSubmit(false); - }, [open]); - - // Auto-derive the instance id from driver + label until the user types - // in the Instance ID field directly (after which they own its value). - useEffect(() => { - if (instanceIdDirty) return; - setInstanceId(deriveInstanceId(driver, label)); - }, [driver, label, instanceIdDirty]); - const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION; + const instanceId = instanceIdOverride ?? deriveInstanceId(driver, label); const driverSettingsFields = useMemo( () => deriveProviderSettingsFields(driverOption), [driverOption], @@ -379,8 +358,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns placeholder={`${driver}_work`} value={instanceId} onChange={(event) => { - setInstanceIdDirty(true); - setInstanceId(event.target.value); + setInstanceIdOverride(event.target.value); }} aria-invalid={showInstanceIdError} /> diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index f0e26d4958..96d9dd4510 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -126,6 +126,11 @@ import { connectSshEnvironment as connectSshEnvironmentAtom, } from "~/connection/onboarding"; import { useEnvironmentQuery } from "~/state/query"; +import { + desktopNetworkAccessStateAtom, + refreshDesktopNetworkAccessState, +} from "~/state/desktopNetworkAccess"; +import { desktopSshHostsStateAtom } from "~/state/desktopSshHosts"; import { type EnvironmentPresentation, useEnvironments, @@ -136,6 +141,8 @@ import { relayEnvironmentDiscovery } from "~/state/relay"; import { useAtomCommand } from "../../state/use-atom-command"; const DEFAULT_TAILSCALE_SERVE_PORT = 443; +const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray = []; +const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray = []; const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", @@ -480,45 +487,6 @@ function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerC }; } -function upsertDesktopPairingLink( - current: ReadonlyArray, - next: ServerPairingLinkRecord, -) { - const existingIndex = current.findIndex((pairingLink) => pairingLink.id === next.id); - if (existingIndex === -1) { - return sortDesktopPairingLinks([...current, next]); - } - const updated = [...current]; - updated[existingIndex] = next; - return sortDesktopPairingLinks(updated); -} - -function removeDesktopPairingLink(current: ReadonlyArray, id: string) { - return current.filter((pairingLink) => pairingLink.id !== id); -} - -function upsertDesktopClientSession( - current: ReadonlyArray, - next: ServerClientSessionRecord, -) { - const existingIndex = current.findIndex( - (clientSession) => clientSession.sessionId === next.sessionId, - ); - if (existingIndex === -1) { - return sortDesktopClientSessions([...current, next]); - } - const updated = [...current]; - updated[existingIndex] = next; - return sortDesktopClientSessions(updated); -} - -function removeDesktopClientSession( - current: ReadonlyArray, - sessionId: ServerClientSessionRecord["sessionId"], -) { - return current.filter((clientSession) => clientSession.sessionId !== sessionId); -} - function selectPairingEndpoint( endpoints: ReadonlyArray, defaultEndpointKey?: string | null, @@ -1982,30 +1950,15 @@ export function ConnectionsSettings() { } return keys; }, [savedEnvironments]); - const [discoveredSshHosts, setDiscoveredSshHosts] = useState< - ReadonlyArray - >([]); - const [hasLoadedDiscoveredSshHosts, setHasLoadedDiscoveredSshHosts] = useState(false); - const [isLoadingDiscoveredSshHosts, setIsLoadingDiscoveredSshHosts] = useState(false); - const [discoveredSshHostsError, setDiscoveredSshHostsError] = useState(null); + const [sshConnectionError, setSshConnectionError] = useState(null); const [connectingSshHostAlias, setConnectingSshHostAlias] = useState(null); - const [desktopServerExposureState, setDesktopServerExposureState] = - useState(null); - const [desktopAdvertisedEndpoints, setDesktopAdvertisedEndpoints] = useState< - ReadonlyArray - >([]); - const [desktopServerExposureError, setDesktopServerExposureError] = useState(null); - const [desktopPairingLinks, setDesktopPairingLinks] = useState< - ReadonlyArray - >([]); - const [desktopClientSessions, setDesktopClientSessions] = useState< - ReadonlyArray - >([]); - const [desktopAccessManagementError, setDesktopAccessManagementError] = useState( - null, - ); - const [isLoadingDesktopAccessManagement, setIsLoadingDesktopAccessManagement] = useState(false); + const [desktopServerExposureMutationError, setDesktopServerExposureMutationError] = useState< + string | null + >(null); + const [desktopAccessManagementMutationError, setDesktopAccessManagementMutationError] = useState< + string | null + >(null); const [revokingDesktopPairingLinkId, setRevokingDesktopPairingLinkId] = useState( null, ); @@ -2022,17 +1975,6 @@ export function ConnectionsSettings() { const [savedBackendSshPort, setSavedBackendSshPort] = useState(""); const [savedBackendError, setSavedBackendError] = useState(null); const [isAddingSavedBackend, setIsAddingSavedBackend] = useState(false); - const unsavedDiscoveredSshHosts = useMemo( - () => - discoveredSshHosts.filter((target) => { - const address = formatDesktopSshTarget(target); - return ( - !savedDesktopSshEnvironmentKeys.has(target.alias) && - !savedDesktopSshEnvironmentKeys.has(address) - ); - }), - [discoveredSshHosts, savedDesktopSshEnvironmentKeys], - ); const [removingSavedEnvironmentId, setRemovingSavedEnvironmentId] = useState(null); const [isUpdatingDesktopServerExposure, setIsUpdatingDesktopServerExposure] = useState(false); @@ -2066,6 +2008,57 @@ export function ConnectionsSettings() { }) : null, ); + const desktopNetworkAccess = useEnvironmentQuery( + canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null, + ); + const desktopSshHosts = useEnvironmentQuery( + desktopBridge && addBackendDialogOpen && savedBackendMode === "ssh" + ? desktopSshHostsStateAtom + : null, + ); + const discoveredSshHosts = desktopSshHosts.data ?? EMPTY_DISCOVERED_SSH_HOSTS; + const unsavedDiscoveredSshHosts = useMemo( + () => + discoveredSshHosts.filter((target) => { + const address = formatDesktopSshTarget(target); + return ( + !savedDesktopSshEnvironmentKeys.has(target.alias) && + !savedDesktopSshEnvironmentKeys.has(address) + ); + }), + [discoveredSshHosts, savedDesktopSshEnvironmentKeys], + ); + const hasLoadedDiscoveredSshHosts = + desktopSshHosts.data !== null || desktopSshHosts.error !== null; + const isLoadingDiscoveredSshHosts = desktopSshHosts.isPending; + const discoveredSshHostsError = sshConnectionError ?? desktopSshHosts.error; + const desktopServerExposureState = desktopNetworkAccess.data?.serverExposureState ?? null; + const desktopAdvertisedEndpoints = + desktopNetworkAccess.data?.advertisedEndpoints ?? EMPTY_ADVERTISED_ENDPOINTS; + const desktopServerExposureError = + desktopServerExposureMutationError ?? desktopNetworkAccess.error; + const desktopAccessManagementError = + desktopAccessManagementMutationError ?? authAccessChanges.error; + const isLoadingDesktopAccessManagement = + authAccessChanges.isPending && authAccessChanges.data === null; + const desktopPairingLinks = useMemo(() => { + const event = authAccessChanges.data; + if (event?.type !== "snapshot") return []; + return sortDesktopPairingLinks( + event.payload.pairingLinks.map((pairingLink: AuthPairingLink) => + toDesktopPairingLinkRecord(pairingLink), + ), + ); + }, [authAccessChanges.data]); + const desktopClientSessions = useMemo(() => { + const event = authAccessChanges.data; + if (event?.type !== "snapshot") return []; + return sortDesktopClientSessions( + event.payload.clientSessions.map((clientSession: AuthClientSession) => + toDesktopClientSessionRecord(clientSession), + ), + ); + }, [authAccessChanges.data]); const isLocalBackendNetworkAccessible = desktopBridge ? desktopServerExposureState?.mode === "network-accessible" : currentAuthPolicy === "remote-reachable"; @@ -2096,19 +2089,17 @@ export function ConnectionsSettings() { async (checked: boolean) => { if (!desktopBridge) return; setIsUpdatingDesktopServerExposure(true); - setDesktopServerExposureError(null); + setDesktopServerExposureMutationError(null); try { - const nextState = await desktopBridge.setServerExposureMode( - checked ? "network-accessible" : "local-only", - ); - setDesktopServerExposureState(nextState); + await desktopBridge.setServerExposureMode(checked ? "network-accessible" : "local-only"); + refreshDesktopNetworkAccessState(); setIsDesktopServerExposureDialogOpen(false); setIsUpdatingDesktopServerExposure(false); } catch (error) { const message = error instanceof Error ? error.message : "Failed to update network exposure."; setIsDesktopServerExposureDialogOpen(false); - setDesktopServerExposureError(message); + setDesktopServerExposureMutationError(message); toastManager.add( stackedThreadToast({ type: "error", @@ -2132,18 +2123,18 @@ export function ConnectionsSettings() { if (!desktopBridge) return; if (!isTailscaleServePortValid) return; setIsUpdatingTailscaleServe(true); - setDesktopServerExposureError(null); + setDesktopServerExposureMutationError(null); try { - const nextState = await desktopBridge.setTailscaleServeEnabled({ + await desktopBridge.setTailscaleServeEnabled({ enabled: true, port: parsedTailscaleServePort, }); - setDesktopServerExposureState(nextState); + refreshDesktopNetworkAccessState(); setPendingTailscaleServeEndpoint(null); } catch (error) { const message = error instanceof Error ? error.message : "Failed to configure Tailscale HTTPS."; - setDesktopServerExposureError(message); + setDesktopServerExposureMutationError(message); toastManager.add( stackedThreadToast({ type: "error", @@ -2169,17 +2160,17 @@ export function ConnectionsSettings() { const handleConfirmTailscaleServeDisable = useCallback(async () => { if (!desktopBridge) return; setIsUpdatingTailscaleServe(true); - setDesktopServerExposureError(null); + setDesktopServerExposureMutationError(null); try { - const nextState = await desktopBridge.setTailscaleServeEnabled({ + await desktopBridge.setTailscaleServeEnabled({ enabled: false, port: desktopServerExposureState?.tailscaleServePort ?? DEFAULT_TAILSCALE_SERVE_PORT, }); - setDesktopServerExposureState(nextState); + refreshDesktopNetworkAccessState(); setDisableTailscaleServeDialogOpen(false); } catch (error) { const message = error instanceof Error ? error.message : "Failed to disable Tailscale HTTPS."; - setDesktopServerExposureError(message); + setDesktopServerExposureMutationError(message); toastManager.add( stackedThreadToast({ type: "error", @@ -2198,12 +2189,12 @@ export function ConnectionsSettings() { const handleRevokeDesktopPairingLink = useCallback(async (id: string) => { setRevokingDesktopPairingLinkId(id); - setDesktopAccessManagementError(null); + setDesktopAccessManagementMutationError(null); try { await revokeServerPairingLink(id); } catch (error) { const message = error instanceof Error ? error.message : "Failed to revoke pairing link."; - setDesktopAccessManagementError(message); + setDesktopAccessManagementMutationError(message); toastManager.add( stackedThreadToast({ type: "error", @@ -2219,12 +2210,12 @@ export function ConnectionsSettings() { const handleRevokeDesktopClientSession = useCallback( async (sessionId: ServerClientSessionRecord["sessionId"]) => { setRevokingDesktopClientSessionId(sessionId); - setDesktopAccessManagementError(null); + setDesktopAccessManagementMutationError(null); try { await revokeServerClientSession(sessionId); } catch (error) { const message = error instanceof Error ? error.message : "Failed to revoke client access."; - setDesktopAccessManagementError(message); + setDesktopAccessManagementMutationError(message); toastManager.add( stackedThreadToast({ type: "error", @@ -2241,7 +2232,7 @@ export function ConnectionsSettings() { const handleRevokeOtherDesktopClients = useCallback(async () => { setIsRevokingOtherDesktopClients(true); - setDesktopAccessManagementError(null); + setDesktopAccessManagementMutationError(null); try { const revokedCount = await revokeOtherServerClientSessions(); toastManager.add({ @@ -2251,7 +2242,7 @@ export function ConnectionsSettings() { }); } catch (error) { const message = error instanceof Error ? error.message : "Failed to revoke other clients."; - setDesktopAccessManagementError(message); + setDesktopAccessManagementMutationError(message); toastManager.add( stackedThreadToast({ type: "error", @@ -2410,36 +2401,13 @@ export function ConnectionsSettings() { [removeEnvironment], ); - const loadDiscoveredSshHosts = useCallback(async () => { - if (!desktopBridge) { - setDiscoveredSshHosts([]); - setHasLoadedDiscoveredSshHosts(false); - setDiscoveredSshHostsError(null); - return; - } - - setIsLoadingDiscoveredSshHosts(true); - setDiscoveredSshHostsError(null); - try { - const hosts = await desktopBridge.discoverSshHosts(); - setDiscoveredSshHosts(hosts); - setHasLoadedDiscoveredSshHosts(true); - } catch (error) { - const message = error instanceof Error ? error.message : "Failed to discover SSH hosts."; - setDiscoveredSshHostsError(message); - setHasLoadedDiscoveredSshHosts(true); - } finally { - setIsLoadingDiscoveredSshHosts(false); - } - }, [desktopBridge]); - const handleConnectSshHost = useCallback( async (target: DesktopSshEnvironmentTarget, label?: string) => { setConnectingSshHostAlias(target.alias); if (savedBackendMode === "ssh") { setSavedBackendError(null); } else { - setDiscoveredSshHostsError(null); + setSshConnectionError(null); } const result = await connectSshEnvironment({ target, @@ -2466,143 +2434,13 @@ export function ConnectionsSettings() { if (savedBackendMode === "ssh") { setSavedBackendError(message); } else { - setDiscoveredSshHostsError(message); + setSshConnectionError(message); } } }, [connectSshEnvironment, savedBackendMode, savedDesktopSshEnvironmentsByAlias], ); - useEffect(() => { - if (!desktopBridge || !addBackendDialogOpen || savedBackendMode !== "ssh") { - return; - } - if (hasLoadedDiscoveredSshHosts || isLoadingDiscoveredSshHosts) { - return; - } - void loadDiscoveredSshHosts(); - }, [ - addBackendDialogOpen, - desktopBridge, - hasLoadedDiscoveredSshHosts, - isLoadingDiscoveredSshHosts, - loadDiscoveredSshHosts, - savedBackendMode, - ]); - - useEffect(() => { - if (!canManageLocalBackend) { - return; - } - if (authAccessChanges.error !== null) { - setDesktopAccessManagementError(authAccessChanges.error); - setIsLoadingDesktopAccessManagement(false); - return; - } - if (authAccessChanges.isPending) { - setIsLoadingDesktopAccessManagement(true); - } - const event = authAccessChanges.data; - if (event === null) { - return; - } - - switch (event.type) { - case "snapshot": - setDesktopPairingLinks( - sortDesktopPairingLinks( - event.payload.pairingLinks.map((pairingLink: AuthPairingLink) => - toDesktopPairingLinkRecord(pairingLink), - ), - ), - ); - setDesktopClientSessions( - sortDesktopClientSessions( - event.payload.clientSessions.map((clientSession: AuthClientSession) => - toDesktopClientSessionRecord(clientSession), - ), - ), - ); - break; - case "pairingLinkUpserted": - setDesktopPairingLinks((current) => - upsertDesktopPairingLink(current, toDesktopPairingLinkRecord(event.payload)), - ); - break; - case "pairingLinkRemoved": - setDesktopPairingLinks((current) => removeDesktopPairingLink(current, event.payload.id)); - break; - case "clientUpserted": - setDesktopClientSessions((current) => - upsertDesktopClientSession(current, toDesktopClientSessionRecord(event.payload)), - ); - break; - case "clientRemoved": - setDesktopClientSessions((current) => - removeDesktopClientSession(current, event.payload.sessionId), - ); - break; - } - - setDesktopAccessManagementError(null); - setIsLoadingDesktopAccessManagement(false); - }, [ - authAccessChanges.data, - authAccessChanges.error, - authAccessChanges.isPending, - canManageLocalBackend, - ]); - - useEffect(() => { - if (!canManageLocalBackend) return; - - let cancelled = false; - if (desktopBridge) { - void desktopBridge - .getServerExposureState() - .then((state) => { - if (cancelled) return; - setDesktopServerExposureState(state); - }) - .catch((error: unknown) => { - if (cancelled) return; - const message = - error instanceof Error ? error.message : "Failed to load network exposure state."; - setDesktopServerExposureError(message); - }); - void desktopBridge - .getAdvertisedEndpoints() - .then((endpoints) => { - if (cancelled) return; - setDesktopAdvertisedEndpoints(endpoints); - }) - .catch((error: unknown) => { - if (cancelled) return; - const message = - error instanceof Error ? error.message : "Failed to load reachable endpoints."; - setDesktopServerExposureError(message); - }); - } else { - setDesktopServerExposureState(null); - setDesktopAdvertisedEndpoints([]); - setDesktopServerExposureError(null); - } - - return () => { - cancelled = true; - }; - }, [canManageLocalBackend, desktopBridge]); - - useEffect(() => { - if (canManageLocalBackend) return; - setIsLoadingDesktopAccessManagement(false); - setDesktopPairingLinks([]); - setDesktopClientSessions([]); - setDesktopAccessManagementError(null); - setDesktopServerExposureState(null); - setDesktopAdvertisedEndpoints([]); - setDesktopServerExposureError(null); - }, [canManageLocalBackend]); const visibleDesktopPairingLinks = desktopPairingLinks; const tailscaleHttpsEndpoint = useMemo( () => desktopAdvertisedEndpoints.find(isTailscaleHttpsEndpoint) ?? null, @@ -2808,7 +2646,7 @@ export function ConnectionsSettings() { size="xs" variant="ghost" disabled={isLoadingDiscoveredSshHosts} - onClick={() => void loadDiscoveredSshHosts()} + onClick={desktopSshHosts.refresh} > {isLoadingDiscoveredSshHosts ? ( diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 823f8f968a..ac2f7be81e 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -12,7 +12,7 @@ import { } from "lucide-react"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { useEffect, useState, type ReactNode } from "react"; +import { useState, type ReactNode } from "react"; import { isProviderDriverKind, type ProviderInstanceConfig, @@ -161,10 +161,6 @@ function ProviderEnvironmentSection(props: { props.environment.map(makeEnvironmentDraftRow), ); - useEffect(() => { - setRows(props.environment.map(makeEnvironmentDraftRow)); - }, [props.environment]); - const publishRows = (nextRows: ReadonlyArray) => { const published: ProviderInstanceEnvironmentVariable[] = []; for (const row of nextRows) { diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 86a31bf8db..7bddcdfcf3 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -1361,10 +1361,9 @@ export function ProviderSettingsPanel() { })} - + {isAddInstanceDialogOpen ? ( + + ) : null} ); } diff --git a/apps/web/src/hooks/useCommitOnBlur.ts b/apps/web/src/hooks/useCommitOnBlur.ts index 43244762aa..d1154fbb26 100644 --- a/apps/web/src/hooks/useCommitOnBlur.ts +++ b/apps/web/src/hooks/useCommitOnBlur.ts @@ -1,4 +1,4 @@ -import { type ChangeEvent, type KeyboardEvent, useEffect, useRef, useState } from "react"; +import { type ChangeEvent, type KeyboardEvent, useState } from "react"; /** * Buffer text input locally so keystrokes don't cause a settings-wide @@ -16,27 +16,21 @@ import { type ChangeEvent, type KeyboardEvent, useEffect, useRef, useState } fro * */ export function useCommitOnBlur(value: string, onCommit: (next: string) => void) { - const [draft, setDraft] = useState(value); - const focusedRef = useRef(false); - - useEffect(() => { - if (!focusedRef.current) { - setDraft(value); - } - }, [value]); + const [draft, setDraft] = useState(null); return { - value: draft, + value: draft ?? value, onChange: (event: ChangeEvent) => { setDraft(event.target.value); }, onFocus: () => { - focusedRef.current = true; + setDraft(value); }, onBlur: () => { - focusedRef.current = false; - if (draft !== value) { - onCommit(draft); + const next = draft ?? value; + setDraft(null); + if (next !== value) { + onCommit(next); } }, onKeyDown: (event: KeyboardEvent) => { diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index b59d014670..0b802dd873 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -19,7 +19,7 @@ import { getProjectOrderKey, selectProjectGroupingSettings, } from "../logicalProject"; -import { readThreadShell, useProjects, useThreadDetail } from "../state/entities"; +import { readThreadShell, useProjects, useThread } from "../state/entities"; import { resolveThreadRouteTarget } from "../threadRoutes"; import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; import { useSettings } from "./useSettings"; @@ -164,7 +164,7 @@ export function useHandleNewThread() { select: (params) => resolveThreadRouteTarget(params), }); const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null; - const activeThread = useThreadDetail(routeThreadRef); + const activeThread = useThread(routeThreadRef); const getDraftThread = useComposerDraftStore((store) => store.getDraftThread); const activeDraftThread = useComposerDraftStore(() => routeTarget diff --git a/apps/web/src/hooks/useLocalStorage.ts b/apps/web/src/hooks/useLocalStorage.ts index 93d26f6632..50e81dbc0b 100644 --- a/apps/web/src/hooks/useLocalStorage.ts +++ b/apps/web/src/hooks/useLocalStorage.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; import * as Record from "effect/Record"; -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useMemo, useSyncExternalStore } from "react"; const isomorphicLocalStorage: Storage = typeof window !== "undefined" @@ -63,85 +63,69 @@ export function useLocalStorage( initialValue: T, schema: Schema.Codec, ): [T, (value: T | ((val: T) => T)) => void] { - // Get the initial value from localStorage or use the provided initialValue - const [storedValue, setStoredValue] = useState(() => { + const getSnapshot = useCallback(() => { try { - const item = getLocalStorageItem(key, schema); - return item ?? initialValue; + return isomorphicLocalStorage.getItem(key); + } catch (error) { + console.error("[LOCALSTORAGE] Error:", error); + return null; + } + }, [key]); + + const subscribe = useCallback( + (onStoreChange: () => void) => { + const handleStorageChange = (event: StorageEvent) => { + if (event.key === key) { + onStoreChange(); + } + }; + const handleLocalChange = (event: CustomEvent) => { + if (event.detail.key === key) { + onStoreChange(); + } + }; + + window.addEventListener("storage", handleStorageChange); + window.addEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener); + return () => { + window.removeEventListener("storage", handleStorageChange); + window.removeEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener); + }; + }, + [key], + ); + + const serializedValue = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); + const storedValue = useMemo(() => { + if (serializedValue === null) { + return initialValue; + } + try { + return decode(schema, serializedValue); } catch (error) { console.error("[LOCALSTORAGE] Error:", error); return initialValue; } - }); + }, [initialValue, schema, serializedValue]); - // Return a wrapped version of useState's setter function that persists the new value to localStorage const setValue = useCallback( (value: T | ((val: T) => T)) => { try { - setStoredValue((prev) => { - const valueToStore = typeof value === "function" ? (value as (val: T) => T)(prev) : value; - if (valueToStore === null) { - removeLocalStorageItem(key); - } else { - setLocalStorageItem(key, valueToStore, schema); - } - // Dispatch event after state update completes to avoid nested state updates - queueMicrotask(() => dispatchLocalStorageChange(key)); - return valueToStore; - }); + const currentValue = getLocalStorageItem(key, schema) ?? initialValue; + const valueToStore = + typeof value === "function" ? (value as (val: T) => T)(currentValue) : value; + if (valueToStore === null) { + removeLocalStorageItem(key); + } else { + setLocalStorageItem(key, valueToStore, schema); + } + dispatchLocalStorageChange(key); } catch (error) { console.error("[LOCALSTORAGE] Error:", error); } }, - [key, schema], + [initialValue, key, schema], ); - const prevKeyRef = useRef(key); - - // Re-sync from localStorage when key changes - useEffect(() => { - if (prevKeyRef.current !== key) { - prevKeyRef.current = key; - try { - const newValue = getLocalStorageItem(key, schema); - setStoredValue(newValue ?? initialValue); - } catch (error) { - console.error("[LOCALSTORAGE] Error:", error); - } - } - }, [key, initialValue, schema]); - - // Listen for storage events from other tabs AND custom events from the same tab - useEffect(() => { - const syncFromStorage = () => { - try { - const newValue = getLocalStorageItem(key, schema); - setStoredValue(newValue ?? initialValue); - } catch (error) { - console.error("[LOCALSTORAGE] Error:", error); - } - }; - - const handleStorageChange = (event: StorageEvent) => { - if (event.key === key) { - syncFromStorage(); - } - }; - - const handleLocalChange = (event: CustomEvent) => { - if (event.detail.key === key) { - syncFromStorage(); - } - }; - - window.addEventListener("storage", handleStorageChange); - window.addEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener); - - return () => { - window.removeEventListener("storage", handleStorageChange); - window.removeEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener); - }; - }, [key, initialValue, schema]); - return [storedValue, setValue]; } diff --git a/apps/web/src/hooks/useResizableWidth.ts b/apps/web/src/hooks/useResizableWidth.ts index 3552c82d9d..d3c7207c18 100644 --- a/apps/web/src/hooks/useResizableWidth.ts +++ b/apps/web/src/hooks/useResizableWidth.ts @@ -1,11 +1,5 @@ import * as Schema from "effect/Schema"; -import { - type PointerEvent as ReactPointerEvent, - useCallback, - useEffect, - useRef, - useState, -} from "react"; +import { type PointerEvent as ReactPointerEvent, useCallback, useRef, useState } from "react"; import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage"; @@ -66,10 +60,7 @@ export function useResizableWidth(options: UseResizableWidthOptions): { } }); - // Re-clamp if min/max change at runtime (e.g. window resize narrows max). - useEffect(() => { - setWidth((current) => clamp(current)); - }, [clamp]); + const clampedWidth = clamp(width); const dragStateRef = useRef<{ pointerId: number; @@ -114,13 +105,13 @@ export function useResizableWidth(options: UseResizableWidthOptions): { dragStateRef.current = { pointerId: event.pointerId, startX: event.clientX, - startWidth: width, - pending: width, + startWidth: clampedWidth, + pending: clampedWidth, rafId: null, target, }; }, - [width], + [clampedWidth], ); const onPointerMove = useCallback( @@ -170,7 +161,7 @@ export function useResizableWidth(options: UseResizableWidthOptions): { ); return { - width, + width: clampedWidth, handlers: { onPointerDown, onPointerMove, onPointerUp, onPointerCancel }, }; } diff --git a/apps/web/src/routes/_chat.draft.$draftId.tsx b/apps/web/src/routes/_chat.draft.$draftId.tsx index 630d202ff5..dd152ce1a9 100644 --- a/apps/web/src/routes/_chat.draft.$draftId.tsx +++ b/apps/web/src/routes/_chat.draft.$draftId.tsx @@ -9,7 +9,7 @@ import { } from "../composerDraftStore"; import { SidebarInset } from "../components/ui/sidebar"; import { buildThreadRouteParams } from "../threadRoutes"; -import { useThreadDetail, useThreadRefs } from "../state/entities"; +import { useThread, useThreadRefs } from "../state/entities"; function DraftChatThreadRouteView() { const navigate = useNavigate(); @@ -25,7 +25,7 @@ function DraftChatThreadRouteView() { ) ?? null) : null; const serverThreadRef = draftSession?.promotedTo ?? inferredThreadRef; - const serverThread = useThreadDetail(serverThreadRef); + const serverThread = useThread(serverThreadRef); const serverThreadStarted = threadHasStarted(serverThread); const canonicalThreadRef = serverThreadStarted ? serverThreadRef : null; diff --git a/apps/web/src/state/desktopNetworkAccess.test.ts b/apps/web/src/state/desktopNetworkAccess.test.ts new file mode 100644 index 0000000000..7af13cbbcf --- /dev/null +++ b/apps/web/src/state/desktopNetworkAccess.test.ts @@ -0,0 +1,50 @@ +import type { AdvertisedEndpoint, DesktopServerExposureState } from "@t3tools/contracts"; +import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"; +import { AtomRegistry } from "effect/unstable/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { createDesktopNetworkAccessStateAtom } from "./desktopNetworkAccess"; + +const serverExposureState: DesktopServerExposureState = { + advertisedHost: "192.168.1.10", + endpointUrl: "http://192.168.1.10:37737", + mode: "network-accessible", + tailscaleServeEnabled: false, + tailscaleServePort: 443, +}; + +const advertisedEndpoints: ReadonlyArray = []; + +describe("desktopNetworkAccessState", () => { + it("retains the loaded snapshot when the settings screen remounts", async () => { + const getServerExposureState = vi.fn(async () => serverExposureState); + const getAdvertisedEndpoints = vi.fn(async () => advertisedEndpoints); + const atom = createDesktopNetworkAccessStateAtom(() => ({ + getAdvertisedEndpoints, + getServerExposureState, + })); + const registry = AtomRegistry.make(); + + const unmount = registry.mount(atom); + await vi.waitFor(() => { + expect(AsyncResult.value(registry.get(atom))).toEqual( + expect.objectContaining({ _tag: "Some" }), + ); + }); + unmount(); + + const remount = registry.mount(atom); + const result = registry.get(atom); + expect(AsyncResult.value(result)).toEqual( + expect.objectContaining({ + _tag: "Some", + value: { advertisedEndpoints, serverExposureState }, + }), + ); + expect(getServerExposureState).toHaveBeenCalledTimes(1); + expect(getAdvertisedEndpoints).toHaveBeenCalledTimes(1); + + remount(); + registry.dispose(); + }); +}); diff --git a/apps/web/src/state/desktopNetworkAccess.ts b/apps/web/src/state/desktopNetworkAccess.ts new file mode 100644 index 0000000000..150a256bc6 --- /dev/null +++ b/apps/web/src/state/desktopNetworkAccess.ts @@ -0,0 +1,79 @@ +import type { + AdvertisedEndpoint, + DesktopBridge, + DesktopServerExposureState, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { Atom } from "effect/unstable/reactivity"; + +import { appAtomRegistry } from "~/rpc/atomRegistry"; + +const DESKTOP_NETWORK_ACCESS_STALE_TIME_MS = 30_000; + +type DesktopNetworkAccessBridge = Pick< + DesktopBridge, + "getAdvertisedEndpoints" | "getServerExposureState" +>; + +export interface DesktopNetworkAccessSnapshot { + readonly advertisedEndpoints: ReadonlyArray; + readonly serverExposureState: DesktopServerExposureState; +} + +class DesktopNetworkAccessError extends Schema.TaggedErrorClass()( + "DesktopNetworkAccessError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +function getDesktopNetworkAccessBridge(): DesktopNetworkAccessBridge | undefined { + return typeof window === "undefined" ? undefined : window.desktopBridge; +} + +export function createDesktopNetworkAccessStateAtom( + getBridge: () => DesktopNetworkAccessBridge | undefined, +) { + const loadDesktopNetworkAccess = Effect.fn("loadDesktopNetworkAccess")(function* () { + const bridge = getBridge(); + if (!bridge) { + return yield* new DesktopNetworkAccessError({ + message: "Desktop network access is unavailable.", + }); + } + return yield* Effect.tryPromise({ + try: async (): Promise => { + const [serverExposureState, advertisedEndpoints] = await Promise.all([ + bridge.getServerExposureState(), + bridge.getAdvertisedEndpoints(), + ]); + return { advertisedEndpoints, serverExposureState }; + }, + catch: (cause) => + new DesktopNetworkAccessError({ + message: + cause instanceof Error ? cause.message : "Failed to load desktop network access.", + cause, + }), + }); + }); + + return Atom.make(loadDesktopNetworkAccess()).pipe( + Atom.swr({ + staleTime: DESKTOP_NETWORK_ACCESS_STALE_TIME_MS, + revalidateOnMount: true, + }), + Atom.keepAlive, + Atom.withLabel("desktop:network-access"), + ); +} + +export const desktopNetworkAccessStateAtom = createDesktopNetworkAccessStateAtom( + getDesktopNetworkAccessBridge, +); + +export function refreshDesktopNetworkAccessState(): void { + appAtomRegistry.refresh(desktopNetworkAccessStateAtom); +} diff --git a/apps/web/src/state/desktopSshHosts.test.ts b/apps/web/src/state/desktopSshHosts.test.ts new file mode 100644 index 0000000000..571704a95f --- /dev/null +++ b/apps/web/src/state/desktopSshHosts.test.ts @@ -0,0 +1,41 @@ +import type { DesktopDiscoveredSshHost } from "@t3tools/contracts"; +import { AtomRegistry } from "effect/unstable/reactivity"; +import * as AsyncResult from "effect/unstable/reactivity/AsyncResult"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { createDesktopSshHostsStateAtom } from "./desktopSshHosts"; + +const hosts: ReadonlyArray = [ + { + alias: "devbox", + hostname: "devbox.local", + port: null, + source: "ssh-config", + username: null, + }, +]; + +describe("desktopSshHostsState", () => { + it("retains discovered hosts when the settings screen remounts", async () => { + const discoverSshHosts = vi.fn(async () => hosts); + const atom = createDesktopSshHostsStateAtom(() => ({ discoverSshHosts })); + const registry = AtomRegistry.make(); + + const unmount = registry.mount(atom); + await vi.waitFor(() => { + expect(AsyncResult.value(registry.get(atom))).toEqual( + expect.objectContaining({ _tag: "Some", value: hosts }), + ); + }); + unmount(); + + const remount = registry.mount(atom); + expect(AsyncResult.value(registry.get(atom))).toEqual( + expect.objectContaining({ _tag: "Some", value: hosts }), + ); + expect(discoverSshHosts).toHaveBeenCalledTimes(1); + + remount(); + registry.dispose(); + }); +}); diff --git a/apps/web/src/state/desktopSshHosts.ts b/apps/web/src/state/desktopSshHosts.ts new file mode 100644 index 0000000000..47b2c87e97 --- /dev/null +++ b/apps/web/src/state/desktopSshHosts.ts @@ -0,0 +1,49 @@ +import type { DesktopBridge, DesktopDiscoveredSshHost } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { Atom } from "effect/unstable/reactivity"; + +type DesktopSshDiscoveryBridge = Pick; + +class DesktopSshDiscoveryError extends Schema.TaggedErrorClass()( + "DesktopSshDiscoveryError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + +function getDesktopSshDiscoveryBridge(): DesktopSshDiscoveryBridge | undefined { + return typeof window === "undefined" ? undefined : window.desktopBridge; +} + +export function createDesktopSshHostsStateAtom( + getBridge: () => DesktopSshDiscoveryBridge | undefined, +) { + const discoverDesktopSshHosts = Effect.fn("discoverDesktopSshHosts")(function* () { + const bridge = getBridge(); + if (!bridge) { + return yield* new DesktopSshDiscoveryError({ + message: "Desktop SSH host discovery is unavailable.", + }); + } + return yield* Effect.tryPromise({ + try: (): Promise> => bridge.discoverSshHosts(), + catch: (cause) => + new DesktopSshDiscoveryError({ + message: cause instanceof Error ? cause.message : "Failed to discover SSH hosts.", + cause, + }), + }); + }); + + return Atom.make(discoverDesktopSshHosts()).pipe( + Atom.swr({ staleTime: 30_000, revalidateOnMount: true }), + Atom.keepAlive, + Atom.withLabel("desktop:ssh-hosts"), + ); +} + +export const desktopSshHostsStateAtom = createDesktopSshHostsStateAtom( + getDesktopSshDiscoveryBridge, +); diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 2d99ad8438..2d827e36b3 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -4,6 +4,7 @@ import type { EnvironmentThread, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; +import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads"; import type { OrchestrationMessage, OrchestrationProposedPlan, @@ -14,6 +15,7 @@ import type { } from "@t3tools/contracts"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; +import { useMemo } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentProjects } from "./projects"; import { environmentThreadDetails, environmentThreadShells } from "./threads"; @@ -127,6 +129,13 @@ export function useThreadDetail(ref: ScopedThreadRef | null): EnvironmentThread ); } +/** Detail collections composed with shell-authoritative thread/workspace metadata. */ +export function useThread(ref: ScopedThreadRef | null): EnvironmentThread | null { + const shell = useThreadShell(ref); + const detail = useThreadDetail(ref); + return useMemo(() => mergeEnvironmentThread(detail, shell), [detail, shell]); +} + export function useThreadMessages( ref: ScopedThreadRef | null, ): ReadonlyArray { diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 26984c8297..9e480df08b 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -2,6 +2,7 @@ import { combineTerminalSessionState, EMPTY_TERMINAL_BUFFER_STATE, EMPTY_TERMINAL_SESSION_STATE, + selectRunningSubprocessTerminalIds, type KnownTerminalSession, type TerminalSessionState, } from "@t3tools/client-runtime/state/terminal"; @@ -85,7 +86,5 @@ export function useThreadRunningTerminalIds(input: { readonly environmentId: EnvironmentId | null; readonly threadId: ThreadId | null; }): ReadonlyArray { - return useKnownTerminalSessions(input) - .filter((session) => session.state.status === "running") - .map((session) => session.target.terminalId); + return selectRunningSubprocessTerminalIds(useKnownTerminalSessions(input)); } diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.ts index a04c7253f9..2bdb8f8425 100644 --- a/packages/client-runtime/src/state/entities.test.ts +++ b/packages/client-runtime/src/state/entities.test.ts @@ -16,6 +16,7 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./t import { createEnvironmentProjectAtoms } from "./projectEntities.ts"; import { createEnvironmentSnapshotAtom } from "./snapshots.ts"; import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts"; +import { mergeEnvironmentThread } from "./threadDetail.ts"; import { createEnvironmentThreadShellAtoms } from "./threadShell.ts"; const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); @@ -136,6 +137,38 @@ function makeHarness() { } describe("environment entity projections", () => { + it("composes detail collections with authoritative shell workspace metadata", () => { + const messages: OrchestrationThread["messages"] = []; + const detail = { + ...THREAD_SHELL, + environmentId: ENVIRONMENT_ID, + title: "Cached thread", + branch: "stale-branch", + worktreePath: "/repo/stale-worktree", + deletedAt: null, + messages, + proposedPlans: [], + activities: [], + checkpoints: [], + } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId }; + const shell = { + ...THREAD_SHELL, + environmentId: ENVIRONMENT_ID, + title: "Current thread", + branch: "current-branch", + worktreePath: "/repo/current-worktree", + }; + + const merged = mergeEnvironmentThread(detail, shell); + + expect(merged).toMatchObject({ + title: "Current thread", + branch: "current-branch", + worktreePath: "/repo/current-worktree", + }); + expect(merged?.messages).toBe(messages); + }); + it("preserves untouched project and thread identities across unrelated shell updates", () => { const harness = makeHarness(); const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID); diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 1efcf642d1..7584e55d52 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -359,8 +359,8 @@ describe("runtime command runner", () => { secondLatch.openUnsafe(); firstLatch.openUnsafe(); - expect(await first).toEqual(AsyncResult.success("first")); - expect(await second).toEqual(AsyncResult.success("second")); + expect(await first).toMatchObject({ _tag: "Success", value: "first", waiting: false }); + expect(await second).toMatchObject({ _tag: "Success", value: "second", waiting: false }); registry.dispose(); }); @@ -415,8 +415,8 @@ describe("runtime command runner", () => { const second = command.run(registry, "same"); latch.openUnsafe(); - expect(await first).toEqual(AsyncResult.success("done")); - expect(await second).toEqual(AsyncResult.success("done")); + expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false }); + expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false }); expect(executions).toBe(1); registry.dispose(); }); @@ -442,9 +442,9 @@ describe("runtime command runner", () => { const third = command.run(registry, 3); firstLatch.openUnsafe(); - expect(await first).toEqual(AsyncResult.success(1)); - expect(await second).toEqual(AsyncResult.success(3)); - expect(await third).toEqual(AsyncResult.success(3)); + expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false }); + expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false }); + expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false }); expect(executed).toEqual([1, 3]); registry.dispose(); }); diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index cf5634b087..85c57592d1 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -7,6 +7,7 @@ import { applyTerminalMetadataStreamEvent, combineTerminalSessionState, EMPTY_TERMINAL_BUFFER_STATE, + selectRunningSubprocessTerminalIds, } from "./terminalSession.ts"; const TARGET = { @@ -88,6 +89,26 @@ describe("terminal session reducers", () => { ); }); + it("does not treat an idle running shell as a running subprocess", () => { + const idleSession = { + target: TARGET, + state: { + ...combineTerminalSessionState(null, EMPTY_TERMINAL_BUFFER_STATE), + status: "running" as const, + hasRunningSubprocess: false, + }, + }; + const activeSession = { + target: { ...TARGET, terminalId: "term-2" }, + state: { + ...idleSession.state, + hasRunningSubprocess: true, + }, + }; + + expect(selectRunningSubprocessTerminalIds([idleSession, activeSession])).toEqual(["term-2"]); + }); + it("reduces attach snapshots and output without an imperative session manager", () => { const snapshot = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { type: "snapshot", diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index 905cdd27d1..ee444e36db 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -36,6 +36,14 @@ export interface KnownTerminalSession { readonly state: TerminalSessionState; } +export function selectRunningSubprocessTerminalIds( + sessions: ReadonlyArray, +): ReadonlyArray { + return sessions + .filter((session) => session.state.hasRunningSubprocess) + .map((session) => session.target.terminalId); +} + export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({ buffer: "", status: "closed", diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index f96f67efe0..20caf4a05a 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -11,7 +11,7 @@ import type { import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; -import type { EnvironmentThread } from "./models.ts"; +import type { EnvironmentThread, EnvironmentThreadShell } from "./models.ts"; import { scopeThread } from "./models.ts"; import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; @@ -22,6 +22,45 @@ const EMPTY_PROPOSED_PLANS: ReadonlyArray = Object.fr const EMPTY_CHECKPOINTS: ReadonlyArray = Object.freeze([]); const THREAD_DETAIL_IDLE_TTL_MS = 5 * 60_000; +/** + * Combine detail-only collections with the shell's authoritative thread metadata. + * + * Shell and detail subscriptions are intentionally independent. A cached detail can + * therefore briefly outlive a newer shell snapshot after reconnecting. Workspace + * consumers must use the shell branch/worktree/project fields so they do not target + * a stale checkout while retaining messages, activities, plans, and checkpoints + * from the detail subscription. + */ +export function mergeEnvironmentThread( + detail: EnvironmentThread | null, + shell: EnvironmentThreadShell | null, +): EnvironmentThread | null { + if (detail === null || shell === null) { + return detail; + } + if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) { + return detail; + } + + return { + ...detail, + environmentId: shell.environmentId, + id: shell.id, + projectId: shell.projectId, + title: shell.title, + modelSelection: shell.modelSelection, + runtimeMode: shell.runtimeMode, + interactionMode: shell.interactionMode, + branch: shell.branch, + worktreePath: shell.worktreePath, + latestTurn: shell.latestTurn, + createdAt: shell.createdAt, + updatedAt: shell.updatedAt, + archivedAt: shell.archivedAt, + session: shell.session, + }; +} + export function createEnvironmentThreadDetailAtoms( threadStateAtom: ( environmentId: ScopedThreadRef["environmentId"],