Restore client behavior and stabilize async UI state

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-18 00:17:04 -07:00
1 parent c09f491b37
commit 344fca1edc
37 files changed
+970 -839

No files matched your search

@@ -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<EnvironmentId | null>(
projects[0]?.environmentId ?? null,
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const selectedEnvironmentId =
selectedEnvironmentIdOverride !== null &&
projects.some((project) => project.environmentId === selectedEnvironmentIdOverride)
? selectedEnvironmentIdOverride
: (projects[0]?.environmentId ?? null);
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
@@ -170,11 +175,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const [expandedProvider, setExpandedProvider] = useState<string | null>(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 <NewTaskFlowContext.Provider value={value}>{props.children}</NewTaskFlowContext.Provider>;
}
+13 -18
View File
@@ -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<ResultListener>();
let currentResult: GitActionResultNotification | null = null;
const gitActionResultAtom = Atom.make<GitActionResultNotification | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:git-action-result"),
);
let dismissTimer: ReturnType<typeof setTimeout> | 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<GitActionResultNotification | null>(currentResult);
useEffect(() => {
resultListeners.add(setResult);
setResult(currentResult);
return () => {
resultListeners.delete(setResult);
};
}, []);
const result = useAtomValue(gitActionResultAtom);
return { result, dismiss: dismissGitActionResult };
}
+2 -2
View File
@@ -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),
);
@@ -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;
+43 -32
View File
@@ -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<LocalDispatchSnapshot | null>(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 && (
<ExpandedImageDialog preview={expandedImage} onClose={closeExpandedImage} />
<ExpandedImageDialog
key={`${expandedImage.images[expandedImage.index]?.src ?? "image"}:${expandedImage.index}`}
preview={expandedImage}
onClose={closeExpandedImage}
/>
)}
</div>
);
+11 -30
View File
@@ -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: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
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,
+191 -109
View File
@@ -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<string>;
}
const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = 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<DiffRenderMode>("stacked");
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
const [collapsedDiffFileKeys, setCollapsedDiffFileKeys] = useState<ReadonlySet<string>>(
() => new Set(),
);
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
scopeKey: null,
fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
}));
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(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
</div>
</button>
{orderedTurnDiffSummaries.map((summary) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
<Tooltip key={summary.turnId}>
<TooltipTrigger
render={
<button
type="button"
aria-label={summary.turnId}
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
/>
}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn{" "}
{summary.checkpointTurnCount ??
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
"?"}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn{" "}
{summary.checkpointTurnCount ??
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
"?"}
</span>
<span className="text-[9px] leading-tight opacity-70 tabular-nums">
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
</span>
</div>
</div>
</div>
</button>
</TooltipTrigger>
<TooltipPopup side="top">{summary.turnId}</TooltipPopup>
</Tooltip>
))}
</div>
</div>
@@ -534,30 +586,50 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
<Columns2Icon className="size-3" />
</Toggle>
</ToggleGroup>
<Toggle
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
>
<TextWrapIcon className="size-3" />
</Toggle>
<Toggle
aria-label={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
title={diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
variant="outline"
size="xs"
pressed={diffIgnoreWhitespace}
onPressedChange={(pressed) => {
setDiffIgnoreWhitespace(Boolean(pressed));
}}
>
<PilcrowIcon className="size-3" />
</Toggle>
<Tooltip>
<TooltipTrigger
render={
<Toggle
aria-label={
diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"
}
variant="outline"
size="xs"
pressed={diffWordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
}}
/>
}
>
<TextWrapIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<Toggle
aria-label={
diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"
}
variant="outline"
size="xs"
pressed={diffIgnoreWhitespace}
onPressedChange={(pressed) => {
setDiffIgnoreWhitespace(Boolean(pressed));
}}
/>
}
>
<PilcrowIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{diffIgnoreWhitespace ? "Show whitespace changes" : "Hide whitespace changes"}
</TooltipPopup>
</Tooltip>
</div>
</>
);
@@ -635,26 +707,36 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
sectionTitle={reviewSectionTitle}
composerDraftTarget={composerDraftTarget}
renderHeaderPrefix={() => (
<button
type="button"
className={cn(
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
getDiffCollapseIconClassName(fileDiff),
)}
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
aria-expanded={!collapsed}
title={collapsed ? "Expand diff" : "Collapse diff"}
onClick={(event) => {
event.stopPropagation();
toggleDiffFileCollapsed(fileKey);
}}
>
{collapsed ? (
<ChevronRightIcon className="size-4" />
) : (
<ChevronDownIcon className="size-4" />
)}
</button>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className={cn(
"inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden",
getDiffCollapseIconClassName(fileDiff),
)}
aria-label={
collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`
}
aria-expanded={!collapsed}
onClick={(event) => {
event.stopPropagation();
toggleDiffFileCollapsed(fileKey);
}}
/>
}
>
{collapsed ? (
<ChevronRightIcon className="size-4" />
) : (
<ChevronDownIcon className="size-4" />
)}
</TooltipTrigger>
<TooltipPopup side="top">
{collapsed ? "Expand diff" : "Collapse diff"}
</TooltipPopup>
</Tooltip>
)}
options={{
collapsed,
+41 -35
View File
@@ -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<unknown>;
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<PublishProviderKind>("github");
const [publishRepository, setPublishRepository] = useState("");
const [selectedPublishProvider, setSelectedPublishProvider] =
useState<PublishProviderKind | null>(null);
const [publishRepositoryOverride, setPublishRepositoryOverride] = useState<string | null>(null);
const [publishVisibility, setPublishVisibility] =
useState<SourceControlRepositoryVisibility>("private");
const [publishRemoteName, setPublishRemoteName] = useState("origin");
@@ -375,7 +392,6 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
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) {
</span>
<RadioGroup
value={publishProvider}
onValueChange={(value) => 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({
<Menu
onOpenChange={(open) => {
if (open) {
gitStatusQuery.refresh();
requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
}
}}
>
+23 -19
View File
@@ -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<string>();
@@ -8,38 +8,42 @@ const loadedProjectFaviconSrcs = new Set<string>();
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 (
<FolderIcon
className={`size-3.5 shrink-0 text-muted-foreground/50 ${input.className ?? ""}`}
/>
);
return <ProjectFaviconFallback className={input.className} />;
}
return <ProjectFaviconImage key={src} src={src} className={input.className} />;
}
function ProjectFaviconFallback({ className }: { readonly className?: string | undefined }) {
return <FolderIcon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />;
}
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" ? (
<FolderIcon
className={`size-3.5 shrink-0 text-muted-foreground/50 ${input.className ?? ""}`}
/>
) : null}
{status !== "loaded" ? <ProjectFaviconFallback className={className} /> : null}
<img
src={src}
alt=""
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${input.className ?? ""}`}
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${className ?? ""}`}
onLoad={() => {
loadedProjectFaviconSrcs.add(src);
setStatus("loaded");
@@ -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(() => {
+2 -35
View File
@@ -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<DesktopUpdateState | null>(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)
@@ -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<number>) => {
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<HTMLDivElement>) => {
if (event.button !== 0) return;
@@ -1100,20 +1120,23 @@ export default function ThreadTerminalDrawer({
};
}, []);
const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
@@ -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) {
@@ -40,14 +40,12 @@ interface ComposerBannerStackProps {
}
export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) {
const [exitingItemId, setExitingItemId] = useState<string | null>(null);
const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | 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 () => {
@@ -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({
/>
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
{item.name}
{preview.images.length > 1 ? ` (${preview.index + 1}/${preview.images.length})` : ""}
{preview.images.length > 1 ? ` (${index + 1}/${preview.images.length})` : ""}
</p>
</div>
{preview.images.length > 1 && (
@@ -30,14 +30,7 @@ function getPromptErrorMessage(error: unknown): string {
export function SshPasswordPromptDialog() {
const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
const [password, setPassword] = useState("");
const [isResponding, setIsResponding] = useState(false);
const [now, setNow] = useState(() => Date.now());
const [responseError, setResponseError] = useState<string | null>(null);
const currentRequest = queue[0] ?? null;
const inputRef = useRef<HTMLInputElement | null>(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 (
<ActiveSshPasswordPrompt
key={currentRequest.requestId}
request={currentRequest}
onRemove={(requestId) => {
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<string | null>(null);
const inputRef = useRef<HTMLInputElement | null>(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 (
<Dialog
open={currentRequest !== null}
open
onOpenChange={(open) => {
if (!open) {
cancelPrompt();
@@ -159,9 +160,8 @@ export function SshPasswordPromptDialog() {
<DialogHeader>
<DialogTitle>SSH Password Required</DialogTitle>
<DialogDescription>
T3 needs your SSH password to connect to{" "}
{target ? <code>{target}</code> : "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 <code>{target}</code>. The password is passed
to the local SSH process for this connection attempt and is not saved by T3 Code.
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-3" scrollFade={false}>
@@ -175,7 +175,7 @@ export function SshPasswordPromptDialog() {
>
<div className="space-y-2">
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium text-foreground">{currentRequest?.prompt}</p>
<p className="text-sm font-medium text-foreground">{request.prompt}</p>
{remainingLabel ? (
<span
className={
@@ -198,8 +198,8 @@ export function SshPasswordPromptDialog() {
onChange={(event) => setPassword(event.target.value)}
/>
</div>
{responseError ? (
<p className="text-sm text-destructive">{responseError}</p>
{visibleResponseError ? (
<p className="text-sm text-destructive">{visibleResponseError}</p>
) : (
<p className="text-sm text-muted-foreground">
Use SSH keys to avoid repeated password prompts on new SSH sessions.
@@ -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 (
<AgentBrowserCursorEvent
key={event.sequence}
event={event}
zoomFactor={zoomFactor}
controller={controller}
/>
);
}
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 (
<div
className="pointer-events-none absolute left-0 top-0 z-40 transition-[transform,opacity] duration-150 ease-out motion-reduce:transition-none"
@@ -87,12 +87,6 @@ export function PreviewChromeRow({
const [draft, setDraft] = useState(url);
const [inputFocused, setInputFocused] = useState(false);
// Sync the input with external URL changes, but only when the user isn't
// actively typing (preserves in-progress edits during navigation events).
useEffect(() => {
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={
<InputGroupInput
ref={inputRef}
value={inputFocused ? draft : (displayUrl ?? draft)}
value={inputFocused ? draft : (displayUrl ?? url)}
className={cn(
onOpenInBrowser &&
!inputFocused &&
@@ -184,7 +178,6 @@ export function PreviewChromeRow({
queueMicrotask(() => inputRef.current?.select());
}}
onBlur={() => {
setDraft(url);
setInputFocused(false);
}}
onKeyDown={(event) => {
@@ -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<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
const [label, setLabel] = useState("");
const [accentColor, setAccentColor] = useState<string>("");
const [instanceId, setInstanceId] = useState("");
const [instanceIdDirty, setInstanceIdDirty] = useState(false);
const [instanceIdOverride, setInstanceIdOverride] = useState<string | null>(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<Record<string, Record<string, unknown>>>({});
@@ -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}
/>
@@ -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<AdvertisedEndpoint> = [];
const EMPTY_DISCOVERED_SSH_HOSTS: ReadonlyArray<DesktopDiscoveredSshHost> = [];
const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
@@ -480,45 +487,6 @@ function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerC
};
}
function upsertDesktopPairingLink(
current: ReadonlyArray<ServerPairingLinkRecord>,
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<ServerPairingLinkRecord>, id: string) {
return current.filter((pairingLink) => pairingLink.id !== id);
}
function upsertDesktopClientSession(
current: ReadonlyArray<ServerClientSessionRecord>,
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<ServerClientSessionRecord>,
sessionId: ServerClientSessionRecord["sessionId"],
) {
return current.filter((clientSession) => clientSession.sessionId !== sessionId);
}
function selectPairingEndpoint(
endpoints: ReadonlyArray<AdvertisedEndpoint>,
defaultEndpointKey?: string | null,
@@ -1982,30 +1950,15 @@ export function ConnectionsSettings() {
}
return keys;
}, [savedEnvironments]);
const [discoveredSshHosts, setDiscoveredSshHosts] = useState<
ReadonlyArray<DesktopDiscoveredSshHost>
>([]);
const [hasLoadedDiscoveredSshHosts, setHasLoadedDiscoveredSshHosts] = useState(false);
const [isLoadingDiscoveredSshHosts, setIsLoadingDiscoveredSshHosts] = useState(false);
const [discoveredSshHostsError, setDiscoveredSshHostsError] = useState<string | null>(null);
const [sshConnectionError, setSshConnectionError] = useState<string | null>(null);
const [connectingSshHostAlias, setConnectingSshHostAlias] = useState<string | null>(null);
const [desktopServerExposureState, setDesktopServerExposureState] =
useState<DesktopServerExposureState | null>(null);
const [desktopAdvertisedEndpoints, setDesktopAdvertisedEndpoints] = useState<
ReadonlyArray<AdvertisedEndpoint>
>([]);
const [desktopServerExposureError, setDesktopServerExposureError] = useState<string | null>(null);
const [desktopPairingLinks, setDesktopPairingLinks] = useState<
ReadonlyArray<ServerPairingLinkRecord>
>([]);
const [desktopClientSessions, setDesktopClientSessions] = useState<
ReadonlyArray<ServerClientSessionRecord>
>([]);
const [desktopAccessManagementError, setDesktopAccessManagementError] = useState<string | null>(
null,
);
const [isLoadingDesktopAccessManagement, setIsLoadingDesktopAccessManagement] = useState(false);
const [desktopServerExposureMutationError, setDesktopServerExposureMutationError] = useState<
string | null
>(null);
const [desktopAccessManagementMutationError, setDesktopAccessManagementMutationError] = useState<
string | null
>(null);
const [revokingDesktopPairingLinkId, setRevokingDesktopPairingLinkId] = useState<string | null>(
null,
);
@@ -2022,17 +1975,6 @@ export function ConnectionsSettings() {
const [savedBackendSshPort, setSavedBackendSshPort] = useState("");
const [savedBackendError, setSavedBackendError] = useState<string | null>(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<EnvironmentId | null>(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 ? (
<RefreshCwIcon className="size-3 animate-spin" />
@@ -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<EnvironmentDraftRow>) => {
const published: ProviderInstanceEnvironmentVariable[] = [];
for (const row of nextRows) {
@@ -1361,10 +1361,9 @@ export function ProviderSettingsPanel() {
})}
</SettingsSection>
<AddProviderInstanceDialog
open={isAddInstanceDialogOpen}
onOpenChange={setIsAddInstanceDialogOpen}
/>
{isAddInstanceDialogOpen ? (
<AddProviderInstanceDialog open onOpenChange={setIsAddInstanceDialogOpen} />
) : null}
</SettingsPageContainer>
);
}
+8 -14
View File
@@ -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
* <Input {...bag} placeholder="e.g. Work" />
*/
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<string | null>(null);
return {
value: draft,
value: draft ?? value,
onChange: (event: ChangeEvent<HTMLInputElement>) => {
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<HTMLInputElement>) => {
+2 -2
View File
@@ -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
+50 -66
View File
@@ -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<T, E>(
initialValue: T,
schema: Schema.Codec<T, E>,
): [T, (value: T | ((val: T) => T)) => void] {
// Get the initial value from localStorage or use the provided initialValue
const [storedValue, setStoredValue] = useState<T>(() => {
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<LocalStorageChangeDetail>) => {
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<LocalStorageChangeDetail>) => {
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];
}
+6 -15
View File
@@ -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 },
};
}
+2 -2
View File
@@ -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;
@@ -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<AdvertisedEndpoint> = [];
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();
});
});
@@ -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<AdvertisedEndpoint>;
readonly serverExposureState: DesktopServerExposureState;
}
class DesktopNetworkAccessError extends Schema.TaggedErrorClass<DesktopNetworkAccessError>()(
"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<DesktopNetworkAccessSnapshot> => {
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);
}
@@ -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<DesktopDiscoveredSshHost> = [
{
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();
});
});
+49
View File
@@ -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<DesktopBridge, "discoverSshHosts">;
class DesktopSshDiscoveryError extends Schema.TaggedErrorClass<DesktopSshDiscoveryError>()(
"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<ReadonlyArray<DesktopDiscoveredSshHost>> => 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,
);
+9
View File
@@ -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<OrchestrationMessage> {
+2 -3
View File
@@ -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<string> {
return useKnownTerminalSessions(input)
.filter((session) => session.state.status === "running")
.map((session) => session.target.terminalId);
return selectRunningSubprocessTerminalIds(useKnownTerminalSessions(input));
}
@@ -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);
@@ -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();
});
@@ -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",
@@ -36,6 +36,14 @@ export interface KnownTerminalSession {
readonly state: TerminalSessionState;
}
export function selectRunningSubprocessTerminalIds(
sessions: ReadonlyArray<KnownTerminalSession>,
): ReadonlyArray<string> {
return sessions
.filter((session) => session.state.hasRunningSubprocess)
.map((session) => session.target.terminalId);
}
export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({
buffer: "",
status: "closed",
@@ -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<OrchestrationProposedPlan> = Object.fr
const EMPTY_CHECKPOINTS: ReadonlyArray<OrchestrationCheckpointSummary> = 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<E>(
threadStateAtom: (
environmentId: ScopedThreadRef["environmentId"],