Show an error for missing project paths (#1490)

* Fix missing project paths flashing in the sidebar

* Log project lifecycle changes

* Address project picker review feedback

* Show project picker transport errors

* Inject session filesystem for workspace tests
This commit is contained in:
Mohamed Boudra
2026-06-12 23:42:21 +08:00
committed by GitHub
parent c4d544baf6
commit a929ea9726
20 changed files with 603 additions and 73 deletions
@@ -8,27 +8,57 @@ import {
View,
type PressableStateCallbackType,
} from "react-native";
import { Folder } from "lucide-react-native";
import { Folder, FolderPlus } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { useQuery } from "@tanstack/react-query";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { shortenPath } from "@/utils/shorten-path";
import { useRecommendedProjectPaths } from "@/stores/session-store-hooks";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useOpenProject } from "@/hooks/use-open-project";
import { buildWorkingDirectorySuggestions } from "@/utils/working-directory-suggestions";
import type { OpenProjectFailure, OpenProjectResult } from "@/hooks/open-project";
import { isNative } from "@/constants/platform";
import { useActiveServerId } from "@/hooks/use-active-server-id";
import {
buildProjectPickerOptions,
isOpenableProjectPath,
type ProjectPickerOption,
} from "./project-picker-options";
interface PathRowProps {
path: string;
option: ProjectPickerOption;
active: boolean;
openPathLabel: string;
onSelect: (path: string) => void;
}
function PathRow({ path, active, onSelect }: PathRowProps) {
type ProjectPickerErrorCode = NonNullable<OpenProjectFailure["errorCode"]>;
function getProjectPickerErrorMessage(
result: OpenProjectResult | undefined,
thrownError: Error | null,
translateErrorCode: (errorCode: ProjectPickerErrorCode) => string,
translateOpenFailed: () => string,
): string | null {
if (result?.ok === false) {
if (result.errorCode) {
return translateErrorCode(result.errorCode);
}
return result.error;
}
if (thrownError) {
return thrownError.message || translateOpenFailed();
}
return null;
}
function PathRow({ option, active, openPathLabel, onSelect }: PathRowProps) {
const { theme } = useUnistyles();
const Icon = option.kind === "path" ? FolderPlus : Folder;
const path = option.path;
const displayPath = shortenPath(path);
const label = option.kind === "path" ? `${openPathLabel}: ${displayPath}` : displayPath;
const handlePress = useCallback(() => {
onSelect(path);
}, [onSelect, path]);
@@ -49,10 +79,10 @@ function PathRow({ path, active, onSelect }: PathRowProps) {
<Pressable style={pressableStyle} onPress={handlePress}>
<View style={styles.rowContent}>
<View style={styles.iconSlot}>
<Folder size={16} strokeWidth={2.2} color={theme.colors.foregroundMuted} />
<Icon size={16} strokeWidth={2.2} color={theme.colors.foregroundMuted} />
</View>
<Text style={rowTextStyle} numberOfLines={1}>
{shortenPath(path)}
{label}
</Text>
</View>
</Pressable>
@@ -74,9 +104,25 @@ export function ProjectPickerModal() {
const inputRef = useRef<TextInput>(null);
const [query, setQuery] = useState("");
const [activeIndex, setActiveIndex] = useState(0);
const [isSubmitting, setIsSubmitting] = useState(false);
const openProject = useOpenProject(serverId);
const openProjectMutation = useMutation({
mutationFn: (path: string) => openProject(path),
onSuccess: (result) => {
if (result.ok) {
setOpen(false);
}
},
});
const { mutate: submitPath, reset: resetSubmit, isPending: isSubmitting } = openProjectMutation;
const submitResult = openProjectMutation.data;
const errorMessage = getProjectPickerErrorMessage(
submitResult,
openProjectMutation.error,
(errorCode) => t(`projectPicker.errors.${errorCode}`),
() => t("projectPicker.errors.open_failed"),
);
const directorySuggestionsQuery = useQuery({
queryKey: ["project-picker-directory-suggestions", serverId, query],
queryFn: async () => {
@@ -97,16 +143,11 @@ export function ProjectPickerModal() {
});
const options = useMemo(() => {
const suggestedPaths = buildWorkingDirectorySuggestions({
return buildProjectPickerOptions({
recommendedPaths,
serverPaths: directorySuggestionsQuery.data ?? [],
query,
});
const trimmedQuery = query.trim();
if (!trimmedQuery || suggestedPaths.includes(trimmedQuery)) {
return suggestedPaths;
}
return [trimmedQuery, ...suggestedPaths];
}, [query, directorySuggestionsQuery.data, recommendedPaths]);
const handleClose = useCallback(() => {
@@ -114,43 +155,41 @@ export function ProjectPickerModal() {
}, [setOpen]);
const handleSelectPath = useCallback(
async (path: string) => {
(path: string) => {
const trimmed = path.trim();
if (!trimmed || !client || !serverId) return;
setIsSubmitting(true);
try {
const didOpenProject = await openProject(trimmed);
if (didOpenProject) {
setOpen(false);
}
} finally {
setIsSubmitting(false);
}
submitPath(trimmed);
},
[client, openProject, serverId, setOpen],
[client, serverId, submitPath],
);
const handleSubmitCustom = useCallback(() => {
const trimmed = query.trim();
if (!trimmed) return;
void handleSelectPath(trimmed);
if (!isOpenableProjectPath(trimmed)) return;
handleSelectPath(trimmed);
}, [handleSelectPath, query]);
const handleChangeQuery = useCallback((text: string) => {
setQuery(text);
setActiveIndex(0);
}, []);
const handleChangeQuery = useCallback(
(text: string) => {
setQuery(text);
setActiveIndex(0);
resetSubmit();
},
[resetSubmit],
);
// Reset state when opening/closing
useEffect(() => {
if (open) {
setQuery("");
setActiveIndex(0);
const id = setTimeout(() => inputRef.current?.focus(), 0);
return () => clearTimeout(id);
resetSubmit();
if (!open) {
return;
}
}, [open]);
setQuery("");
setActiveIndex(0);
const id = setTimeout(() => inputRef.current?.focus(), 0);
return () => clearTimeout(id);
}, [open, resetSubmit]);
// Clamp active index
useEffect(() => {
@@ -170,14 +209,14 @@ export function ProjectPickerModal() {
if (key === "Escape") {
event.preventDefault();
setOpen(false);
handleClose();
return;
}
if (key === "Enter") {
event.preventDefault();
if (options.length > 0 && activeIndex < options.length) {
void handleSelectPath(options[activeIndex]);
handleSelectPath(options[activeIndex].path);
} else if (query.trim()) {
handleSubmitCustom();
}
@@ -199,7 +238,7 @@ export function ProjectPickerModal() {
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
}, [activeIndex, handleSelectPath, handleSubmitCustom, open, options, query, setOpen]);
}, [activeIndex, handleClose, handleSelectPath, handleSubmitCustom, open, options, query]);
const panelStyle = useMemo(
() => [
@@ -219,6 +258,10 @@ export function ProjectPickerModal() {
() => [styles.input, { color: theme.colors.foreground }],
[theme.colors.foreground],
);
const errorTextStyle = useMemo(
() => [styles.errorText, { color: theme.colors.destructive }],
[theme.colors.destructive],
);
const emptyTextStyle = useMemo(
() => [styles.emptyText, { color: theme.colors.foregroundMuted }],
[theme.colors.foregroundMuted],
@@ -247,6 +290,7 @@ export function ProjectPickerModal() {
returnKeyType="go"
onSubmitEditing={handleSubmitCustom}
/>
{errorMessage ? <Text style={errorTextStyle}>{errorMessage}</Text> : null}
</View>
<ScrollView
@@ -256,16 +300,17 @@ export function ProjectPickerModal() {
showsVerticalScrollIndicator={false}
>
{isSubmitting ? <Text style={emptyTextStyle}>{t("projectPicker.opening")}</Text> : null}
{!isSubmitting && options.length === 0 && !query.trim() ? (
{!isSubmitting && options.length === 0 ? (
<Text style={emptyTextStyle}>{t("projectPicker.empty")}</Text>
) : null}
{!isSubmitting && !(options.length === 0 && !query.trim()) ? (
{!isSubmitting && options.length > 0 ? (
<>
{options.map((path, index) => (
{options.map((option, index) => (
<PathRow
key={path}
path={path}
key={`${option.kind}:${option.path}`}
option={option}
active={index === activeIndex}
openPathLabel={t("projectPicker.openPath")}
onSelect={handleSelectPath}
/>
))}
@@ -308,6 +353,11 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[1],
outlineStyle: "none",
} as object,
errorText: {
marginTop: theme.spacing[2],
fontSize: theme.fontSize.sm,
lineHeight: 18,
},
results: {
flexGrow: 0,
},
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import { buildProjectPickerOptions, isOpenableProjectPath } from "./project-picker-options";
describe("isOpenableProjectPath", () => {
it("accepts POSIX, tilde, Windows drive-letter, and UNC paths", () => {
expect(isOpenableProjectPath("/repo")).toBe(true);
expect(isOpenableProjectPath("~/src")).toBe(true);
expect(isOpenableProjectPath("C:\\Users\\mo")).toBe(true);
expect(isOpenableProjectPath("c:/users/mo")).toBe(true);
expect(isOpenableProjectPath("\\\\server\\share")).toBe(true);
});
it("rejects relative input", () => {
expect(isOpenableProjectPath("repo")).toBe(false);
expect(isOpenableProjectPath("repo/sub")).toBe(false);
expect(isOpenableProjectPath("c:repo")).toBe(false);
expect(isOpenableProjectPath("")).toBe(false);
});
});
describe("buildProjectPickerOptions", () => {
it("does not create an open-path row for word queries", () => {
const options = buildProjectPickerOptions({
recommendedPaths: ["/repo/api"],
serverPaths: ["/repo/app"],
query: "repo",
});
expect(options).toEqual([
{ kind: "suggestion", path: "/repo/api" },
{ kind: "suggestion", path: "/repo/app" },
]);
});
it("puts an absolute path row first", () => {
const options = buildProjectPickerOptions({
recommendedPaths: ["/repo/api"],
serverPaths: [],
query: "/repo",
});
expect(options).toEqual([
{ kind: "path", path: "/repo" },
{ kind: "suggestion", path: "/repo/api" },
]);
});
it("puts a home-relative path row first", () => {
const options = buildProjectPickerOptions({
recommendedPaths: ["/Users/mo/src/api"],
serverPaths: [],
query: "~/src",
});
expect(options).toEqual([
{ kind: "path", path: "~/src" },
{ kind: "suggestion", path: "/Users/mo/src/api" },
]);
});
it("creates an open-path row for Windows paths", () => {
const options = buildProjectPickerOptions({
recommendedPaths: [],
serverPaths: [],
query: "C:\\Users\\mo\\src",
});
expect(options).toEqual([{ kind: "path", path: "C:\\Users\\mo\\src" }]);
});
it("does not duplicate an existing suggestion", () => {
const options = buildProjectPickerOptions({
recommendedPaths: ["/repo/api"],
serverPaths: ["/repo/app"],
query: "/repo/app",
});
expect(options).toEqual([{ kind: "suggestion", path: "/repo/app" }]);
});
});
@@ -0,0 +1,48 @@
import { buildWorkingDirectorySuggestions } from "@/utils/working-directory-suggestions";
export interface BuildProjectPickerOptionsInput {
recommendedPaths: string[];
serverPaths: string[];
query: string;
}
export interface ProjectPickerPathOption {
kind: "path";
path: string;
}
export interface ProjectPickerSuggestionOption {
kind: "suggestion";
path: string;
}
export type ProjectPickerOption = ProjectPickerPathOption | ProjectPickerSuggestionOption;
// Matches the daemon's filesystem semantics, not the client's: POSIX absolute,
// tilde, Windows drive letter (C:\ or C:/), or UNC (\\server\share).
export function isOpenableProjectPath(query: string): boolean {
const trimmedQuery = query.trim();
return (
trimmedQuery.startsWith("/") ||
trimmedQuery.startsWith("~") ||
trimmedQuery.startsWith("\\\\") ||
/^[a-zA-Z]:[\\/]/.test(trimmedQuery)
);
}
export function buildProjectPickerOptions(
input: BuildProjectPickerOptionsInput,
): ProjectPickerOption[] {
const suggestedPaths = buildWorkingDirectorySuggestions(input);
const suggestions = suggestedPaths.map<ProjectPickerSuggestionOption>((path) => ({
kind: "suggestion",
path,
}));
const trimmedQuery = input.query.trim();
if (!isOpenableProjectPath(trimmedQuery) || suggestedPaths.includes(trimmedQuery)) {
return suggestions;
}
return [{ kind: "path", path: trimmedQuery }, ...suggestions];
}
+27 -5
View File
@@ -1,7 +1,23 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { OpenProjectResponseMessage } from "@getpaseo/protocol/messages";
import { normalizeWorkspaceDescriptor, type WorkspaceDescriptor } from "@/stores/session-store";
import { buildWorkspaceTabPersistenceKey } from "@/stores/workspace-tabs-store";
type OpenProjectPayload = OpenProjectResponseMessage["payload"];
type OpenProjectErrorCode = NonNullable<OpenProjectPayload["errorCode"]>;
export interface OpenProjectSuccess {
ok: true;
}
export interface OpenProjectFailure {
ok: false;
errorCode: OpenProjectErrorCode | null;
error: string | null;
}
export type OpenProjectResult = OpenProjectSuccess | OpenProjectFailure;
export interface OpenProjectDirectlyInput {
serverId: string;
projectPath: string;
@@ -13,16 +29,22 @@ export interface OpenProjectDirectlyInput {
navigateToWorkspace: (serverId: string, workspaceId: string) => void;
}
export async function openProjectDirectly(input: OpenProjectDirectlyInput): Promise<boolean> {
export async function openProjectDirectly(
input: OpenProjectDirectlyInput,
): Promise<OpenProjectResult> {
const normalizedServerId = input.serverId.trim();
const trimmedPath = input.projectPath.trim();
if (!normalizedServerId || !trimmedPath || !input.client || !input.isConnected) {
return false;
return { ok: false, errorCode: null, error: null };
}
const payload = await input.client.openProject(trimmedPath);
if (payload.error || !payload.workspace) {
return false;
return {
ok: false,
errorCode: payload.errorCode ?? null,
error: payload.error,
};
}
const workspace = normalizeWorkspaceDescriptor(payload.workspace);
@@ -34,10 +56,10 @@ export async function openProjectDirectly(input: OpenProjectDirectlyInput): Prom
workspaceId: workspace.id,
});
if (!workspaceKey) {
return false;
return { ok: false, errorCode: null, error: null };
}
input.openDraftTab(workspaceKey);
input.navigateToWorkspace(normalizedServerId, workspace.id);
return true;
return { ok: true };
}
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import { openProjectDirectly } from "@/hooks/open-project";
import type { WorkspaceDescriptor } from "@/stores/session-store";
@@ -91,11 +91,11 @@ describe("openProjectDirectly", () => {
projectPath: PROJECT_PATH,
isConnected: true,
client: {
openProject: vi.fn(async () => ({
openProject: async () => ({
requestId: "request-1",
error: null,
workspace: workspacePayload,
})),
}),
},
mergeWorkspaces: session.mergeWorkspaces,
setHasHydratedWorkspaces: session.setHasHydratedWorkspaces,
@@ -103,7 +103,7 @@ describe("openProjectDirectly", () => {
navigateToWorkspace: navigator.navigateToWorkspace,
});
expect(result).toBe(true);
expect(result).toEqual({ ok: true });
expect(session.merges).toHaveLength(1);
expect(session.merges[0]?.serverId).toBe(SERVER_ID);
expect(session.merges[0]?.workspaces[0]).toMatchObject({
@@ -127,11 +127,12 @@ describe("openProjectDirectly", () => {
projectPath: PROJECT_PATH,
isConnected: true,
client: {
openProject: vi.fn(async () => ({
openProject: async () => ({
requestId: "request-2",
error: "Failed to open project",
error: "Directory not found: /repo/project",
errorCode: "directory_not_found" as const,
workspace: null,
})),
}),
},
mergeWorkspaces: session.mergeWorkspaces,
setHasHydratedWorkspaces: session.setHasHydratedWorkspaces,
@@ -139,7 +140,11 @@ describe("openProjectDirectly", () => {
navigateToWorkspace: navigator.navigateToWorkspace,
});
expect(result).toBe(false);
expect(result).toEqual({
ok: false,
errorCode: "directory_not_found",
error: "Directory not found: /repo/project",
});
expect(session.merges).toEqual([]);
expect(session.hydrated).toEqual([]);
expect(layout.openedTabs).toEqual([]);
+4 -2
View File
@@ -4,9 +4,11 @@ import { useSessionStore } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { generateDraftId } from "@/stores/draft-keys";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import { openProjectDirectly } from "@/hooks/open-project";
import { openProjectDirectly, type OpenProjectResult } from "@/hooks/open-project";
export function useOpenProject(serverId: string | null): (path: string) => Promise<boolean> {
export function useOpenProject(
serverId: string | null,
): (path: string) => Promise<OpenProjectResult> {
const normalizedServerId = serverId?.trim() ?? "";
const client = useHostRuntimeClient(normalizedServerId);
const isConnected = useHostRuntimeIsConnected(normalizedServerId);
+5
View File
@@ -1025,6 +1025,11 @@ export const ar: TranslationResources = {
placeholder: "اكتب مسار الدليل...",
opening: "افتتاح المشروع...",
empty: "ابدأ بكتابة المسار",
errors: {
directory_not_found: "لم يتم العثور على الدليل.",
open_failed: "تعذر فتح المشروع.",
},
openPath: "فتح المسار",
},
branchSwitcher: {
currentBranch: "الفرع الحالي:{{branchName}}. اضغط لتبديل الفرع.",
+5
View File
@@ -1030,6 +1030,11 @@ export const en = {
placeholder: "Type a directory path...",
opening: "Opening project...",
empty: "Start typing a path",
errors: {
directory_not_found: "Directory not found.",
open_failed: "Could not open project.",
},
openPath: "Open path",
},
branchSwitcher: {
currentBranch: "Current branch: {{branchName}}. Press to switch branch.",
+5
View File
@@ -1057,6 +1057,11 @@ export const es: TranslationResources = {
placeholder: "Escriba una ruta de directorio...",
opening: "Proyecto de apertura...",
empty: "Comience a escribir una ruta",
errors: {
directory_not_found: "No se encontró el directorio.",
open_failed: "No se pudo abrir el proyecto.",
},
openPath: "Abrir ruta",
},
branchSwitcher: {
currentBranch: "Sucursal actual:{{branchName}}. Presione para cambiar de rama.",
+5
View File
@@ -1059,6 +1059,11 @@ export const fr: TranslationResources = {
placeholder: "Tapez un chemin de répertoire...",
opening: "Projet d'ouverture...",
empty: "Commencez à taper un chemin",
errors: {
directory_not_found: "Répertoire introuvable.",
open_failed: "Impossible d’ouvrir le projet.",
},
openPath: "Ouvrir le chemin",
},
branchSwitcher: {
currentBranch: "Branche actuelle:{{branchName}}. Appuyez pour changer de branche.",
+5
View File
@@ -1047,6 +1047,11 @@ export const ru: TranslationResources = {
placeholder: "Введите путь к каталогу...",
opening: "Открытие проекта...",
empty: "Начните вводить путь",
errors: {
directory_not_found: "Каталог не найден.",
open_failed: "Не удалось открыть проект.",
},
openPath: "Открыть путь",
},
branchSwitcher: {
currentBranch: "Текущая ветка:{{branchName}}. Нажмите, чтобы переключить ветку.",
+5
View File
@@ -1010,6 +1010,11 @@ export const zhCN: TranslationResources = {
placeholder: "输入目录路径...",
opening: "正在打开 project...",
empty: "开始输入路径",
errors: {
directory_not_found: "找不到目录。",
open_failed: "无法打开项目。",
},
openPath: "打开路径",
},
branchSwitcher: {
currentBranch: "当前分支:{{branchName}}。按下以切换分支。",