diff --git a/packages/app/src/hooks/use-active-workspace-archive.ts b/packages/app/src/hooks/use-active-workspace-archive.ts new file mode 100644 index 0000000000..266263e6c9 --- /dev/null +++ b/packages/app/src/hooks/use-active-workspace-archive.ts @@ -0,0 +1,91 @@ +import { useCallback } from "react"; +import { + useActiveWorkspaceSelection, + type ActiveWorkspaceSelection, +} from "@/stores/navigation-active-workspace-store"; +import { getFocusedWorkspaceSelection } from "@/navigation/workspace-route-navigation"; +import { useSessionStore } from "@/stores/session-store"; +import { useWorkspaceFields } from "@/stores/session-store-hooks"; +import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity"; +import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect"; +import { useWorkspaceArchive } from "@/workspace/use-workspace-archive"; +import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive"; + +// The redirect compares descriptor ids; the route's id is not guaranteed to equal one (see +// use-global-workspace-pin-action.ts), so resolve it through the session store. +function readActiveDescriptorSelection(): ActiveWorkspaceSelection | null { + const selection = getFocusedWorkspaceSelection(); + if (!selection) { + return null; + } + const workspaces = useSessionStore.getState().sessions[selection.serverId]?.workspaces; + const key = resolveWorkspaceMapKeyByIdentity({ + workspaces, + workspaceId: selection.workspaceId, + }); + const descriptor = key ? workspaces?.get(key) : undefined; + return descriptor ? { serverId: selection.serverId, workspaceId: descriptor.id } : null; +} + +export interface ActiveWorkspaceArchive { + /** False when no workspace is routed, or the routed one is already archiving. */ + canArchive: boolean; + /** Starts the archive for the routed workspace. Returns false when nothing was started. */ + archive: () => boolean; +} + +/** + * Archives the workspace the route points at. Keyed on the route selection rather than a rendered + * row, so it works from the keyboard shortcut and from the compact header menu alike. + */ +export function useActiveWorkspaceArchive(): ActiveWorkspaceArchive { + const selection = useActiveWorkspaceSelection(); + const serverId = selection?.serverId ?? null; + const routeWorkspaceId = selection?.workspaceId ?? null; + // `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts. + const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({ + id: workspace.id, + workspaceKind: workspace.workspaceKind, + workspaceDirectory: workspace.workspaceDirectory, + name: workspace.name, + archivingAt: workspace.archivingAt, + diffStat: workspace.diffStat, + })); + + // The archive starts after the host answers and you confirm, by which time the header that began + // it may be gone (a resize swaps it, and on native switching workspaces unmounts it), and you may + // have left workspace routes. So the redirect reads the focused route now, not this render's. + const redirectAfterArchive = useCallback((workspace: WorkspaceArchiveTarget) => { + redirectIfArchivingActiveWorkspace({ + ...workspace, + activeWorkspaceSelection: readActiveDescriptorSelection(), + }); + }, []); + + const archiveController = useWorkspaceArchive({ + serverId: serverId ?? "", + workspaceId: fields?.id ?? "", + workspaceKind: fields?.workspaceKind ?? "directory", + workspaceDirectory: fields?.workspaceDirectory ?? "", + name: fields?.name ?? "", + diffStat: fields?.diffStat, + onArchiveStarted: redirectAfterArchive, + }); + + const canArchive = fields !== null && fields.archivingAt === null; + + const archive = useCallback(() => { + if (!canArchive || !serverId) { + return false; + } + // Archiving hides its target immediately. Read the store in case this runs again before + // React renders that update. + if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) { + return false; + } + archiveController.archive(); + return true; + }, [archiveController, canArchive, fields, serverId]); + + return { canArchive, archive }; +} diff --git a/packages/app/src/hooks/use-global-workspace-archive-action.ts b/packages/app/src/hooks/use-global-workspace-archive-action.ts index de4ff264ae..d6b5a9efcf 100644 --- a/packages/app/src/hooks/use-global-workspace-archive-action.ts +++ b/packages/app/src/hooks/use-global-workspace-archive-action.ts @@ -1,11 +1,6 @@ -import { useCallback } from "react"; +import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive"; import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler"; import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher"; -import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store"; -import { useWorkspaceFields } from "@/stores/session-store-hooks"; -import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect"; -import { useWorkspaceArchive } from "@/workspace/use-workspace-archive"; -import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive"; const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"]; @@ -14,64 +9,13 @@ const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archi // the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the // active route selection. export function useGlobalWorkspaceArchiveAction() { - const selection = useActiveWorkspaceSelection(); - const serverId = selection?.serverId ?? null; - const routeWorkspaceId = selection?.workspaceId ?? null; - // `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts. - const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({ - id: workspace.id, - workspaceKind: workspace.workspaceKind, - workspaceDirectory: workspace.workspaceDirectory, - name: workspace.name, - archivingAt: workspace.archivingAt, - diffStat: workspace.diffStat, - })); - - // useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is - // routed when the archive starts, after any confirmation. It is the descriptor id, which is what - // the redirect compares against. - const activeWorkspaceId = fields?.id ?? null; - const redirectAfterArchive = useCallback( - (workspace: WorkspaceArchiveTarget) => { - redirectIfArchivingActiveWorkspace({ - ...workspace, - activeWorkspaceSelection: - serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null, - }); - }, - [activeWorkspaceId, serverId], - ); - - const archiveController = useWorkspaceArchive({ - serverId: serverId ?? "", - workspaceId: fields?.id ?? "", - workspaceKind: fields?.workspaceKind ?? "directory", - workspaceDirectory: fields?.workspaceDirectory ?? "", - name: fields?.name ?? "", - diffStat: fields?.diffStat, - onArchiveStarted: redirectAfterArchive, - }); - - const canArchive = fields !== null && fields.archivingAt === null; - - const handle = useCallback(() => { - if (!canArchive || !serverId) { - return false; - } - // Archiving hides its target immediately. Read the store in case the shortcut - // runs again before React renders that update. - if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) { - return false; - } - archiveController.archive(); - return true; - }, [archiveController, canArchive, fields, serverId]); + const { canArchive, archive } = useActiveWorkspaceArchive(); useKeyboardActionHandler({ handlerId: "workspace-archive-global", actions: WORKSPACE_ARCHIVE_ACTIONS, enabled: canArchive, priority: 0, - handle, + handle: archive, }); } diff --git a/packages/app/src/navigation/workspace-route-navigation.test.ts b/packages/app/src/navigation/workspace-route-navigation.test.ts index 841a31dc64..881beb3d58 100644 --- a/packages/app/src/navigation/workspace-route-navigation.test.ts +++ b/packages/app/src/navigation/workspace-route-navigation.test.ts @@ -1,17 +1,22 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { NavigationContainerRefWithCurrent } from "expo-router/react-navigation"; import { + getFocusedWorkspaceSelection, navigateToHostWorkspaceRoute, registerWorkspaceRouteNavigationRef, } from "./workspace-route-navigation"; -function createNavigationRef(rootState: unknown, options: { ready?: boolean } = {}) { +function createNavigationRef( + rootState: unknown, + options: { ready?: boolean; currentRoute?: { name: string; params?: object } } = {}, +) { const dispatch = vi.fn(); let ready = options.ready ?? true; const readyListeners = new Set<() => void>(); const navigation = { isReady: () => ready, getRootState: () => rootState, + getCurrentRoute: () => options.currentRoute, dispatch, addListener: (event: string, listener: () => void) => { if (event === "ready") readyListeners.add(listener); @@ -215,3 +220,27 @@ describe("navigateToHostWorkspaceRoute", () => { expect(dismissTo).toHaveBeenCalledWith("/h/server-1/workspace/workspace-a"); }); }); + +describe("getFocusedWorkspaceSelection", () => { + function focus(currentRoute?: { name: string; params?: object }) { + registerWorkspaceRouteNavigationRef(createNavigationRef({}, { currentRoute }).navigationRef); + } + + it("returns the workspace on screen", () => { + focus({ + name: "workspace/[workspaceId]/index", + params: { serverId: "server-1", workspaceId: "workspace-a" }, + }); + + expect(getFocusedWorkspaceSelection()).toEqual({ + serverId: "server-1", + workspaceId: "workspace-a", + }); + }); + + it("returns null when a non-workspace screen is focused", () => { + focus({ name: "settings/[section]", params: { section: "general" } }); + + expect(getFocusedWorkspaceSelection()).toBeNull(); + }); +}); diff --git a/packages/app/src/navigation/workspace-route-navigation.ts b/packages/app/src/navigation/workspace-route-navigation.ts index d8b33ea305..081e12a873 100644 --- a/packages/app/src/navigation/workspace-route-navigation.ts +++ b/packages/app/src/navigation/workspace-route-navigation.ts @@ -5,6 +5,7 @@ import type { } from "expo-router/react-navigation"; import { router, type Href } from "expo-router"; import { + decodeWorkspaceIdFromPathSegment, encodeWorkspaceIdForPathSegment, getHostWorkspaceOpenParamFromPathname, parseHostWorkspaceRouteFromPathname, @@ -39,6 +40,27 @@ export function registerWorkspaceRouteNavigationRef( }; } +/** + * The workspace on screen right now, read from the focused route, or null on any other screen + * (Settings, New workspace, ...). Unlike a component's last render, it stays correct for work that + * finishes after the screen that started it is gone. + */ +export function getFocusedWorkspaceSelection(): { serverId: string; workspaceId: string } | null { + // Typed routes narrow the container's route to `never`; this only reads name and params. + const route = rootNavigationRef?.current?.getCurrentRoute() as + | { name: string; params?: { serverId?: unknown; workspaceId?: unknown } } + | undefined; + if (route?.name !== HOST_WORKSPACE_ROUTE_NAME) { + return null; + } + const params = route.params; + if (typeof params?.serverId !== "string" || typeof params.workspaceId !== "string") { + return null; + } + const workspaceId = decodeWorkspaceIdFromPathSegment(params.workspaceId); + return workspaceId ? { serverId: params.serverId, workspaceId } : null; +} + interface MountedRouteStack { key: string; focusedRouteName: string | null; diff --git a/packages/app/src/screens/workspace/workspace-header-menu.tsx b/packages/app/src/screens/workspace/workspace-header-menu.tsx index cca5dd2e10..572b31ccca 100644 --- a/packages/app/src/screens/workspace/workspace-header-menu.tsx +++ b/packages/app/src/screens/workspace/workspace-header-menu.tsx @@ -3,7 +3,14 @@ import React, { useCallback, useMemo } from "react"; import { View } from "react-native"; import { useRouter, type Href } from "expo-router"; import { useTranslation } from "react-i18next"; -import { Copy, Ellipsis, Globe, Import as ImportIcon, Settings } from "lucide-react-native"; +import { + Archive, + Copy, + Ellipsis, + Globe, + Import as ImportIcon, + Settings, +} from "lucide-react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import type { TerminalProfile } from "@getpaseo/protocol/messages"; import { @@ -21,6 +28,7 @@ import { useIconButtonChromeStyle, } from "@/components/ui/icon-button-chrome"; import { TerminalProfileIcon } from "@/components/terminal-profile-icon"; +import { useActiveWorkspaceArchive } from "@/hooks/use-active-workspace-archive"; import { useDaemonConfig } from "@/hooks/use-daemon-config"; import { getTerminalProfileIcon, @@ -35,6 +43,7 @@ import { import { usePluginWorkspaceMenu } from "@/plugins"; const ThemedEllipsis = withUnistyles(Ellipsis); +const ThemedArchive = withUnistyles(Archive); const ThemedCopy = withUnistyles(Copy); const ThemedGlobe = withUnistyles(Globe); const ThemedImport = withUnistyles(ImportIcon); @@ -45,6 +54,7 @@ const mutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMut const MENU_NEW_BROWSER_ICON = ; const MENU_IMPORT_ICON = ; const MENU_COPY_ICON = ; +const MENU_ARCHIVE_ICON = ; const MENU_SETTINGS_ICON = ; function WorkspaceHeaderMenuTriggerIcon() { return ( @@ -259,6 +269,10 @@ export function WorkspaceHeaderMenuMobile({ const handleEditProfiles = useCallback(() => { router.push(buildSettingsHostSectionRoute(normalizedServerId, "terminals") as Href); }, [normalizedServerId, router]); + const { canArchive, archive } = useActiveWorkspaceArchive(); + const handleArchiveWorkspace = useCallback(() => { + archive(); + }, [archive]); const scriptsMenu = useWorkspaceScriptsMenuPages(scripts); const pluginMenu = usePluginWorkspaceMenu(normalizedServerId, normalizedWorkspaceId); const pages = useMemo( @@ -330,6 +344,15 @@ export function WorkspaceHeaderMenuMobile({ ) : null} + + {t("sidebar.workspace.actions.archiveWorkspace")} + + {t("workspace.tabs.actions.terminalProfilesMenu")} {profiles.map((profile) => (