The best way to control Claude Code, Codex and more from any computer or phone
perf(web): the command palette compiles with the React Compiler (#20477)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 18:46 UTC
7a89733cab5fb473c8c8af9bf8c81fb82aa4e232
2 files changed
+777
-957
apps/web/reactCompiledFiles.ts
+1
@@ -52,4 +52,5 @@ export const REACT_COMPILED_FILES = [
52
"apps/web/src/hooks/useSettings.ts",
53
"apps/web/src/components/chat/QueuedRunsControl.tsx",
54
"apps/web/src/components/preview/PreviewView.tsx",
55
+ "apps/web/src/components/CommandPalette.tsx",
56
] as const;
apps/web/src/components/CommandPalette.tsx
+776
-957
@@ -44,6 +44,7 @@ import {
44
AuthSourceControlWriteScope,
45
AuthFilesystemReadScope,
46
type DesktopWslState,
47
+ type ClientSettings,
48
type EnvironmentId,
49
type EnvironmentMachineKind,
50
type FilesystemBrowseResult,
@@ -55,7 +56,6 @@ import {
56
resolveEnvironmentMachineKind,
57
} from "@t3tools/contracts";
58
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
58
-import * as Option from "effect/Option";
59
import {
60
ArrowLeftIcon,
61
ChartNoAxesColumnIcon,
@@ -80,11 +80,10 @@ import {
80
} from "lucide-react";
81
import { requestThreadFindOpen } from "./chat/threadFindActionBus";
82
import {
83
- useCallback,
83
useDeferredValue,
84
useEffect,
85
+ useEffectEvent,
86
useLayoutEffect,
87
- useMemo,
87
useReducer,
88
useRef,
89
useState,
@@ -105,6 +104,7 @@ import {
104
promptLinkRepositoryOf,
105
} from "./promptLinks/copyPromptLink";
106
import { useClientSettings } from "../hooks/useSettings";
107
+import { useStableCallback } from "../hooks/useStableCallback";
108
import { useTheme } from "../hooks/useTheme";
109
import { useCustomThemes } from "../hooks/useCustomThemes";
110
import { useEnvironmentThemeDefinitions } from "../hooks/useEnvironmentTheme";
@@ -366,8 +366,133 @@ function notifyThemeSaveFailure(): void {
366
);
367
}
368
369
-function projectFavicon(project: Project) {
370
- return <ProjectFavicon project={project} className="size-4" />;
369
+// These run in their own hooks so the results stay cached across the palette's
370
+// later hook calls; the thread and project items key on them.
371
+function useThemeCards(
372
+ customThemes: ReturnType<typeof useCustomThemes>,
373
+ environmentThemes: ReturnType<typeof useEnvironmentThemeDefinitions>,
374
+) {
375
+ "use memo";
376
+ const seen = new Set<string>();
377
+ return [
378
+ ...STANDARD_THEME_CARDS.map((card) => ({ ...card, id: null })),
379
+ ...[...BUILT_IN_THEMES, ...customThemes, ...environmentThemes]
380
+ .filter((definition) => {
381
+ if (seen.has(definition.id)) return false;
382
+ seen.add(definition.id);
383
+ return true;
384
+ })
385
+ .map(getThemeCardDefinition),
386
+ ];
387
+}
388
+
389
+function useProviderEntryMap(
390
+ environments: ReturnType<typeof useEnvironments>["environments"],
391
+ primaryEnvironmentId: ReturnType<typeof usePrimaryEnvironmentId>,
392
+ providers: Parameters<typeof deriveProviderInstanceEntries>[0],
393
+) {
394
+ "use memo";
395
+ const map = new Map<string, ProviderInstanceEntry>();
396
+ for (const environment of environments) {
397
+ const serverConfig = environment.serverConfig;
398
+ const environmentProviders =
399
+ serverConfig?.providers ??
400
+ (environment.environmentId === primaryEnvironmentId ? providers : []);
401
+ const derived = deriveProviderInstanceEntries(environmentProviders);
402
+ const entries = serverConfig
403
+ ? applyProviderInstanceSettings(derived, serverConfig.settings, null)
404
+ : derived;
405
+ for (const entry of entries) {
406
+ map.set(`${environment.environmentId}:${entry.instanceId}`, entry);
407
+ }
408
+ }
409
+ return map;
410
+}
411
+
412
+function useThreadContentMatchByKey(matches: ReturnType<typeof useThreadSearch>["matches"]) {
413
+ "use memo";
414
+ return new Map(
415
+ matches.flatMap((match) =>
416
+ match.source === "user" || match.source === "assistant"
417
+ ? [[threadSearchMatchKey(match), match] as const]
418
+ : [],
419
+ ),
420
+ );
421
+}
422
+
423
+function useEnvironmentLookups(environments: ReturnType<typeof useEnvironments>["environments"]) {
424
+ "use memo";
425
+ const environmentLabelById = new Map(
426
+ environments.map((environment) => [environment.environmentId, environment.label] as const),
427
+ );
428
+ const projectEnvironmentLocationById = new Map(
429
+ environments.map((environment) => {
430
+ const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
431
+ const isLocal = isPrimary || isDesktopLocalConnectionTarget(environment.entry.target);
432
+ return [
433
+ environment.environmentId,
434
+ {
435
+ kind: isLocal ? "local" : "remote",
436
+ label: isPrimary ? "Local" : isLocal ? `${environment.label} (Local)` : environment.label,
437
+ machine: resolveEnvironmentMachineKind(environment.serverConfig),
438
+ },
439
+ ] as const;
440
+ }),
441
+ );
442
+ return { environmentLabelById, projectEnvironmentLocationById };
443
+}
444
+
445
+function useProjectLookups(projects: ReturnType<typeof useProjects>) {
446
+ "use memo";
447
+ const projectCwdById = new Map<ProjectId, string>(
448
+ projects.map((project) => [project.id, project.workspaceRoot]),
449
+ );
450
+ const projectByKey = new Map(
451
+ projects.map((project) => [`${project.environmentId}:${project.id}`, project]),
452
+ );
453
+ const projectTitleById = new Map<ProjectId, string>(
454
+ projects.map((project) => [project.id, project.title]),
455
+ );
456
+ return { projectCwdById, projectByKey, projectTitleById };
457
+}
458
+
459
+function useSortedProjectGroups({
460
+ projects,
461
+ projectOrder,
462
+ clientSettings,
463
+ primaryEnvironmentId,
464
+ environmentLabelById,
465
+ threads,
466
+}: {
467
+ readonly projects: ReturnType<typeof useProjects>;
468
+ readonly projectOrder: ReturnType<typeof useUiStateStore.getState>["projectOrder"];
469
+ readonly clientSettings: ClientSettings;
470
+ readonly primaryEnvironmentId: ReturnType<typeof usePrimaryEnvironmentId>;
471
+ readonly environmentLabelById: ReadonlyMap<EnvironmentId, string>;
472
+ readonly threads: ReturnType<typeof useThreadShells>;
473
+}) {
474
+ "use memo";
475
+ const projectGroupingSettings = selectProjectGroupingSettings(clientSettings);
476
+ const orderedProjects = orderItemsByPreferredIds({
477
+ items: projects,
478
+ preferredIds: projectOrder,
479
+ getId: getProjectOrderKey,
480
+ getPreferenceIds: (project) => [
481
+ getProjectOrderKey(project),
482
+ legacyProjectCwdPreferenceKey(project.workspaceRoot),
483
+ ],
484
+ });
485
+ const unsortedProjectGroups = buildSidebarProjectSnapshots({
486
+ projects: clientSettings.sidebarProjectSortOrder === "manual" ? orderedProjects : projects,
487
+ settings: projectGroupingSettings,
488
+ primaryEnvironmentId,
489
+ resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
490
+ });
491
+ return sortLogicalProjectsForSidebar(
492
+ unsortedProjectGroups,
493
+ threads,
494
+ clientSettings.sidebarProjectSortOrder,
495
+ );
496
}
497
498
export function CommandPalette({ children }: { children: ReactNode }) {
@@ -377,14 +502,11 @@ export function CommandPalette({ children }: { children: ReactNode }) {
502
mode: "command",
503
openIntent: null,
504
});
380
- const setOpen = useCallback((open: boolean) => dispatch({ _tag: "SetOpen", open }), []);
381
- const toggleMode = useCallback(
382
- (mode: SearchOverlayMode) => dispatch({ _tag: "ToggleMode", mode }),
383
- [],
384
- );
385
- const openAddProject = useCallback(() => dispatch({ _tag: "OpenAddProject" }), []);
386
- const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
387
- const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
505
+ const setOpen = (open: boolean) => dispatch({ _tag: "SetOpen", open });
506
+ const toggleMode = (mode: SearchOverlayMode) => dispatch({ _tag: "ToggleMode", mode });
507
+ const openAddProject = () => dispatch({ _tag: "OpenAddProject" });
508
+ const openNewThreadIn = () => dispatch({ _tag: "OpenNewThreadIn" });
509
+ const clearOpenIntent = () => dispatch({ _tag: "ClearOpenIntent" });
510
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
511
const { theme, themeHalves, resolvedTheme, appearanceMode, setAppearanceMode } = useTheme();
512
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
@@ -668,7 +790,7 @@ function OpenCommandPaletteDialog(props: {
790
linkedPullRequestUrl:
791
activeThread?.linkedPullRequest?.url ?? activeThread?.branchPullRequest?.url ?? null,
792
});
671
- const copyActiveThreadReference = useCallback(async () => {
793
+ const copyActiveThreadReference = async () => {
794
const target = activeThreadReferenceCopyTarget;
795
if (target === null) return;
796
try {
@@ -689,7 +811,7 @@ function OpenCommandPaletteDialog(props: {
811
}),
812
);
813
}
692
- }, [activeThreadReferenceCopyTarget]);
814
+ };
815
const projectOrder = useUiStateStore((store) => store.projectOrder);
816
const threads = useThreadShells();
817
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
@@ -704,67 +826,23 @@ function OpenCommandPaletteDialog(props: {
826
} = useTheme();
827
const customThemes = useCustomThemes();
828
const environmentThemes = useEnvironmentThemeDefinitions();
707
- const themeCards = useMemo(() => {
708
- const seen = new Set<string>();
709
- return [
710
- ...STANDARD_THEME_CARDS.map((card) => ({ ...card, id: null })),
711
- ...[...BUILT_IN_THEMES, ...customThemes, ...environmentThemes]
712
- .filter((definition) => {
713
- if (seen.has(definition.id)) return false;
714
- seen.add(definition.id);
715
- return true;
716
- })
717
- .map(getThemeCardDefinition),
718
- ];
719
- }, [customThemes, environmentThemes]);
829
+ const themeCards = useThemeCards(customThemes, environmentThemes);
830
const providers = useAtomValue(primaryServerProvidersAtom);
721
- const providerEntryByEnvironmentAndInstanceId = useMemo(() => {
722
- const map = new Map<string, ProviderInstanceEntry>();
723
- for (const environment of environments) {
724
- const serverConfig = environment.serverConfig;
725
- const environmentProviders =
726
- serverConfig?.providers ??
727
- (environment.environmentId === primaryEnvironmentId ? providers : []);
728
- const derived = deriveProviderInstanceEntries(environmentProviders);
729
- const entries = serverConfig
730
- ? applyProviderInstanceSettings(derived, serverConfig.settings, null)
731
- : derived;
732
- for (const entry of entries) {
733
- map.set(`${environment.environmentId}:${entry.instanceId}`, entry);
734
- }
735
- }
736
- return map;
737
- }, [environments, primaryEnvironmentId, providers]);
831
+ const providerEntryByEnvironmentAndInstanceId = useProviderEntryMap(
832
+ environments,
833
+ primaryEnvironmentId,
834
+ providers,
835
+ );
836
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
837
const currentView = viewStack.at(-1) ?? null;
740
- const environmentIds = useMemo(
741
- () =>
742
- environments
743
- .filter((environment) => environment.connection.phase === "connected")
744
- .map((environment) => environment.environmentId),
745
- [environments],
746
- );
838
+ const environmentIds = environments
839
+ .filter((environment) => environment.connection.phase === "connected")
840
+ .map((environment) => environment.environmentId);
841
const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : "";
842
const threadSearch = useThreadSearch(environmentIds, threadSearchQuery);
749
- const threadContentMatchByKey = useMemo(
750
- () =>
751
- new Map(
752
- threadSearch.matches.flatMap((match) =>
753
- match.source === "user" || match.source === "assistant"
754
- ? [[threadSearchMatchKey(match), match] as const]
755
- : [],
756
- ),
757
- ),
758
- [threadSearch.matches],
759
- );
843
+ const threadContentMatchByKey = useThreadContentMatchByKey(threadSearch.matches);
844
const [browseGeneration, setBrowseGeneration] = useState(0);
761
- const browseNavigationRef = useRef<ReturnType<typeof createBrowseNavigationCoordinator> | null>(
762
- null,
763
- );
764
- if (browseNavigationRef.current === null) {
765
- browseNavigationRef.current = createBrowseNavigationCoordinator();
766
- }
767
- const browseNavigation = browseNavigationRef.current;
845
+ const [browseNavigation] = useState(createBrowseNavigationCoordinator);
846
const [addProjectEnvironmentId, setAddProjectEnvironmentId] = useState<EnvironmentId | null>(
847
null,
848
);
@@ -785,117 +863,38 @@ function OpenCommandPaletteDialog(props: {
863
const cloneLookupGeneration = useRef(0);
864
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
865
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
788
- const projectGroupingSettings = useMemo(
789
- () => selectProjectGroupingSettings(clientSettings),
790
- [clientSettings],
791
- );
792
-
793
- const environmentLabelById = useMemo(
794
- () =>
795
- new Map(
796
- environments.map((environment) => [environment.environmentId, environment.label] as const),
797
- ),
798
- [environments],
799
- );
800
- const projectEnvironmentLocationById = useMemo(
801
- () =>
802
- new Map(
803
- environments.map((environment) => {
804
- const isPrimary = environment.entry.target._tag === "PrimaryConnectionTarget";
805
- const isLocal = isPrimary || isDesktopLocalConnectionTarget(environment.entry.target);
806
- return [
807
- environment.environmentId,
808
- {
809
- kind: isLocal ? "local" : "remote",
810
- label: isPrimary
811
- ? "Local"
812
- : isLocal
813
- ? `${environment.label} (Local)`
814
- : environment.label,
815
- machine: resolveEnvironmentMachineKind(environment.serverConfig),
816
- },
817
- ] as const;
818
- }),
819
- ),
820
- [environments],
821
- );
822
- const orderedProjects = useMemo(
823
- () =>
824
- orderItemsByPreferredIds({
825
- items: projects,
826
- preferredIds: projectOrder,
827
- getId: getProjectOrderKey,
828
- getPreferenceIds: (project) => [
829
- getProjectOrderKey(project),
830
- legacyProjectCwdPreferenceKey(project.workspaceRoot),
831
- ],
832
- }),
833
- [projectOrder, projects],
834
- );
835
- const unsortedProjectGroups = useMemo(
836
- () =>
837
- buildSidebarProjectSnapshots({
838
- projects: clientSettings.sidebarProjectSortOrder === "manual" ? orderedProjects : projects,
839
- settings: projectGroupingSettings,
840
- primaryEnvironmentId,
841
- resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
842
- }),
843
- [
844
- clientSettings.sidebarProjectSortOrder,
845
- environmentLabelById,
846
- orderedProjects,
847
- primaryEnvironmentId,
848
- projectGroupingSettings,
849
- projects,
850
- ],
851
- );
852
- const projectGroups = useMemo(
853
- () =>
854
- sortLogicalProjectsForSidebar(
855
- unsortedProjectGroups,
856
- threads,
857
- clientSettings.sidebarProjectSortOrder,
858
- ),
859
- [clientSettings.sidebarProjectSortOrder, threads, unsortedProjectGroups],
860
- );
861
- const contextualProjectRef = useMemo(
862
- () =>
863
- resolveThreadActionProjectRef({
864
- activeDraftThread,
865
- activeThread: activeThread ?? undefined,
866
- defaultProjectRef,
867
- handleNewThread,
868
- }),
869
- [activeDraftThread, activeThread, defaultProjectRef, handleNewThread],
870
- );
871
- const projectPickerEntries = useMemo(
872
- () =>
873
- buildSidebarProjectPickerEntries({
874
- groups: projectGroups,
875
- preferredProjectRef: contextualProjectRef,
876
- }),
877
- [contextualProjectRef, projectGroups],
878
- );
879
- const pickerProjects = useMemo(
880
- () =>
881
- projectPickerEntries.map(({ group, targetProject }) => ({
882
- ...targetProject,
883
- displayName: group.displayName,
884
- })),
885
- [projectPickerEntries],
886
- );
887
- const projectGroupByTargetKey = useMemo(
888
- () =>
889
- new Map(
890
- projectPickerEntries.map(({ group, targetProject }) => [
891
- `${targetProject.environmentId}:${targetProject.id}`,
892
- group,
893
- ]),
894
- ),
895
- [projectPickerEntries],
866
+ const { environmentLabelById, projectEnvironmentLocationById } =
867
+ useEnvironmentLookups(environments);
868
+ const projectGroups = useSortedProjectGroups({
869
+ projects,
870
+ projectOrder,
871
+ clientSettings,
872
+ primaryEnvironmentId,
873
+ environmentLabelById,
874
+ threads,
875
+ });
876
+ const contextualProjectRef = resolveThreadActionProjectRef({
877
+ activeDraftThread,
878
+ activeThread: activeThread ?? undefined,
879
+ defaultProjectRef,
880
+ handleNewThread,
881
+ });
882
+ const projectPickerEntries = buildSidebarProjectPickerEntries({
883
+ groups: projectGroups,
884
+ preferredProjectRef: contextualProjectRef,
885
+ });
886
+ const pickerProjects = projectPickerEntries.map(({ group, targetProject }) => ({
887
+ ...targetProject,
888
+ displayName: group.displayName,
889
+ }));
890
+ const projectGroupByTargetKey = new Map(
891
+ projectPickerEntries.map(({ group, targetProject }) => [
892
+ `${targetProject.environmentId}:${targetProject.id}`,
893
+ group,
894
+ ]),
895
);
896
898
- const addProjectEnvironmentOptions = useMemo(() => {
897
+ const addProjectEnvironmentOptions = (() => {
898
const options = environments
899
.filter((environment) => canCreateProjectInEnvironment(environment.connection.phase))
900
.map((environment): AddProjectEnvironmentOption => {
@@ -922,24 +921,21 @@ function OpenCommandPaletteDialog(props: {
921
});
922
923
return options;
925
- }, [environments]);
924
+ })();
925
const defaultAddProjectEnvironmentId =
926
addProjectEnvironmentOptions.find((option) => option.isConnected)?.environmentId ?? null;
928
- const wslAddProjectEnvironmentOption = useMemo(
929
- () =>
930
- addProjectEnvironmentOptions.find((option) => {
931
- if (!option.isConnected) {
932
- return false;
933
- }
934
- const environment = environments.find(
935
- (candidate) => candidate.environmentId === option.environmentId,
936
- );
937
- return environment
938
- ? desktopLocalBackendId(environment.entry.target)?.startsWith("wsl:") === true
939
- : false;
940
- }) ?? null,
941
- [addProjectEnvironmentOptions, environments],
942
- );
927
+ const wslAddProjectEnvironmentOption =
928
+ addProjectEnvironmentOptions.find((option) => {
929
+ if (!option.isConnected) {
930
+ return false;
931
+ }
932
+ const environment = environments.find(
933
+ (candidate) => candidate.environmentId === option.environmentId,
934
+ );
935
+ return environment
936
+ ? desktopLocalBackendId(environment.entry.target)?.startsWith("wsl:") === true
937
+ : false;
938
+ }) ?? null;
939
const browseEnvironmentId = addProjectEnvironmentId ?? defaultAddProjectEnvironmentId;
940
const canCreateProject = useEnvironmentScope(browseEnvironmentId, AuthOrchestrationOperateScope);
941
const browseEnvironment =
@@ -950,7 +946,7 @@ function OpenCommandPaletteDialog(props: {
946
// "wsl:ubuntu"). The catalog environmentId is descriptor-derived and won't
947
// route on the desktop side; pickFolder only recognizes the pool id, which
948
// the bootstrap list exposes.
953
- const browseDesktopInstanceId = useMemo(() => {
949
+ const browseDesktopInstanceId = (() => {
950
if (!browseEnvironmentIsDesktopLocal || browseEnvironment === null) {
951
return null;
952
}
@@ -961,7 +957,7 @@ function OpenCommandPaletteDialog(props: {
957
return (
958
desktopLocalBootstraps.find((bootstrap) => bootstrap.httpBaseUrl === displayUrl)?.id ?? null
959
);
964
- }, [browseEnvironment, browseEnvironmentIsDesktopLocal, desktopLocalBootstraps]);
960
+ })();
961
const sourceControlDiscovery = useEnvironmentQuery(
962
browseEnvironmentId === null
963
? null
@@ -981,52 +977,25 @@ function OpenCommandPaletteDialog(props: {
977
addProjectCloneFlow.repository?.nameWithOwner ?? addProjectCloneFlow.remoteUrl,
978
)
979
: "";
984
- const browsePath = useMemo(
985
- () =>
986
- getFilesystemBrowsePath(
987
- query,
988
- browseEnvironmentPlatform,
989
- browseEnvironmentId !== null && !isRemoteProjectRepositoryStep && newProjectFlow === null,
990
- ),
991
- [
992
- browseEnvironmentId,
993
- browseEnvironmentPlatform,
994
- isRemoteProjectRepositoryStep,
995
- newProjectFlow,
996
- query,
997
- ],
980
+ const browsePath = getFilesystemBrowsePath(
981
+ query,
982
+ browseEnvironmentPlatform,
983
+ browseEnvironmentId !== null && !isRemoteProjectRepositoryStep && newProjectFlow === null,
984
);
985
const isBrowsing = browsePath.isBrowsing;
986
const browseDirectoryPath = browsePath.directoryPath;
987
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
1002
- const getAddProjectInitialQueryForEnvironment = useCallback(
1003
- (environmentId: EnvironmentId | null): string => {
1004
- const environment = environments.find(
1005
- (candidate) => candidate.environmentId === environmentId,
1006
- );
1007
- const environmentSettings = environment?.serverConfig?.settings ?? null;
1008
- const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? "";
1009
- if (baseDirectory.length === 0) {
1010
- return "~/";
1011
- }
1012
- return ensureBrowseDirectoryPath(baseDirectory);
1013
- },
1014
- [environments],
1015
- );
988
+ const getAddProjectInitialQueryForEnvironment = (environmentId: EnvironmentId | null): string => {
989
+ const environment = environments.find((candidate) => candidate.environmentId === environmentId);
990
+ const environmentSettings = environment?.serverConfig?.settings ?? null;
991
+ const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? "";
992
+ if (baseDirectory.length === 0) {
993
+ return "~/";
994
+ }
995
+ return ensureBrowseDirectoryPath(baseDirectory);
996
+ };
997
1017
- const projectCwdById = useMemo(
1018
- () =>
1019
- new Map<ProjectId, string>(projects.map((project) => [project.id, project.workspaceRoot])),
1020
- [projects],
1021
- );
1022
- const projectByKey = useMemo(
1023
- () => new Map(projects.map((project) => [`${project.environmentId}:${project.id}`, project])),
1024
- [projects],
1025
- );
1026
- const projectTitleById = useMemo(
1027
- () => new Map<ProjectId, string>(projects.map((project) => [project.id, project.title])),
1028
- [projects],
1029
- );
998
+ const { projectCwdById, projectByKey, projectTitleById } = useProjectLookups(projects);
999
1000
const activeThreadId = activeThread?.id;
1001
const supportsThreadFind =
@@ -1045,11 +1014,8 @@ function OpenCommandPaletteDialog(props: {
1014
browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId
1015
? currentProjectCwd
1016
: null;
1048
- const getBrowseCwdForEnvironment = useCallback(
1049
- (environmentId: EnvironmentId | null): string | null =>
1050
- environmentId && currentProjectEnvironmentId === environmentId ? currentProjectCwd : null,
1051
- [currentProjectCwd, currentProjectEnvironmentId],
1052
- );
1017
+ const getBrowseCwdForEnvironment = (environmentId: EnvironmentId | null): string | null =>
1018
+ environmentId && currentProjectEnvironmentId === environmentId ? currentProjectCwd : null;
1019
const relativePathNeedsActiveProject =
1020
isExplicitRelativeProjectPath(query.trim()) && currentProjectCwdForBrowse === null;
1021
const browseAccess = useFilesystemReadAccess(browseEnvironmentId);
@@ -1076,48 +1042,40 @@ function OpenCommandPaletteDialog(props: {
1042
? (browseAccess.error ?? "This connection cannot browse host folders.")
1043
: null;
1044
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
1079
- const { visibleEntries: visibleBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
1080
- () =>
1081
- pinnedCloneDirectoryName
1082
- ? filterPinnedBrowseEntries({
1083
- browseEntries,
1084
- filterQuery: browsePath.filterQuery,
1085
- pinnedDirectoryName: pinnedCloneDirectoryName,
1086
- caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform),
1087
- })
1088
- : filterFilesystemBrowseEntries(browseEntries, browsePath.filterQuery),
1089
- [browseEntries, browseEnvironmentPlatform, browsePath.filterQuery, pinnedCloneDirectoryName],
1090
- );
1091
-
1092
- const prefetchBrowsePath = useCallback(
1093
- async (
1094
- partialPath: string,
1095
- environmentId: EnvironmentId | null = browseEnvironmentId,
1096
- cwd: string | null = currentProjectCwdForBrowse,
1097
- ): Promise<void> => {
1098
- if (!environmentId) {
1099
- return;
1100
- }
1101
- const environment = environments.find(
1102
- (candidate) => candidate.environmentId === environmentId,
1103
- );
1104
- if (
1105
- !readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||
1106
- !canPreloadBrowsePath(environment?.connection.phase)
1107
- ) {
1108
- return;
1109
- }
1045
+ const { visibleEntries: visibleBrowseEntries, exactEntry: exactBrowseEntry } =
1046
+ pinnedCloneDirectoryName
1047
+ ? filterPinnedBrowseEntries({
1048
+ browseEntries,
1049
+ filterQuery: browsePath.filterQuery,
1050
+ pinnedDirectoryName: pinnedCloneDirectoryName,
1051
+ caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform),
1052
+ })
1053
+ : filterFilesystemBrowseEntries(browseEntries, browsePath.filterQuery);
1054
+
1055
+ const prefetchBrowsePath = async (
1056
+ partialPath: string,
1057
+ environmentId: EnvironmentId | null = browseEnvironmentId,
1058
+ cwd: string | null = currentProjectCwdForBrowse,
1059
+ ): Promise<void> => {
1060
+ if (!environmentId) {
1061
+ return;
1062
+ }
1063
+ const environment = environments.find((candidate) => candidate.environmentId === environmentId);
1064
+ if (
1065
+ !readEnvironmentScope(environmentId, AuthFilesystemReadScope) ||
1066
+ !canPreloadBrowsePath(environment?.connection.phase)
1067
+ ) {
1068
+ return;
1069
+ }
1070
1111
- await loadBrowsePath({
1112
- environmentId,
1113
- input: {
1114
- partialPath,
1115
- ...(cwd ? { cwd } : {}),
1116
- },
1117
- });
1118
- },
1119
- [browseEnvironmentId, currentProjectCwdForBrowse, environments, loadBrowsePath],
1120
- );
1071
+ await loadBrowsePath({
1072
+ environmentId,
1073
+ input: {
1074
+ partialPath,
1075
+ ...(cwd ? { cwd } : {}),
1076
+ },
1077
+ });
1078
+ };
1079
1080
useEffect(
1081
() => () => {
@@ -1126,97 +1084,77 @@ function OpenCommandPaletteDialog(props: {
1084
[browseNavigation],
1085
);
1086
1129
- const openProjectFromSearch = useMemo(
1130
- () => async (project: (typeof projects)[number]) => {
1131
- const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
1132
- const groupedProjectKeys = group
1133
- ? new Set(
1134
- group.memberProjectRefs.map(
1135
- (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
1136
- ),
1137
- )
1138
- : null;
1139
- const latestThread = groupedProjectKeys
1140
- ? (sortThreads(
1141
- threads.filter(
1142
- (thread) =>
1143
- thread.archivedAt === null &&
1144
- groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`),
1145
- ),
1146
- clientSettings.sidebarThreadSortOrder,
1147
- )[0] ?? null)
1148
- : getLatestThreadForProject(
1149
- threads.filter((thread) => thread.environmentId === project.environmentId),
1150
- project.id,
1151
- clientSettings.sidebarThreadSortOrder,
1152
- );
1153
- if (latestThread) {
1154
- await navigate({
1155
- to: "/$environmentId/$threadId",
1156
- params: buildThreadRouteParams(
1157
- scopeThreadRef(latestThread.environmentId, latestThread.id),
1087
+ const openProjectFromSearch = async (project: (typeof projects)[number]) => {
1088
+ const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);
1089
+ const groupedProjectKeys = group
1090
+ ? new Set(
1091
+ group.memberProjectRefs.map(
1092
+ (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
1093
),
1159
- });
1160
- return;
1161
- }
1094
+ )
1095
+ : null;
1096
+ const latestThread = groupedProjectKeys
1097
+ ? (sortThreads(
1098
+ threads.filter(
1099
+ (thread) =>
1100
+ thread.archivedAt === null &&
1101
+ groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`),
1102
+ ),
1103
+ clientSettings.sidebarThreadSortOrder,
1104
+ )[0] ?? null)
1105
+ : getLatestThreadForProject(
1106
+ threads.filter((thread) => thread.environmentId === project.environmentId),
1107
+ project.id,
1108
+ clientSettings.sidebarThreadSortOrder,
1109
+ );
1110
+ if (latestThread) {
1111
+ await navigate({
1112
+ to: "/$environmentId/$threadId",
1113
+ params: buildThreadRouteParams(scopeThreadRef(latestThread.environmentId, latestThread.id)),
1114
+ });
1115
+ return;
1116
+ }
1117
1163
- await handleNewThread(scopeProjectRef(project.environmentId, project.id));
1164
- },
1165
- [
1166
- clientSettings.sidebarThreadSortOrder,
1167
- handleNewThread,
1168
- navigate,
1169
- projectGroupByTargetKey,
1170
- threads,
1171
- ],
1172
- );
1118
+ await handleNewThread(scopeProjectRef(project.environmentId, project.id));
1119
+ };
1120
1174
- const projectSearchItems = useMemo(
1175
- () =>
1176
- buildProjectActionItems({
1177
- projects: pickerProjects,
1178
- valuePrefix: "project",
1179
- searchTerms: (project) => {
1180
- const members = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`)
1181
- ?.memberProjects ?? [project];
1182
- return buildCommandPaletteProjectMetadata({
1183
- projects: members,
1184
- locationByEnvironmentId: projectEnvironmentLocationById,
1185
- }).searchTerms;
1186
- },
1187
- renderDescription: (project) => {
1188
- const members = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`)
1189
- ?.memberProjects ?? [project];
1190
- const metadata = buildCommandPaletteProjectMetadata({
1191
- projects: members,
1192
- locationByEnvironmentId: projectEnvironmentLocationById,
1193
- });
1194
- const location = projectEnvironmentLocationById.get(project.environmentId) ?? {
1195
- kind: "remote" as const,
1196
- label: "Remote",
1197
- machine: "server" as const,
1198
- };
1199
- return (
1200
- <ProjectSearchDescription
1201
- environmentLabels={metadata.environmentLabels}
1202
- grouped={members.length > 1}
1203
- location={location}
1204
- workspaceRoot={project.workspaceRoot}
1205
- />
1206
- );
1207
- },
1208
- icon: projectFaviconIcon,
1209
- runProject: openProjectFromSearch,
1210
- }),
1211
- [
1212
- openProjectFromSearch,
1213
- pickerProjects,
1214
- projectEnvironmentLocationById,
1215
- projectGroupByTargetKey,
1216
- ],
1217
- );
1121
+ const projectSearchItems = buildProjectActionItems({
1122
+ projects: pickerProjects,
1123
+ valuePrefix: "project",
1124
+ searchTerms: (project) => {
1125
+ const members = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`)
1126
+ ?.memberProjects ?? [project];
1127
+ return buildCommandPaletteProjectMetadata({
1128
+ projects: members,
1129
+ locationByEnvironmentId: projectEnvironmentLocationById,
1130
+ }).searchTerms;
1131
+ },
1132
+ renderDescription: (project) => {
1133
+ const members = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`)
1134
+ ?.memberProjects ?? [project];
1135
+ const metadata = buildCommandPaletteProjectMetadata({
1136
+ projects: members,
1137
+ locationByEnvironmentId: projectEnvironmentLocationById,
1138
+ });
1139
+ const location = projectEnvironmentLocationById.get(project.environmentId) ?? {
1140
+ kind: "remote" as const,
1141
+ label: "Remote",
1142
+ machine: "server" as const,
1143
+ };
1144
+ return (
1145
+ <ProjectSearchDescription
1146
+ environmentLabels={metadata.environmentLabels}
1147
+ grouped={members.length > 1}
1148
+ location={location}
1149
+ workspaceRoot={project.workspaceRoot}
1150
+ />
1151
+ );
1152
+ },
1153
+ icon: projectFaviconIcon,
1154
+ runProject: openProjectFromSearch,
1155
+ });
1156
1219
- const projectThreadItems = useMemo(() => {
1157
+ const projectThreadItems = (() => {
1158
const isScratch = (project: CommandPaletteProject) =>
1159
isScratchProject(project, scratchWorkspaceRootFor(project.environmentId));
1160
const projectItems = enumerateCommandPaletteItems(
@@ -1289,118 +1227,90 @@ function OpenCommandPaletteDialog(props: {
1227
},
1228
...projectItems.slice(noProjectIndex),
1229
];
1292
- }, [
1293
- contextualProjectRef,
1294
- handleNewThread,
1295
- pickerProjects,
1296
- projectEnvironmentLocationById,
1297
- projectGroupByTargetKey,
1298
- scratchTargetEnvironmentId,
1299
- scratchWorkspaceRootFor,
1300
- startScratchThread,
1301
- ]);
1302
-
1303
- const allThreadItems = useMemo(
1304
- () =>
1305
- buildThreadActionItems({
1306
- threads,
1307
- ...(activeThreadId ? { activeThreadId } : {}),
1308
- projectTitleById,
1309
- sortOrder: clientSettings.sidebarThreadSortOrder,
1310
- icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
1311
- renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,
1312
- renderTrailingContent: (thread) => (
1313
- <>
1314
- <ThreadSearchPullRequestNumber
1315
- thread={thread}
1316
- query={threadSearchQuery}
1317
- settled={thread.settledOverride === "settled"}
1318
- />
1319
- <ThreadRowTrailingStatus thread={thread} />
1320
- </>
1321
- ),
1322
- renderDescription: (thread, { projectTitle }) => {
1323
- const modelInstanceId =
1324
- thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
1325
- const providerEntry =
1326
- providerEntryByEnvironmentAndInstanceId.get(
1327
- `${thread.environmentId}:${modelInstanceId}`,
1328
- ) ?? null;
1329
- return (
1330
- <ThreadCommandSubtitle
1331
- project={projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null}
1332
- projectTitle={projectTitle ?? null}
1333
- environmentLabel={
1334
- projectEnvironmentLocationById.get(thread.environmentId)?.label ?? "Remote"
1335
- }
1336
- branch={thread.branch}
1337
- worktreePath={thread.worktreePath}
1338
- isCurrent={thread.id === activeThreadId}
1339
- driverKind={providerEntry?.driverKind ?? null}
1340
- providerDisplayName={
1341
- thread.runtime?.providerName ?? providerEntry?.displayName ?? modelInstanceId
1342
- }
1343
- acpRegistryAgentId={providerEntry?.acpRegistryAgentId}
1344
- acpRegistryIconUrl={providerEntry?.acpRegistryIconUrl}
1345
- />
1346
- );
1347
- },
1348
- getContentMatch: (thread) => {
1349
- const match = threadContentMatchByKey.get(
1350
- threadSearchMatchKey({
1351
- environmentId: thread.environmentId,
1352
- threadId: thread.id,
1353
- }),
1354
- );
1355
- return match && (match.source === "user" || match.source === "assistant")
1356
- ? {
1357
- source: match.source,
1358
- snippet: match.snippet,
1359
- query: threadSearch.query,
1360
- }
1361
- : undefined;
1362
- },
1363
- runThread: async (thread) => {
1364
- await navigate({
1365
- to: "/$environmentId/$threadId",
1366
- params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
1367
- });
1368
- },
1369
- }),
1370
- [
1371
- activeThreadId,
1372
- clientSettings.sidebarThreadSortOrder,
1373
- navigate,
1374
- projectCwdById,
1375
- projectByKey,
1376
- projectEnvironmentLocationById,
1377
- projectTitleById,
1378
- providerEntryByEnvironmentAndInstanceId,
1379
- threadContentMatchByKey,
1380
- threadSearch.query,
1381
- threadSearchQuery,
1382
- threads,
1383
- ],
1384
- );
1230
+ })();
1231
+
1232
+ const allThreadItems = buildThreadActionItems({
1233
+ threads,
1234
+ ...(activeThreadId ? { activeThreadId } : {}),
1235
+ projectTitleById,
1236
+ sortOrder: clientSettings.sidebarThreadSortOrder,
1237
+ icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,
1238
+ renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,
1239
+ renderTrailingContent: (thread) => (
1240
+ <>
1241
+ <ThreadSearchPullRequestNumber
1242
+ thread={thread}
1243
+ query={threadSearchQuery}
1244
+ settled={thread.settledOverride === "settled"}
1245
+ />
1246
+ <ThreadRowTrailingStatus thread={thread} />
1247
+ </>
1248
+ ),
1249
+ renderDescription: (thread, { projectTitle }) => {
1250
+ const modelInstanceId =
1251
+ thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId;
1252
+ const providerEntry =
1253
+ providerEntryByEnvironmentAndInstanceId.get(`${thread.environmentId}:${modelInstanceId}`) ??
1254
+ null;
1255
+ return (
1256
+ <ThreadCommandSubtitle
1257
+ project={projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null}
1258
+ projectTitle={projectTitle ?? null}
1259
+ environmentLabel={
1260
+ projectEnvironmentLocationById.get(thread.environmentId)?.label ?? "Remote"
1261
+ }
1262
+ branch={thread.branch}
1263
+ worktreePath={thread.worktreePath}
1264
+ isCurrent={thread.id === activeThreadId}
1265
+ driverKind={providerEntry?.driverKind ?? null}
1266
+ providerDisplayName={
1267
+ thread.runtime?.providerName ?? providerEntry?.displayName ?? modelInstanceId
1268
+ }
1269
+ acpRegistryAgentId={providerEntry?.acpRegistryAgentId}
1270
+ acpRegistryIconUrl={providerEntry?.acpRegistryIconUrl}
1271
+ />
1272
+ );
1273
+ },
1274
+ getContentMatch: (thread) => {
1275
+ const match = threadContentMatchByKey.get(
1276
+ threadSearchMatchKey({
1277
+ environmentId: thread.environmentId,
1278
+ threadId: thread.id,
1279
+ }),
1280
+ );
1281
+ return match && (match.source === "user" || match.source === "assistant")
1282
+ ? {
1283
+ source: match.source,
1284
+ snippet: match.snippet,
1285
+ query: threadSearch.query,
1286
+ }
1287
+ : undefined;
1288
+ },
1289
+ runThread: async (thread) => {
1290
+ await navigate({
1291
+ to: "/$environmentId/$threadId",
1292
+ params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),
1293
+ });
1294
+ },
1295
+ });
1296
const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);
1297
1387
- const pushPaletteView = useCallback(
1388
- (view: CommandPaletteView): void => {
1389
- browseNavigation.invalidate();
1390
- setViewStack((previousViews) => [
1391
- ...previousViews,
1392
- {
1393
- addonIcon: view.addonIcon,
1394
- groups: view.groups,
1395
- ...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
1396
- },
1397
- ]);
1398
- highlightClearedRef.current = true;
1399
- setHighlightedItemValue(null);
1400
- setQuery(view.initialQuery ?? "");
1401
- },
1402
- [browseNavigation],
1403
- );
1298
+ // Stable so the item builders that capture it during render never see the
1299
+ // highlight ref it writes.
1300
+ const pushPaletteView = useStableCallback((view: CommandPaletteView): void => {
1301
+ browseNavigation.invalidate();
1302
+ setViewStack((previousViews) => [
1303
+ ...previousViews,
1304
+ {
1305
+ addonIcon: view.addonIcon,
1306
+ groups: view.groups,
1307
+ ...(view.initialQuery ? { initialQuery: view.initialQuery } : {}),
1308
+ },
1309
+ ]);
1310
+ highlightClearedRef.current = true;
1311
+ setHighlightedItemValue(null);
1312
+ setQuery(view.initialQuery ?? "");
1313
+ });
1314
1315
function pushView(item: CommandPaletteSubmenuItem): void {
1316
pushPaletteView({
@@ -1433,227 +1343,195 @@ function OpenCommandPaletteDialog(props: {
1343
}
1344
}
1345
1436
- const startAddProjectBrowse = useCallback(
1437
- async (environmentId: EnvironmentId): Promise<void> => {
1438
- const initialQuery = getAddProjectInitialQueryForEnvironment(environmentId);
1439
- const initialBrowsePath = getBrowseDirectoryPath(initialQuery);
1440
- const browseCwd = getBrowseCwdForEnvironment(environmentId);
1441
- const view: CommandPaletteView = {
1442
- addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
1443
- groups: [],
1444
- initialQuery,
1445
- };
1346
+ const startAddProjectBrowse = async (environmentId: EnvironmentId): Promise<void> => {
1347
+ const initialQuery = getAddProjectInitialQueryForEnvironment(environmentId);
1348
+ const initialBrowsePath = getBrowseDirectoryPath(initialQuery);
1349
+ const browseCwd = getBrowseCwdForEnvironment(environmentId);
1350
+ const view: CommandPaletteView = {
1351
+ addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
1352
+ groups: [],
1353
+ initialQuery,
1354
+ };
1355
1447
- await browseNavigation.run(
1448
- () =>
1449
- initialBrowsePath.length > 0
1450
- ? prefetchBrowsePath(initialBrowsePath, environmentId, browseCwd)
1451
- : Promise.resolve(),
1452
- () => {
1453
- setAddProjectEnvironmentId(environmentId);
1454
- setAddProjectCloneFlow(null);
1455
- pushPaletteView(view);
1456
- },
1457
- );
1458
- },
1459
- [
1460
- browseNavigation,
1461
- getAddProjectInitialQueryForEnvironment,
1462
- getBrowseCwdForEnvironment,
1463
- prefetchBrowsePath,
1464
- pushPaletteView,
1465
- ],
1466
- );
1356
+ await browseNavigation.run(
1357
+ () =>
1358
+ initialBrowsePath.length > 0
1359
+ ? prefetchBrowsePath(initialBrowsePath, environmentId, browseCwd)
1360
+ : Promise.resolve(),
1361
+ () => {
1362
+ setAddProjectEnvironmentId(environmentId);
1363
+ setAddProjectCloneFlow(null);
1364
+ pushPaletteView(view);
1365
+ },
1366
+ );
1367
+ };
1368
1468
- const startAddProjectClone = useCallback(
1469
- (environmentId: EnvironmentId, source: AddProjectRemoteSource): void => {
1470
- setAddProjectEnvironmentId(environmentId);
1471
- setAddProjectCloneFlow({ step: "repository", environmentId, source });
1472
- pushPaletteView({
1473
- addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
1474
- groups: [],
1475
- initialQuery: "",
1476
- });
1477
- },
1478
- [pushPaletteView],
1479
- );
1369
+ const startAddProjectClone = (
1370
+ environmentId: EnvironmentId,
1371
+ source: AddProjectRemoteSource,
1372
+ ): void => {
1373
+ setAddProjectEnvironmentId(environmentId);
1374
+ setAddProjectCloneFlow({ step: "repository", environmentId, source });
1375
+ pushPaletteView({
1376
+ addonIcon: remoteProjectSourceIcon(source, ADDON_ICON_CLASS),
1377
+ groups: [],
1378
+ initialQuery: "",
1379
+ });
1380
+ };
1381
1481
- const newProjectsRootFor = useCallback(
1482
- (environmentId: EnvironmentId | null): string | null =>
1483
- environments.find((environment) => environment.environmentId === environmentId)?.serverConfig
1484
- ?.newProjectsRoot ?? null,
1485
- [environments],
1486
- );
1382
+ const newProjectsRootFor = (environmentId: EnvironmentId | null): string | null =>
1383
+ environments.find((environment) => environment.environmentId === environmentId)?.serverConfig
1384
+ ?.newProjectsRoot ?? null;
1385
1488
- const startNewProject = useCallback(
1489
- (environmentId: EnvironmentId, sourcesEnvironmentId: EnvironmentId | null): void => {
1490
- setAddProjectEnvironmentId(environmentId);
1491
- setAddProjectCloneFlow(null);
1492
- setNewProjectFlow({ environmentId, sourcesEnvironmentId });
1493
- setNewProjectPublishes(false);
1494
- setNewProjectPublishKind(null);
1495
- pushPaletteView({
1496
- addonIcon: <FolderGit2Icon className={ADDON_ICON_CLASS} />,
1497
- groups: [],
1498
- });
1499
- },
1500
- [pushPaletteView],
1501
- );
1386
+ const startNewProject = (
1387
+ environmentId: EnvironmentId,
1388
+ sourcesEnvironmentId: EnvironmentId | null,
1389
+ ): void => {
1390
+ setAddProjectEnvironmentId(environmentId);
1391
+ setAddProjectCloneFlow(null);
1392
+ setNewProjectFlow({ environmentId, sourcesEnvironmentId });
1393
+ setNewProjectPublishes(false);
1394
+ setNewProjectPublishKind(null);
1395
+ pushPaletteView({
1396
+ addonIcon: <FolderGit2Icon className={ADDON_ICON_CLASS} />,
1397
+ groups: [],
1398
+ });
1399
+ };
1400
1503
- const openSourceControlSettings = useCallback(() => {
1401
+ const openSourceControlSettings = () => {
1402
setOpen(false);
1403
void navigate({ to: "/settings/source-control" });
1506
- }, [navigate, setOpen]);
1507
-
1508
- const buildAddProjectSourceGroups = useCallback(
1509
- (
1510
- environmentId: EnvironmentId,
1511
- readinessBySource: AddProjectRemoteSourceReadiness,
1512
- ): CommandPaletteView["groups"] => {
1513
- const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [
1514
- {
1515
- kind: "action",
1516
- value: `action:add-project:${environmentId}:local`,
1517
- searchTerms: ["local", "folder", "directory", "browse"],
1518
- title: "Local folder",
1519
- description: "Browse a folder on disk",
1520
- icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
1521
- keepOpen: true,
1522
- run: async () => {
1523
- await startAddProjectBrowse(environmentId);
1524
- },
1404
+ };
1405
+
1406
+ const buildAddProjectSourceGroups = (
1407
+ environmentId: EnvironmentId,
1408
+ readinessBySource: AddProjectRemoteSourceReadiness,
1409
+ ): CommandPaletteView["groups"] => {
1410
+ const sourceItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [
1411
+ {
1412
+ kind: "action",
1413
+ value: `action:add-project:${environmentId}:local`,
1414
+ searchTerms: ["local", "folder", "directory", "browse"],
1415
+ title: "Local folder",
1416
+ description: "Browse a folder on disk",
1417
+ icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
1418
+ keepOpen: true,
1419
+ run: async () => {
1420
+ await startAddProjectBrowse(environmentId);
1421
},
1526
- ];
1422
+ },
1423
+ ];
1424
1528
- if (newProjectsRootFor(environmentId) !== null) {
1529
- sourceItems.unshift({
1530
- kind: "action",
1531
- value: `action:add-project:${environmentId}:new`,
1532
- searchTerms: ["new project", "create", "empty", "repository", "git init"],
1533
- title: "New project",
1534
- description: "Start a new Git repository from a name",
1535
- icon: <FolderGit2Icon className={ITEM_ICON_CLASS} />,
1536
- keepOpen: true,
1537
- run: async () => {
1538
- startNewProject(environmentId, environmentId);
1539
- },
1540
- });
1541
- }
1425
+ if (newProjectsRootFor(environmentId) !== null) {
1426
+ sourceItems.unshift({
1427
+ kind: "action",
1428
+ value: `action:add-project:${environmentId}:new`,
1429
+ searchTerms: ["new project", "create", "empty", "repository", "git init"],
1430
+ title: "New project",
1431
+ description: "Start a new Git repository from a name",
1432
+ icon: <FolderGit2Icon className={ITEM_ICON_CLASS} />,
1433
+ keepOpen: true,
1434
+ run: async () => {
1435
+ startNewProject(environmentId, environmentId);
1436
+ },
1437
+ });
1438
+ }
1439
1543
- const orderedSources: ReadonlyArray<AddProjectRemoteSource> = [
1544
- "url",
1545
- ...sortAddProjectProviderSources(readinessBySource),
1546
- ];
1547
-
1548
- for (const source of orderedSources) {
1549
- const label = addProjectRemoteSourceLabel(source);
1550
- const title = source === "url" ? "Git URL" : `${label} repository`;
1551
- const description =
1552
- source === "url"
1553
- ? "Clone from a remote URL"
1554
- : `Clone ${label} ${addProjectRemoteSourcePathHint(source)}`;
1555
- const readiness = readinessBySource(source);
1556
- const disabledHint = readiness.hint;
1557
-
1558
- const titleTrailingContent = readiness.ready ? undefined : (
1559
- <span className="ml-auto">
1560
- <Tooltip>
1561
- <TooltipTrigger
1562
- render={
1563
- <Button
1564
- variant="warning-outline"
1565
- size="micro"
1566
- onClick={() => {
1567
- openSourceControlSettings();
1568
- }}
1569
- >
1570
- Setup Required
1571
- </Button>
1572
- }
1573
- />
1574
- <TooltipPopup align="end" side="left">
1575
- {disabledHint ?? "Open Settings -> Source Control to configure this provider."}
1576
- </TooltipPopup>
1577
- </Tooltip>
1578
- </span>
1579
- );
1440
+ const orderedSources: ReadonlyArray<AddProjectRemoteSource> = [
1441
+ "url",
1442
+ ...sortAddProjectProviderSources(readinessBySource),
1443
+ ];
1444
1581
- if (!readiness.ready) {
1582
- sourceItems.push({
1583
- kind: "action",
1584
- value: `action:add-project:${environmentId}:${source}:not-ready`,
1585
- searchTerms: ["clone", "remote", "repository", "repo", "git", label, "setup required"],
1586
- title,
1587
- description,
1588
- disabled: true,
1589
- icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
1590
- ...(titleTrailingContent ? { titleTrailingContent } : {}),
1591
- run: async () => {},
1592
- });
1593
- continue;
1594
- }
1445
+ for (const source of orderedSources) {
1446
+ const label = addProjectRemoteSourceLabel(source);
1447
+ const title = source === "url" ? "Git URL" : `${label} repository`;
1448
+ const description =
1449
+ source === "url"
1450
+ ? "Clone from a remote URL"
1451
+ : `Clone ${label} ${addProjectRemoteSourcePathHint(source)}`;
1452
+ const readiness = readinessBySource(source);
1453
+ const disabledHint = readiness.hint;
1454
+
1455
+ const titleTrailingContent = readiness.ready ? undefined : (
1456
+ <span className="ml-auto">
1457
+ <Tooltip>
1458
+ <TooltipTrigger
1459
+ render={
1460
+ <Button
1461
+ variant="warning-outline"
1462
+ size="micro"
1463
+ onClick={() => {
1464
+ openSourceControlSettings();
1465
+ }}
1466
+ >
1467
+ Setup Required
1468
+ </Button>
1469
+ }
1470
+ />
1471
+ <TooltipPopup align="end" side="left">
1472
+ {disabledHint ?? "Open Settings -> Source Control to configure this provider."}
1473
+ </TooltipPopup>
1474
+ </Tooltip>
1475
+ </span>
1476
+ );
1477
1478
+ if (!readiness.ready) {
1479
sourceItems.push({
1480
kind: "action",
1598
- value: `action:add-project:${environmentId}:${source}`,
1599
- searchTerms: ["clone", "remote", "repository", "repo", "git", label],
1481
+ value: `action:add-project:${environmentId}:${source}:not-ready`,
1482
+ searchTerms: ["clone", "remote", "repository", "repo", "git", label, "setup required"],
1483
title,
1484
description,
1485
+ disabled: true,
1486
icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
1487
...(titleTrailingContent ? { titleTrailingContent } : {}),
1604
- keepOpen: true,
1605
- run: async () => {
1606
- startAddProjectClone(environmentId, source);
1607
- },
1488
+ run: async () => {},
1489
});
1490
+ continue;
1491
}
1492
1611
- return [{ value: `sources:${environmentId}`, label: "Sources", items: sourceItems }];
1612
- },
1613
- [
1614
- newProjectsRootFor,
1615
- openSourceControlSettings,
1616
- startAddProjectBrowse,
1617
- startAddProjectClone,
1618
- startNewProject,
1619
- ],
1620
- );
1493
+ sourceItems.push({
1494
+ kind: "action",
1495
+ value: `action:add-project:${environmentId}:${source}`,
1496
+ searchTerms: ["clone", "remote", "repository", "repo", "git", label],
1497
+ title,
1498
+ description,
1499
+ icon: remoteProjectSourceIcon(source, ITEM_ICON_CLASS),
1500
+ ...(titleTrailingContent ? { titleTrailingContent } : {}),
1501
+ keepOpen: true,
1502
+ run: async () => {
1503
+ startAddProjectClone(environmentId, source);
1504
+ },
1505
+ });
1506
+ }
1507
1622
- const startAddProjectSourceSelection = useCallback(
1623
- (environmentId: EnvironmentId): void => {
1624
- const environment = environments.find(
1625
- (candidate) => candidate.environmentId === environmentId,
1508
+ return [{ value: `sources:${environmentId}`, label: "Sources", items: sourceItems }];
1509
+ };
1510
+
1511
+ const startAddProjectSourceSelection = (environmentId: EnvironmentId): void => {
1512
+ const environment = environments.find((candidate) => candidate.environmentId === environmentId);
1513
+ if (!canCreateProjectInEnvironment(environment?.connection.phase)) {
1514
+ toastManager.add(
1515
+ stackedThreadToast({
1516
+ type: "error",
1517
+ title: "Environment unavailable",
1518
+ description: `${environment?.label ?? "The selected environment"} is not connected.`,
1519
+ }),
1520
);
1627
- if (!canCreateProjectInEnvironment(environment?.connection.phase)) {
1628
- toastManager.add(
1629
- stackedThreadToast({
1630
- type: "error",
1631
- title: "Environment unavailable",
1632
- description: `${environment?.label ?? "The selected environment"} is not connected.`,
1633
- }),
1634
- );
1635
- return;
1636
- }
1637
- setAddProjectEnvironmentId(environmentId);
1638
- setAddProjectCloneFlow(null);
1639
- pushPaletteView({
1640
- addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
1641
- groups: buildAddProjectSourceGroups(
1642
- environmentId,
1643
- buildPaletteRemoteSourceReadiness(
1644
- browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null,
1645
- ),
1521
+ return;
1522
+ }
1523
+ setAddProjectEnvironmentId(environmentId);
1524
+ setAddProjectCloneFlow(null);
1525
+ pushPaletteView({
1526
+ addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
1527
+ groups: buildAddProjectSourceGroups(
1528
+ environmentId,
1529
+ buildPaletteRemoteSourceReadiness(
1530
+ browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null,
1531
),
1647
- });
1648
- },
1649
- [
1650
- browseEnvironmentId,
1651
- buildAddProjectSourceGroups,
1652
- environments,
1653
- pushPaletteView,
1654
- sourceControlDiscovery.data,
1655
- ],
1656
- );
1532
+ ),
1533
+ });
1534
+ };
1535
1536
const buildEnvironmentItem = (
1537
option: AddProjectEnvironmentOption,
@@ -1687,18 +1565,15 @@ function OpenCommandPaletteDialog(props: {
1565
(option) => option.isConnected && newProjectsRootFor(option.environmentId) !== null,
1566
);
1567
1690
- const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(
1691
- () => [
1692
- {
1693
- value: "environments",
1694
- label: "Environments",
1695
- items: addProjectEnvironmentItems,
1696
- },
1697
- ],
1698
- [addProjectEnvironmentItems],
1699
- );
1568
+ const addProjectEnvironmentGroups = [
1569
+ {
1570
+ value: "environments",
1571
+ label: "Environments",
1572
+ items: addProjectEnvironmentItems,
1573
+ },
1574
+ ];
1575
1701
- const openAddProjectFlow = useCallback(() => {
1576
+ const openAddProjectFlow = () => {
1577
if (addProjectEnvironmentOptions.length === 0) {
1578
setOpen(false);
1579
void navigate({ to: "/settings/connections" });
@@ -1714,58 +1589,13 @@ function OpenCommandPaletteDialog(props: {
1589
}
1590
1591
void startAddProjectSourceSelection(defaultAddProjectEnvironmentId);
1717
- }, [
1718
- addProjectEnvironmentGroups,
1719
- addProjectEnvironmentOptions.length,
1720
- defaultAddProjectEnvironmentId,
1721
- navigate,
1722
- pushPaletteView,
1723
- setOpen,
1724
- startAddProjectSourceSelection,
1725
- ]);
1592
+ };
1593
1594
const openNewProjectFlow = () => {
1595
const firstOption = newProjectEnvironmentOptions[0];
1596
if (firstOption) startNewProject(firstOption.environmentId, null);
1597
};
1598
1732
- useLayoutEffect(() => {
1733
- if (openIntent?.kind !== "search") return;
1734
- browseNavigation.invalidate();
1735
- cloneLookupGeneration.current += 1;
1736
- setIsRemoteProjectLookingUp(false);
1737
- setAddProjectCloneFlow(null);
1738
- setNewProjectFlow(null);
1739
- setViewStack([]);
1740
- setLinkedThreadSearch(openIntent);
1741
- setQuery(openIntent.query);
1742
- clearOpenIntent();
1743
- }, [browseNavigation, clearOpenIntent, openIntent]);
1744
-
1745
- useLayoutEffect(() => {
1746
- if (openIntent?.kind !== "add-project") {
1747
- return;
1748
- }
1749
- clearOpenIntent();
1750
- openAddProjectFlow();
1751
- }, [clearOpenIntent, openAddProjectFlow, openIntent]);
1752
-
1753
- useLayoutEffect(() => {
1754
- if (openIntent?.kind !== "new-thread-in" || projectThreadItems.length === 0) {
1755
- return;
1756
- }
1757
- clearOpenIntent();
1758
- browseNavigation.invalidate();
1759
- setAddProjectCloneFlow(null);
1760
- setNewProjectFlow(null);
1761
- setViewStack([]);
1762
- setQuery("");
1763
- pushPaletteView({
1764
- addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
1765
- groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
1766
- });
1767
- }, [clearOpenIntent, browseNavigation, openIntent, projectThreadItems, pushPaletteView]);
1768
-
1599
const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];
1600
1601
if (projects.length > 0) {
@@ -2128,20 +1958,60 @@ function OpenCommandPaletteDialog(props: {
1958
};
1959
actionItems.push(changeAppearanceItem);
1960
1961
+ // The parent pushes an intent into this mounted dialog; applying it clears the
1962
+ // parent's intent and may navigate, so it runs after commit but before paint.
1963
+ const projectThreadItemCount = projectThreadItems.length;
1964
+ const applyOpenIntent = useEffectEvent((intent: CommandPaletteOpenIntent) => {
1965
+ switch (intent.kind) {
1966
+ case "search":
1967
+ browseNavigation.invalidate();
1968
+ cloneLookupGeneration.current += 1;
1969
+ setIsRemoteProjectLookingUp(false);
1970
+ setAddProjectCloneFlow(null);
1971
+ setNewProjectFlow(null);
1972
+ setViewStack([]);
1973
+ setLinkedThreadSearch(intent);
1974
+ setQuery(intent.query);
1975
+ clearOpenIntent();
1976
+ return;
1977
+ case "add-project":
1978
+ clearOpenIntent();
1979
+ openAddProjectFlow();
1980
+ return;
1981
+ case "new-thread-in":
1982
+ clearOpenIntent();
1983
+ browseNavigation.invalidate();
1984
+ setAddProjectCloneFlow(null);
1985
+ setNewProjectFlow(null);
1986
+ setViewStack([]);
1987
+ setQuery("");
1988
+ pushPaletteView({
1989
+ addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,
1990
+ groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],
1991
+ });
1992
+ return;
1993
+ case "change-theme":
1994
+ clearOpenIntent();
1995
+ browseNavigation.invalidate();
1996
+ cloneLookupGeneration.current += 1;
1997
+ setIsRemoteProjectLookingUp(false);
1998
+ setAddProjectCloneFlow(null);
1999
+ setNewProjectFlow(null);
2000
+ setViewStack([]);
2001
+ pushPaletteView({
2002
+ addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />,
2003
+ groups: [{ value: "themes", label: "Change theme", items: [] }],
2004
+ });
2005
+ return;
2006
+ }
2007
+ });
2008
useLayoutEffect(() => {
2132
- if (openIntent?.kind !== "change-theme") return;
2133
- clearOpenIntent();
2134
- browseNavigation.invalidate();
2135
- cloneLookupGeneration.current += 1;
2136
- setIsRemoteProjectLookingUp(false);
2137
- setAddProjectCloneFlow(null);
2138
- setNewProjectFlow(null);
2139
- setViewStack([]);
2140
- pushPaletteView({
2141
- addonIcon: <PaletteIcon className={ADDON_ICON_CLASS} />,
2142
- groups: [{ value: "themes", label: "Change theme", items: [] }],
2143
- });
2144
- }, [browseNavigation, clearOpenIntent, openIntent, pushPaletteView]);
2009
+ if (openIntent === null) return;
2010
+ // A new-thread-in intent waits until the project items exist.
2011
+ if (openIntent.kind === "new-thread-in" && projectThreadItemCount === 0) return;
2012
+ // oxlint-disable-next-line react/set-state-in-effect -- applying the intent dispatches to the parent reducer and can navigate, neither of which may run during render.
2013
+ applyOpenIntent(openIntent);
2014
+ }, [openIntent, projectThreadItemCount]);
2015
2016
actionItems.push({
2017
kind: "action",
@@ -2295,130 +2165,113 @@ function OpenCommandPaletteDialog(props: {
2165
: allThreadItems,
2166
});
2167
2298
- const handleAddProjectForEnvironment = useCallback(
2299
- async (input: {
2300
- readonly environmentId: EnvironmentId;
2301
- readonly rawCwd: string;
2302
- readonly platform: string;
2303
- readonly currentProjectCwd: string | null;
2304
- }) => {
2305
- const environment = environments.find(
2306
- (candidate) => candidate.environmentId === input.environmentId,
2168
+ const handleAddProjectForEnvironment = async (input: {
2169
+ readonly environmentId: EnvironmentId;
2170
+ readonly rawCwd: string;
2171
+ readonly platform: string;
2172
+ readonly currentProjectCwd: string | null;
2173
+ }) => {
2174
+ const environment = environments.find(
2175
+ (candidate) => candidate.environmentId === input.environmentId,
2176
+ );
2177
+ if (!canCreateProjectInEnvironment(environment?.connection.phase)) {
2178
+ toastManager.add(
2179
+ stackedThreadToast({
2180
+ type: "error",
2181
+ title: "Environment unavailable",
2182
+ description: `${environment?.label ?? "The selected environment"} is not connected.`,
2183
+ }),
2184
);
2308
- if (!canCreateProjectInEnvironment(environment?.connection.phase)) {
2309
- toastManager.add(
2310
- stackedThreadToast({
2311
- type: "error",
2312
- title: "Environment unavailable",
2313
- description: `${environment?.label ?? "The selected environment"} is not connected.`,
2314
- }),
2315
- );
2316
- return;
2317
- }
2318
- const rawCwd = input.rawCwd;
2185
+ return;
2186
+ }
2187
+ const rawCwd = input.rawCwd;
2188
2320
- if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) {
2321
- toastManager.add(
2322
- stackedThreadToast({
2323
- type: "error",
2324
- title: "Failed to add project",
2325
- description: "Windows-style paths are only supported on Windows.",
2326
- }),
2327
- );
2328
- return;
2329
- }
2189
+ if (isUnsupportedWindowsProjectPath(rawCwd.trim(), input.platform)) {
2190
+ toastManager.add(
2191
+ stackedThreadToast({
2192
+ type: "error",
2193
+ title: "Failed to add project",
2194
+ description: "Windows-style paths are only supported on Windows.",
2195
+ }),
2196
+ );
2197
+ return;
2198
+ }
2199
2331
- if (isExplicitRelativeProjectPath(rawCwd.trim()) && !input.currentProjectCwd) {
2332
- toastManager.add(
2333
- stackedThreadToast({
2334
- type: "error",
2335
- title: "Failed to add project",
2336
- description: "Relative paths require an active project.",
2337
- }),
2338
- );
2339
- return;
2340
- }
2200
+ if (isExplicitRelativeProjectPath(rawCwd.trim()) && !input.currentProjectCwd) {
2201
+ toastManager.add(
2202
+ stackedThreadToast({
2203
+ type: "error",
2204
+ title: "Failed to add project",
2205
+ description: "Relative paths require an active project.",
2206
+ }),
2207
+ );
2208
+ return;
2209
+ }
2210
2342
- const cwd = resolveProjectPathForDispatch(rawCwd, input.currentProjectCwd);
2343
- if (cwd.length === 0) return;
2211
+ const cwd = resolveProjectPathForDispatch(rawCwd, input.currentProjectCwd);
2212
+ if (cwd.length === 0) return;
2213
2345
- const existing = findProjectByPath(
2346
- projects.filter((project) => project.environmentId === input.environmentId),
2347
- cwd,
2214
+ const existing = findProjectByPath(
2215
+ projects.filter((project) => project.environmentId === input.environmentId),
2216
+ cwd,
2217
+ );
2218
+ if (existing) {
2219
+ const latestThread = getLatestThreadForProject(
2220
+ threads.filter((thread) => thread.environmentId === existing.environmentId),
2221
+ existing.id,
2222
+ clientSettings.sidebarThreadSortOrder,
2223
);
2349
- if (existing) {
2350
- const latestThread = getLatestThreadForProject(
2351
- threads.filter((thread) => thread.environmentId === existing.environmentId),
2352
- existing.id,
2353
- clientSettings.sidebarThreadSortOrder,
2354
- );
2355
- if (latestThread && latestThread.settledOverride !== "settled") {
2356
- await navigate({
2357
- to: "/$environmentId/$threadId",
2358
- params: buildThreadRouteParams(
2359
- scopeThreadRef(latestThread.environmentId, latestThread.id),
2360
- ),
2361
- });
2362
- } else {
2363
- const navigationResult = await settlePromise(() =>
2364
- handleNewThread(scopeProjectRef(existing.environmentId, existing.id)),
2365
- );
2366
- if (navigationResult._tag === "Failure") {
2367
- const error = squashAtomCommandFailure(navigationResult);
2368
- toastManager.add(
2369
- stackedThreadToast({
2370
- type: "error",
2371
- title: "Failed to open project",
2372
- description: error instanceof Error ? error.message : "An error occurred.",
2373
- }),
2374
- );
2375
- return;
2376
- }
2377
- }
2378
- setOpen(false);
2379
- return;
2380
- }
2381
-
2382
- if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {
2383
- toastManager.add(
2384
- stackedThreadToast({
2385
- type: "error",
2386
- title: "Cannot add project",
2387
- description: "This connection cannot add projects.",
2388
- }),
2224
+ if (latestThread && latestThread.settledOverride !== "settled") {
2225
+ await navigate({
2226
+ to: "/$environmentId/$threadId",
2227
+ params: buildThreadRouteParams(
2228
+ scopeThreadRef(latestThread.environmentId, latestThread.id),
2229
+ ),
2230
+ });
2231
+ } else {
2232
+ const navigationResult = await settlePromise(() =>
2233
+ handleNewThread(scopeProjectRef(existing.environmentId, existing.id)),
2234
);
2390
- return;
2391
- }
2392
- const projectId = newProjectId();
2393
- const createResult = await createProject({
2394
- environmentId: input.environmentId,
2395
- input: {
2396
- projectId,
2397
- title: inferProjectTitleFromPath(cwd),
2398
- workspaceRoot: cwd,
2399
- createWorkspaceRootIfMissing: true,
2400
- defaultModelSelection: null,
2401
- },
2402
- });
2403
- if (createResult._tag === "Failure") {
2404
- if (!isAtomCommandInterrupted(createResult)) {
2405
- const error = squashAtomCommandFailure(createResult);
2235
+ if (navigationResult._tag === "Failure") {
2236
+ const error = squashAtomCommandFailure(navigationResult);
2237
toastManager.add(
2238
stackedThreadToast({
2239
type: "error",
2409
- title: "Failed to add project",
2240
+ title: "Failed to open project",
2241
description: error instanceof Error ? error.message : "An error occurred.",
2242
}),
2243
);
2244
+ return;
2245
}
2414
- return;
2246
}
2247
+ setOpen(false);
2248
+ return;
2249
+ }
2250
2417
- const navigationResult = await settlePromise(() =>
2418
- handleNewThread(scopeProjectRef(input.environmentId, projectId)),
2251
+ if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {
2252
+ toastManager.add(
2253
+ stackedThreadToast({
2254
+ type: "error",
2255
+ title: "Cannot add project",
2256
+ description: "This connection cannot add projects.",
2257
+ }),
2258
);
2420
- if (navigationResult._tag === "Failure") {
2421
- const error = squashAtomCommandFailure(navigationResult);
2259
+ return;
2260
+ }
2261
+ const projectId = newProjectId();
2262
+ const createResult = await createProject({
2263
+ environmentId: input.environmentId,
2264
+ input: {
2265
+ projectId,
2266
+ title: inferProjectTitleFromPath(cwd),
2267
+ workspaceRoot: cwd,
2268
+ createWorkspaceRootIfMissing: true,
2269
+ defaultModelSelection: null,
2270
+ },
2271
+ });
2272
+ if (createResult._tag === "Failure") {
2273
+ if (!isAtomCommandInterrupted(createResult)) {
2274
+ const error = squashAtomCommandFailure(createResult);
2275
toastManager.add(
2276
stackedThreadToast({
2277
type: "error",
@@ -2426,41 +2279,36 @@ function OpenCommandPaletteDialog(props: {
2279
description: error instanceof Error ? error.message : "An error occurred.",
2280
}),
2281
);
2429
- return;
2282
}
2431
- setOpen(false);
2432
- },
2433
- [
2434
- handleNewThread,
2435
- createProject,
2436
- environments,
2437
- navigate,
2438
- primaryEnvironmentId,
2439
- projects,
2440
- providers,
2441
- setOpen,
2442
- clientSettings.sidebarThreadSortOrder,
2443
- threads,
2444
- ],
2445
- );
2283
+ return;
2284
+ }
2285
2447
- const handleAddProject = useCallback(
2448
- async (rawCwd: string) => {
2449
- if (!browseEnvironmentId) return;
2450
- await handleAddProjectForEnvironment({
2451
- environmentId: browseEnvironmentId,
2452
- rawCwd,
2453
- platform: browseEnvironmentPlatform,
2454
- currentProjectCwd: currentProjectCwdForBrowse,
2455
- });
2456
- },
2457
- [
2458
- browseEnvironmentId,
2459
- browseEnvironmentPlatform,
2460
- currentProjectCwdForBrowse,
2461
- handleAddProjectForEnvironment,
2462
- ],
2463
- );
2286
+ const navigationResult = await settlePromise(() =>
2287
+ handleNewThread(scopeProjectRef(input.environmentId, projectId)),
2288
+ );
2289
+ if (navigationResult._tag === "Failure") {
2290
+ const error = squashAtomCommandFailure(navigationResult);
2291
+ toastManager.add(
2292
+ stackedThreadToast({
2293
+ type: "error",
2294
+ title: "Failed to add project",
2295
+ description: error instanceof Error ? error.message : "An error occurred.",
2296
+ }),
2297
+ );
2298
+ return;
2299
+ }
2300
+ setOpen(false);
2301
+ };
2302
+
2303
+ const handleAddProject = async (rawCwd: string) => {
2304
+ if (!browseEnvironmentId) return;
2305
+ await handleAddProjectForEnvironment({
2306
+ environmentId: browseEnvironmentId,
2307
+ rawCwd,
2308
+ platform: browseEnvironmentPlatform,
2309
+ currentProjectCwd: currentProjectCwdForBrowse,
2310
+ });
2311
+ };
2312
2313
const newProjectPublishTargets =
2314
newProjectFlow === null ? [] : getNewProjectPublishTargets(sourceControlDiscovery.data ?? null);
@@ -2481,17 +2329,18 @@ function OpenCommandPaletteDialog(props: {
2329
}
2330
newProjectSubmittingRef.current = true;
2331
setIsCreatingNewProject(true);
2484
- try {
2485
- const created = await createNewProject({
2332
+ const created = await settlePromise(() =>
2333
+ createNewProject({
2334
environmentId: newProjectFlow.environmentId,
2335
name: newProjectName,
2336
publishTo: newProjectPublishes ? newProjectPublishTarget : null,
2489
- });
2490
- if (created) setOpen(false);
2491
- } finally {
2492
- newProjectSubmittingRef.current = false;
2493
- setIsCreatingNewProject(false);
2494
- }
2337
+ }),
2338
+ );
2339
+ newProjectSubmittingRef.current = false;
2340
+ setIsCreatingNewProject(false);
2341
+ // Same outcome as the old try/finally: the rejection still surfaces to the caller.
2342
+ if (created._tag === "Failure") throw squashAtomCommandFailure(created);
2343
+ if (created.value) setOpen(false);
2344
}
2345
2346
function getDefaultCloneParentPath(environmentId: EnvironmentId): string {
@@ -2696,36 +2545,26 @@ function OpenCommandPaletteDialog(props: {
2545
}
2546
}
2547
2699
- const browseTo = useCallback(
2700
- async (name: string): Promise<void> => {
2701
- const nextQuery = pinnedCloneDirectoryName
2702
- ? getCloneDestinationBrowsePath({
2703
- browseDirectoryPath: browsePath.directoryPath,
2704
- selectedDirectoryName: name,
2705
- cloneDirectoryName: pinnedCloneDirectoryName,
2706
- caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform),
2707
- })
2708
- : appendBrowsePathSegment(query, name);
2709
- await browseNavigation.run(
2710
- () => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)),
2711
- () => {
2712
- setHighlightedItemValue(null);
2713
- setQuery(nextQuery);
2714
- setBrowseGeneration((generation) => generation + 1);
2715
- },
2716
- );
2717
- },
2718
- [
2719
- browseNavigation,
2720
- browseEnvironmentPlatform,
2721
- browsePath.directoryPath,
2722
- pinnedCloneDirectoryName,
2723
- prefetchBrowsePath,
2724
- query,
2725
- ],
2726
- );
2548
+ const browseTo = async (name: string): Promise<void> => {
2549
+ const nextQuery = pinnedCloneDirectoryName
2550
+ ? getCloneDestinationBrowsePath({
2551
+ browseDirectoryPath: browsePath.directoryPath,
2552
+ selectedDirectoryName: name,
2553
+ cloneDirectoryName: pinnedCloneDirectoryName,
2554
+ caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform),
2555
+ })
2556
+ : appendBrowsePathSegment(query, name);
2557
+ await browseNavigation.run(
2558
+ () => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)),
2559
+ () => {
2560
+ setHighlightedItemValue(null);
2561
+ setQuery(nextQuery);
2562
+ setBrowseGeneration((generation) => generation + 1);
2563
+ },
2564
+ );
2565
+ };
2566
2728
- const browseUp = useCallback(async (): Promise<void> => {
2567
+ const browseUp = async (): Promise<void> => {
2568
const parentPath = browsePath.parentPath;
2569
if (parentPath === null) {
2570
return;
@@ -2740,7 +2579,7 @@ function OpenCommandPaletteDialog(props: {
2579
setBrowseGeneration((generation) => generation + 1);
2580
},
2581
);
2743
- }, [browseNavigation, browsePath.parentPath, pinnedCloneDirectoryName, prefetchBrowsePath]);
2582
+ };
2583
2584
const resolvedAddProjectPath = hasTrailingPathSeparator(query)
2585
? (browseResult?.parentPath ?? query.trim())
@@ -2757,15 +2596,11 @@ function OpenCommandPaletteDialog(props: {
2596
browseUp,
2597
browseTo,
2598
});
2760
- const cloneDestinationBrowseGroups = useMemo(
2761
- () =>
2762
- browseGroups.map((group) =>
2763
- group.value === "directories" ? { ...group, label: "Select where to clone" } : group,
2764
- ),
2765
- [browseGroups],
2599
+ const cloneDestinationBrowseGroups = browseGroups.map((group) =>
2600
+ group.value === "directories" ? { ...group, label: "Select where to clone" } : group,
2601
);
2602
2768
- const remoteProjectContext = useMemo(() => {
2603
+ const remoteProjectContext = (() => {
2604
if (addProjectCloneFlow?.step !== "confirm") {
2605
return null;
2606
}
@@ -2775,7 +2610,7 @@ function OpenCommandPaletteDialog(props: {
2610
description: addProjectCloneFlow.repository?.url ?? addProjectCloneFlow.remoteUrl,
2611
icon: remoteProjectSourceIcon(addProjectCloneFlow.source, ITEM_ICON_CLASS),
2612
};
2778
- }, [addProjectCloneFlow]);
2613
+ })();
2614
2615
const newProjectsRoot = newProjectFlow ? newProjectsRootFor(newProjectFlow.environmentId) : null;
2616
const newProjectPathPreview =
@@ -3029,7 +2864,7 @@ function OpenCommandPaletteDialog(props: {
2864
(browseEnvironmentIsDesktopLocal && browseDesktopInstanceId !== null)) &&
2865
typeof window !== "undefined" &&
2866
window.desktopBridge !== undefined;
3032
- const fileManagerInitialPath = useMemo(() => {
2867
+ const fileManagerInitialPath = (() => {
2868
if (!canOpenProjectFromFileManager) {
2869
return undefined;
2870
}
@@ -3045,13 +2880,7 @@ function OpenCommandPaletteDialog(props: {
2880
2881
const resolvedPath = resolveProjectPathForDispatch(initialPath, currentProjectCwdForBrowse);
2882
return resolvedPath.length > 0 ? resolvedPath : undefined;
3048
- }, [
3049
- browseDirectoryPath,
3050
- browseResult?.parentPath,
3051
- canOpenProjectFromFileManager,
3052
- currentProjectCwdForBrowse,
3053
- query,
3054
- ]);
2883
+ })();
2884
2885
function isPrimaryModifierPressed(event: KeyboardEvent<HTMLInputElement>): boolean {
2886
return useMetaForMod ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
@@ -3193,7 +3022,7 @@ function OpenCommandPaletteDialog(props: {
3022
});
3023
}
3024
3196
- const handleOpenProjectFromFileManager = useCallback(async () => {
3025
+ const handleOpenProjectFromFileManager = async () => {
3026
if (!canOpenProjectFromFileManager || isPickingProjectFolder) {
3027
return;
3028
}
@@ -3236,7 +3065,9 @@ function OpenCommandPaletteDialog(props: {
3065
return;
3066
}
3067
if (parseWslUncPath(pickedPath)) {
3239
- desktopWslState ??= (await window.desktopBridge?.getWslState().catch(() => null)) ?? null;
3068
+ if (desktopWslState === null) {
3069
+ desktopWslState = (await window.desktopBridge?.getWslState().catch(() => null)) ?? null;
3070
+ }
3071
let primaryRunningDistro: string | null = null;
3072
try {
3073
primaryRunningDistro =
@@ -3284,19 +3115,7 @@ function OpenCommandPaletteDialog(props: {
3115
return;
3116
}
3117
await handleAddProject(pickedPath);
3287
- }, [
3288
- browseDesktopInstanceId,
3289
- browseEnvironmentId,
3290
- browseEnvironmentPlatform,
3291
- canOpenProjectFromFileManager,
3292
- desktopLocalBootstraps,
3293
- environments,
3294
- fileManagerInitialPath,
3295
- handleAddProject,
3296
- handleAddProjectForEnvironment,
3297
- isPickingProjectFolder,
3298
- primaryEnvironmentId,
3299
- ]);
3118
+ };
3119
3120
const inputAccessory =
3121
newProjectFlow !== null ? (