From b82b2b31e7a3c004231687221bae5a1fa1f6f287 Mon Sep 17 00:00:00 2001 From: Viktor Bystrov <18964918+ViktorBystrov72@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:23:39 +0500 Subject: [PATCH 1/2] fix(desktop): show launch progress and Codex usage on agent presets --- .../useAcpChatEnabled/useAcpChatEnabled.ts | 2 + .../components/PresetsBar/PresetsBar.tsx | 12 ++ .../PresetBarItem/PresetBarItem.test.tsx | 168 ++++++++++++++++++ .../PresetBarItem/PresetBarItem.tsx | 103 ++++++++++- .../useAgentSessionLauncher.ts | 13 +- .../AgentTerminalPane/AgentTerminalPane.tsx | 9 + .../UsageWarningDot/UsageWarningDot.tsx | 11 +- .../hooks/usePaneRegistry/usePaneRegistry.tsx | 32 +++- .../usePresetExecution/usePresetExecution.ts | 57 ++++-- .../utils/launchPresetTab.test.ts | 90 ++++++++++ .../utils/launchPresetTab.ts | 78 ++++++++ .../workspace/$workspaceId/page.tsx | 1 + .../$workspaceId/state/presetLaunches.test.ts | 47 +++++ .../$workspaceId/state/presetLaunches.ts | 59 ++++++ 14 files changed, 652 insertions(+), 30 deletions(-) create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.test.tsx create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.test.ts create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.ts create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts diff --git a/apps/desktop/src/renderer/hooks/useAcpChatEnabled/useAcpChatEnabled.ts b/apps/desktop/src/renderer/hooks/useAcpChatEnabled/useAcpChatEnabled.ts index 7a20f61b8d8..cdbfc80f8ee 100644 --- a/apps/desktop/src/renderer/hooks/useAcpChatEnabled/useAcpChatEnabled.ts +++ b/apps/desktop/src/renderer/hooks/useAcpChatEnabled/useAcpChatEnabled.ts @@ -13,6 +13,8 @@ export function useAcpChatSettled(): boolean { /** For choosing chat or terminal at launch: waits for the setting instead of reading "off" while it loads. */ export function useResolveAcpChatEnabled(): () => Promise { + // Warm the same preference that the toolbar must honor on the first click. + cloudTrpc.userSettings.get.useQuery(undefined, { staleTime: 60_000 }); const utils = cloudTrpc.useUtils(); return useCallback( () => diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/PresetsBar.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/PresetsBar.tsx index 9027b606478..2b13c1a5ad4 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/PresetsBar.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/PresetsBar.tsx @@ -10,6 +10,7 @@ import { } from "@superset/ui/dropdown-menu"; import { Tooltip, TooltipContent, TooltipTrigger } from "@superset/ui/tooltip"; import { cn } from "@superset/ui/utils"; +import { useWorkspaceHostUrl } from "@superset/workspace-client"; import { useNavigate } from "@tanstack/react-router"; import { Eye, EyeOff, Settings } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; @@ -26,6 +27,7 @@ import { useUserPreferences } from "renderer/hooks/useUserPreferences"; import type { HotkeyId } from "renderer/hotkeys"; import { posthog } from "renderer/lib/posthog"; import { resolvePresetIcon } from "renderer/lib/preset-icon"; +import { useWorkspace } from "renderer/routes/_authenticated/_dashboard/workspace/providers/WorkspaceProvider"; import { useCollections } from "renderer/routes/_authenticated/providers/CollectionsProvider"; import type { TerminalPresetRow } from "renderer/routes/_authenticated/providers/CollectionsProvider/dashboardSidebarLocal"; import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider"; @@ -80,6 +82,8 @@ export function PresetsBar({ onToggleShowPresetsBar, }: PresetsBarProps) { const navigate = useNavigate(); + const { workspace } = useWorkspace(); + const hostUrl = useWorkspaceHostUrl(); const isDark = useIsDarkTheme(); const isParadevShell = useParadevShell(); const collections = useCollections(); @@ -353,6 +357,14 @@ export function PresetsBar({ return ( + void navigate({ + to: "/settings/usage", + search: { workspaceId: workspace.id, agent: "codex" }, + }) + } preset={preset} visibleIndex={visibleIndex} hotkeyId={hotkeyId} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.test.tsx new file mode 100644 index 00000000000..9d160d50740 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.test.tsx @@ -0,0 +1,168 @@ +import { afterEach, expect, mock, test } from "bun:test"; +import { createWorkspaceStore } from "@superset/panes"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + act, + cleanup, + fireEvent, + render, + screen, + within, +} from "@testing-library/react"; +import { DndProvider } from "react-dnd"; +import { HTML5Backend } from "react-dnd-html5-backend"; +import { + HOST_USAGE_QUOTA_QUERY_KEY, + type UsageAccount, +} from "renderer/hooks/host-service/useHostUsageQuota"; +import type { TerminalPresetRow } from "renderer/routes/_authenticated/providers/CollectionsProvider/dashboardSidebarLocal"; +import { launchPresetTab } from "../../../../hooks/usePresetExecution/utils/launchPresetTab"; +import { runPresetOnce } from "../../../../state/presetLaunches"; +import type { PaneViewerData } from "../../../../types"; +import { PresetBarItem } from "./PresetBarItem"; + +afterEach(cleanup); + +function showButton( + name: string, + execute: () => void, + accounts: UsageAccount[] = [], +) { + const workspaceId = "workspace"; + const hostUrl = "https://host.invalid"; + const client = new QueryClient(); + client.setQueryData([...HOST_USAGE_QUOTA_QUERY_KEY, hostUrl], accounts); + const preset: TerminalPresetRow = { + id: crypto.randomUUID(), + name, + agentId: name.toLowerCase(), + commands: [name.toLowerCase()], + cwd: "", + projectIds: null, + executionMode: "new-tab", + tabOrder: 0, + createdAt: new Date(), + }; + const viewUsage = mock(() => {}); + render( + + + {}} + onLocalReorder={() => {}} + onPersistReorder={() => {}} + /> + + , + ); + return { + button: screen.getByRole("button", { name: new RegExp(name) }), + viewUsage, + workspaceId, + preset, + }; +} + +test.each([ + "Pi", + "Codex", +])("%s opens one tab while the host is starting", async (name) => { + const store = createWorkspaceStore(); + const preference = Promise.withResolvers(); + const session = Promise.withResolvers(); + const launcher = { + mint: () => crypto.randomUUID(), + create: mock(() => session.promise), + }; + let pending: Promise | undefined; + const { button, workspaceId, preset } = showButton(name, () => { + pending = runPresetOnce(workspaceId, preset.id, () => + launchPresetTab({ + store, + linkedStores: [], + launcher, + title: name, + command: name.toLowerCase(), + tryChat: () => preference.promise, + }), + ); + }); + await act(async () => { + fireEvent.click(button); + fireEvent.click(button); + }); + expect(button.getAttribute("aria-busy")).toBe("true"); + expect(store.getState().tabs).toHaveLength(1); + expect(launcher.create).not.toHaveBeenCalled(); + await act(async () => { + preference.resolve(null); + }); + expect(launcher.create).toHaveBeenCalledTimes(1); + fireEvent.click(button); + expect(store.getState().tabs).toHaveLength(1); + await act(async () => { + session.resolve("ready"); + await pending; + }); + expect(button.hasAttribute("disabled")).toBe(false); + await act(async () => { + fireEvent.click(button); + await pending; + }); + expect(store.getState().tabs).toHaveLength(2); +}); + +test("shows the default Codex account quota on the button and in its menu", async () => { + const account: UsageAccount = { + agent: "codex", + credentialKind: "subscription", + accountKey: "selected", + sourceLabel: "default", + email: null, + plan: null, + status: "ok", + statusDetail: null, + windows: [ + { id: "secondary", label: "Weekly", usedPercent: 46, resetsAt: null }, + ], + creditsBalance: null, + extraUsage: null, + selection: null, + isDefault: true, + fetchedAt: new Date(), + }; + const { button, viewUsage } = showButton("Codex", () => {}, [ + { + ...account, + accountKey: "other", + isDefault: false, + windows: [{ ...account.windows[0], usedPercent: 90 }], + }, + account, + ]); + expect(button.textContent).toContain("46%"); + fireEvent.contextMenu(button); + const menu = within(await screen.findByRole("menu")); + expect(menu.getByText("Weekly")).toBeDefined(); + expect(menu.getByText("46%")).toBeDefined(); + expect(menu.queryByText("90%")).toBeNull(); + fireEvent.click(menu.getByText("View usage")); + expect(viewUsage).toHaveBeenCalledTimes(1); +}); + +test("shows a link to usage when Codex quota data is unavailable", async () => { + const { button } = showButton("Codex", () => {}); + fireEvent.contextMenu(button); + const menu = within(await screen.findByRole("menu")); + expect(menu.getByRole("status").textContent).toContain("Usage unavailable."); + expect(menu.getByText("View usage")).toBeDefined(); + expect(button.textContent).not.toContain("%"); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.tsx index 4145a8b1502..9f5d1b980be 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/components/PresetsBar/components/PresetBarItem/PresetBarItem.tsx @@ -1,24 +1,36 @@ import { Trans } from "@lingui/react/macro"; import type { HostAgentConfig } from "@superset/host-service/settings"; +import { formatPercent } from "@superset/i18n/format"; import { Button } from "@superset/ui/button"; import { ContextMenu, ContextMenuContent, ContextMenuItem, + ContextMenuLabel, ContextMenuSeparator, ContextMenuTrigger, } from "@superset/ui/context-menu"; +import { Loader2 } from "lucide-react"; import { useEffect, useRef } from "react"; import { useDrag, useDrop } from "react-dnd"; import { HiMiniCommandLine } from "react-icons/hi2"; +import { QuotaWindowRow } from "renderer/components/QuotaWindowRow"; +import { useHostUsageQuota } from "renderer/hooks/host-service/useHostUsageQuota"; +import { useNow } from "renderer/hooks/useNow"; import type { HotkeyId } from "renderer/hotkeys"; import { HotkeyTooltip } from "renderer/hotkeys"; +import { findLinkedAgent } from "renderer/lib/agent-launch-command"; import { resolvePresetIcon } from "renderer/lib/preset-icon"; +import { resolvePresetIconKey } from "renderer/lib/preset-icon-key"; import type { TerminalPresetRow } from "renderer/routes/_authenticated/providers/CollectionsProvider/dashboardSidebarLocal"; +import { usePresetStarting } from "../../../../state/presetLaunches"; const V2_PRESET_BAR_ITEM_TYPE = "V2_PRESET_BAR_ITEM"; interface PresetBarItemProps { + workspaceId: string; + hostUrl: string; + onViewUsage: () => void; preset: TerminalPresetRow; visibleIndex: number; hotkeyId?: HotkeyId; @@ -31,6 +43,9 @@ interface PresetBarItemProps { } export function PresetBarItem({ + workspaceId, + hostUrl, + onViewUsage, preset, visibleIndex, hotkeyId, @@ -43,6 +58,37 @@ export function PresetBarItem({ }: PresetBarItemProps) { const containerRef = useRef(null); const icon = resolvePresetIcon(preset, agents, isDark); + const starting = usePresetStarting(workspaceId, preset.id); + const linked = findLinkedAgent(agents, preset.agentId); + const isCodex = + (linked?.presetId ?? resolvePresetIconKey(preset, undefined)) === "codex"; + const quota = useHostUsageQuota(isCodex ? hostUrl : null); + const account = quota.data?.find( + (item) => item.agent === "codex" && item.isDefault, + ); + const now = useNow(60_000, isCodex); + const windows = + account?.status === "ok" && + !quota.isError && + now.getTime() - new Date(account.fetchedAt).getTime() < 10 * 60_000 + ? account.windows.filter( + (window) => + Number.isFinite(window.usedPercent) && + window.usedPercent >= 0 && + (!window.resetsAt || + new Date(window.resetsAt).getTime() > now.getTime()), + ) + : []; + const summary = + windows.find( + (window) => + ["seven_day", "secondary"].includes(window.id) || + window.label === "Weekly", + ) ?? windows[0]; + + const used = summary + ? formatPercent(summary.usedPercent / 100, { maximumFractionDigits: 0 }) + : undefined; const [{ isDragging }, drag] = useDrag( () => ({ @@ -90,10 +136,17 @@ export function PresetBarItem({ - onExecutePreset(preset)}> + {isCodex && ( + <> + + Usage · Default + + {windows.length ? ( + windows.map((window) => ( + + )) + ) : ( + + {account?.credentialKind === "api_key" ? ( + API billing + ) : quota.isLoading ? ( + Reading usage… + ) : ( + Usage unavailable. + )} + + )} + + View usage + + + + )} + onExecutePreset(preset)} + > Run script diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts index b4e2d31cc5c..ba7325753d3 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts @@ -1,7 +1,7 @@ import { useLingui } from "@lingui/react/macro"; import { acpHarnessForPreset } from "@superset/chat/core"; import { errorMessage } from "@superset/i18n/errors"; -import type { WorkspaceStore } from "@superset/panes"; +import type { CreatePaneInput, WorkspaceStore } from "@superset/panes"; import { toast } from "@superset/ui/sonner"; import { useWorkspaceClient, workspaceTrpc } from "@superset/workspace-client"; import { useQueryClient } from "@tanstack/react-query"; @@ -43,6 +43,7 @@ export type OpenAgentChat = ( prompt?: string; presetId?: string; }, + place?: (pane: CreatePaneInput) => void, ) => Promise<{ terminalId: string } | null>; interface UseAgentSessionLauncherOptions { @@ -68,7 +69,7 @@ export function useAgentSessionLauncher({ const queryClient = useQueryClient(); const openChatPane = useCallback( - async (input) => { + async (input, place) => { const configs = await queryClient .ensureQueryData(v2AgentConfigsQueryOptions(hostUrl)) .catch(() => agentConfigs ?? []); @@ -95,7 +96,9 @@ export function useAgentSessionLauncher({ ...(input.modeId ? { chatModeId: input.modeId } : {}), } satisfies ChatPaneData, }; - if (input.placement === "split-pane" && state.activeTabId) { + if (place) { + place(pane); + } else if (input.placement === "split-pane" && state.activeTabId) { state.addPane({ tabId: state.activeTabId, pane }); } else { state.addTab({ panes: [pane] }); @@ -106,8 +109,8 @@ export function useAgentSessionLauncher({ ); const openAgentChat = useCallback( - async (input) => - (await resolveAcpChatEnabled()) ? openChatPane(input) : null, + async (input, place) => + (await resolveAcpChatEnabled()) ? openChatPane(input, place) : null, [resolveAcpChatEnabled, openChatPane], ); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/AgentTerminalPane/AgentTerminalPane.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/AgentTerminalPane/AgentTerminalPane.tsx index f6db281acc1..37945a99051 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/AgentTerminalPane/AgentTerminalPane.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/AgentTerminalPane/AgentTerminalPane.tsx @@ -1,3 +1,4 @@ +import { Trans } from "@lingui/react/macro"; import type { RendererContext } from "@superset/panes"; import { useEffect } from "react"; import type { @@ -6,6 +7,7 @@ import type { PaneViewerData, TerminalPaneData, } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/types"; +import { usePresetTerminalStarting } from "../../../../state/presetLaunches"; import { TerminalPane } from "../TerminalPane"; type ChatOnTerminalPaneData = TerminalPaneData & @@ -32,6 +34,7 @@ export function AgentTerminalPane({ onNewShell: () => Promise; }) { const data = ctx.pane.data as ChatOnTerminalPaneData; + const starting = usePresetTerminalStarting(data.terminalId); const isSavedChat = data.agentSurface === "acp"; useEffect(() => { @@ -67,6 +70,12 @@ export function AgentTerminalPane({ ]); if (isSavedChat) return null; + if (starting) + return ( + + Starting… + + ); return ( + {percent} + + ); + if (tightest.usedPercent < 70) return null; return ( { @@ -554,7 +557,15 @@ export function usePaneRegistry({ } clearWorkspaceRunTerminal(terminalId); terminalRuntimeRegistry.dispose(terminalId); - killTerminalSessionSilently({ terminalId, workspaceId }); + afterPresetTerminalStart(terminalId, () => { + if ( + [store, ...(linkedStores ?? [])].some((candidate) => + findTerminalPaneLocation(candidate.getState(), terminalId), + ) + ) + return; + killTerminalSessionSilently({ terminalId, workspaceId }); + }); }, onAfterRemove: (pane) => { terminalRuntimeRegistry.release( @@ -612,16 +623,28 @@ export function usePaneRegistry({ toast.error(t({ message: "Copy failed" })); }); }; - const agentSessionIdOf = (ctx: RendererContext) => { + const agentBindingOf = (ctx: RendererContext) => { const { terminalId } = ctx.pane.data as TerminalPaneData; return queryClient .getQueryData( getTerminalAgentBindingsQueryKey(workspaceId), ) - ?.find((binding) => binding.terminalId === terminalId) - ?.agentSessionId; + ?.find((binding) => binding.terminalId === terminalId); }; + const agentSessionIdOf = (ctx: RendererContext) => + agentBindingOf(ctx)?.agentSessionId; const terminalActions: ContextMenuActionConfig[] = [ + { + key: "view-codex-usage", + label: t({ message: "View usage" }), + hidden: (ctx) => agentBindingOf(ctx)?.agentId !== "codex", + onSelect: () => { + void navigate({ + to: "/settings/usage", + search: { workspaceId, agent: "codex" }, + }); + }, + }, { key: "copy", label: t({ message: "Copy" }), @@ -1205,6 +1228,7 @@ export function usePaneRegistry({ clearShortcut, scrollToBottomShortcut, killTerminalSession, + navigate, killTerminalSessionSilently, isKillingTerminalSession, launcher, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts index c7c33830e1f..5ae4f1a4763 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts @@ -26,9 +26,11 @@ import { filterMatchingPresetsForProject } from "shared/preset-project-targeting import { getPresetsForTriggerField } from "shared/preset-trigger-selection"; import { quote } from "shell-quote"; import type { StoreApi } from "zustand/vanilla"; +import { runPresetOnce } from "../../state/presetLaunches"; import type { PaneViewerData, TerminalPaneData } from "../../types"; import type { OpenAgentChat } from "../useAgentSessionLauncher"; import type { TerminalLauncher } from "../useTerminalLauncher"; +import { launchPresetTab } from "./utils/launchPresetTab"; import { isLinkedPresetLaunchable } from "./utils/linkedPresetGating"; function makeTerminalPane( @@ -90,12 +92,14 @@ function buildFocusedTerminalCommand({ interface UseV2PresetExecutionArgs { store: StoreApi>; + linkedStores: StoreApi>[]; launcher: TerminalLauncher; openAgentChat: OpenAgentChat; } export function usePresetExecution({ store, + linkedStores, launcher, openAgentChat, }: UseV2PresetExecutionArgs) { @@ -163,7 +167,7 @@ export function usePresetExecution({ [agents], ); - const executePreset = useCallback( + const launchPreset = useCallback( async ( preset: TerminalPresetRow, options?: { target?: "new-tab" | "active-tab" }, @@ -207,20 +211,21 @@ export function usePresetExecution({ }); const linkedAgent = findLinkedAgent(agents, preset.agentId); - if ( - linkedAgent && - acpHarnessForPreset(linkedAgent.presetId) && - (plan === "new-tab-single" || plan === "active-tab-single") - ) { - const chat = await openAgentChat({ - configId: linkedAgent.id, - presetId: linkedAgent.presetId, - placement: plan === "active-tab-single" ? "split-pane" : "new-tab", - }); - if (chat) return; - } + const tryChat = + linkedAgent && acpHarnessForPreset(linkedAgent.presetId) + ? (place?: Parameters[1]) => + openAgentChat( + { + configId: linkedAgent.id, + presetId: linkedAgent.presetId, + placement: + plan === "active-tab-single" ? "split-pane" : "new-tab", + }, + place, + ) + : undefined; - // Sessions for every pane this plan creates are spun up in parallel + // Multi-pane plans start every session in parallel // before any of them land in the store, so background tabs (e.g. // new-tab-per-command, where each addTab flips activeTabId and only // the last tab ever mounts) still get their PTY + initial command — @@ -256,8 +261,15 @@ export function usePresetExecution({ } case "new-tab-single": { - const terminalId = await createTerminal(launchCommands[0]); - state.addTab({ panes: [makeTerminalPane(terminalId, title)] }); + await launchPresetTab({ + store, + linkedStores, + launcher, + command: launchCommands[0], + cwd, + title, + tryChat, + }); break; } @@ -287,6 +299,7 @@ export function usePresetExecution({ } case "active-tab-single": { + if (await tryChat?.()) break; const terminalId = await createTerminal(launchCommands[0]); const pane = makeTerminalPane(terminalId, title); if (!activeTabId) { @@ -338,6 +351,7 @@ export function usePresetExecution({ }, [ store, + linkedStores, launcher, resolvePresetCommands, t, @@ -351,6 +365,17 @@ export function usePresetExecution({ ], ); + const executePreset = useCallback( + ( + preset: TerminalPresetRow, + options?: { target?: "new-tab" | "active-tab" }, + ) => + runPresetOnce(workspaceId, preset.id, () => + launchPreset(preset, options), + ), + [workspaceId, launchPreset], + ); + return { matchedPresets, newTabPresets, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.test.ts new file mode 100644 index 00000000000..4a1ef007b4f --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.test.ts @@ -0,0 +1,90 @@ +import { expect, mock, test } from "bun:test"; +import { createWorkspaceStore, transferPaneToNewTab } from "@superset/panes"; +import type { PaneViewerData } from "../../../types"; +import { launchPresetTab } from "./launchPresetTab"; + +test("replaces the pending pane with a chat after the pane moves", async () => { + const store = createWorkspaceStore(); + const right = createWorkspaceStore(); + const ready = Promise.withResolvers(); + const launcher = { + mint: () => "pending", + create: mock(async () => "pending"), + }; + const started = launchPresetTab({ + store, + linkedStores: [right], + launcher, + title: "Codex", + tryChat: async (place) => { + await ready.promise; + place({ + kind: "chat-v3", + data: { terminalId: "chat", sessionId: null, agent: { id: "codex" } }, + }); + return { terminalId: "chat" }; + }, + }); + await Promise.resolve(); + const paneId = store.getState().getActivePane()?.pane.id; + if (!paneId) throw new Error("Expected a pending pane"); + store.getState().setPanePinned({ paneId, pinned: true }); + transferPaneToNewTab({ source: store, target: right, paneId }); + ready.resolve(); + await started; + expect(store.getState().tabs).toHaveLength(0); + expect(right.getState().tabs).toHaveLength(1); + expect(right.getState().getPane(paneId)?.pane).toMatchObject({ + kind: "chat-v3", + pinned: true, + titleOverride: "Codex", + data: { terminalId: "chat" }, + }); + expect(launcher.create).not.toHaveBeenCalled(); +}); + +test("does not launch a terminal if the tab closes while choosing a launch mode", async () => { + const store = createWorkspaceStore(); + const preference = Promise.withResolvers(); + const launcher = { + mint: () => "pending", + create: mock(async () => "pending"), + }; + const started = launchPresetTab({ + store, + linkedStores: [], + launcher, + tryChat: () => preference.promise, + }); + await Promise.resolve(); + const tab = store.getState().getActiveTab(); + if (!tab) throw new Error("Expected a pending tab"); + store.getState().removeTab(tab.id); + preference.resolve(null); + await started; + expect(store.getState().tabs).toHaveLength(0); + expect(launcher.create).not.toHaveBeenCalled(); +}); + +test("keeps the selected terminal when an earlier launch fails", async () => { + const store = createWorkspaceStore(); + const entered = Promise.withResolvers(); + const response = Promise.withResolvers(); + const launcher = { + mint: () => "pending", + create: () => { + entered.resolve(); + return response.promise; + }, + }; + const started = launchPresetTab({ store, linkedStores: [], launcher }); + await entered.promise; + const paneId = store.getState().getActivePane()?.pane.id; + if (!paneId) throw new Error("Expected a pending pane"); + store.getState().setPaneData({ paneId, data: { terminalId: "existing" } }); + response.reject(new Error("offline")); + await expect(started).rejects.toThrow("offline"); + expect(store.getState().getPane(paneId)?.pane.data).toEqual({ + terminalId: "existing", + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.ts new file mode 100644 index 00000000000..9d64583d086 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/utils/launchPresetTab.ts @@ -0,0 +1,78 @@ +import type { WorkspaceStore } from "@superset/panes"; +import type { StoreApi } from "zustand/vanilla"; +import { startPresetTerminal } from "../../../state/presetLaunches"; +import type { PaneViewerData } from "../../../types"; +import type { OpenAgentChat } from "../../useAgentSessionLauncher"; +import type { TerminalLauncher } from "../../useTerminalLauncher"; + +type PaneStore = StoreApi>; + +export function launchPresetTab({ + store, + linkedStores, + launcher, + command, + cwd, + title, + tryChat, +}: { + store: PaneStore; + linkedStores: PaneStore[]; + launcher: TerminalLauncher; + command?: string; + cwd?: string; + title?: string; + tryChat?: ( + place: NonNullable[1]>, + ) => ReturnType; +}) { + const terminalId = launcher.mint(); + const paneId = `pane-${crypto.randomUUID()}`; + const locate = () => { + for (const candidate of [store, ...linkedStores]) { + const state = candidate.getState(); + const location = state.getPane(paneId); + if (location?.pane.kind !== "terminal") continue; + const { data } = location.pane; + if ("terminalId" in data && data.terminalId === terminalId) + return { state, ...location }; + } + }; + + return startPresetTerminal(terminalId, async () => { + store.getState().addTab({ + panes: [ + { + id: paneId, + kind: "terminal", + titleOverride: title, + data: { terminalId }, + }, + ], + }); + try { + const chat = await tryChat?.((pane) => { + const current = locate(); + if (!current) return; + const { state, tabId, pane: pending } = current; + if (pending.pinned) state.setPanePinned({ paneId, pinned: false }); + state.replacePane({ + tabId, + paneId, + newPane: { + ...pane, + id: paneId, + titleOverride: pending.titleOverride ?? pane.titleOverride, + pinned: pending.pinned, + }, + }); + }); + if (!chat && locate()) + await launcher.create({ terminalId, command, cwd }); + } catch (error) { + const current = locate(); + current?.state.closePane({ tabId: current.tabId, paneId }); + throw error; + } + }); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/page.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/page.tsx index 9eb27b874ff..9345aee63df 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/page.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/page.tsx @@ -316,6 +316,7 @@ function WorkspaceContent() { resolvePresetCommands, } = usePresetExecution({ store, + linkedStores: linkedPaneStores, launcher, openAgentChat, }); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts new file mode 100644 index 00000000000..9ed555a3c5f --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it, mock } from "bun:test"; +import { + afterPresetTerminalStart, + runPresetOnce, + startPresetTerminal, +} from "./presetLaunches"; + +describe("preset launches", () => { + it("shares a pending launch for the same preset in the same workspace", async () => { + const hold = Promise.withResolvers(); + const start = mock(() => hold.promise); + const independent = mock(async () => {}); + const first = runPresetOnce("workspace", "pi", start); + expect(runPresetOnce("workspace", "pi", start)).toBe(first); + await Promise.all([ + runPresetOnce("workspace", "codex", independent), + runPresetOnce("another", "pi", independent), + ]); + expect(start).toHaveBeenCalledTimes(1); + expect(independent).toHaveBeenCalledTimes(2); + hold.resolve(); + await first; + await runPresetOnce("workspace", "pi", start); + expect(start).toHaveBeenCalledTimes(2); + }); + + it("lets the user retry after a launch fails", async () => { + const failed = runPresetOnce("ws", "codex", async () => { + throw new Error("offline"); + }); + await expect(failed).rejects.toThrow("offline"); + const retry = mock(async () => {}); + await runPresetOnce("ws", "codex", retry); + expect(retry).toHaveBeenCalledTimes(1); + }); + + it("waits for the pending terminal before running its cleanup", async () => { + const hold = Promise.withResolvers(); + const dispose = mock(() => {}); + const create = startPresetTerminal("new-id", () => hold.promise); + afterPresetTerminalStart("new-id", dispose); + expect(dispose).not.toHaveBeenCalled(); + hold.resolve(); + await create; + expect(dispose).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts new file mode 100644 index 00000000000..857dd2798b0 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts @@ -0,0 +1,59 @@ +import { useStore } from "zustand"; +import { createStore } from "zustand/vanilla"; + +const launches = createStore>>( + () => new Map(), +); + +function track(key: string, start: () => Promise): Promise { + const existing = launches.getState().get(key); + if (existing) return existing; + + const result = Promise.resolve() + .then(start) + .finally(() => { + const remaining = new Map(launches.getState()); + remaining.delete(key); + launches.setState(remaining, true); + }); + launches.setState(new Map(launches.getState()).set(key, result), true); + return result; +} + +const presetKey = (workspaceId: string, presetId: string) => + `preset:${workspaceId}:${presetId}`; +const terminalKey = (terminalId: string) => `terminal:${terminalId}`; + +export function runPresetOnce( + workspaceId: string, + presetId: string, + start: () => Promise, +) { + return track(presetKey(workspaceId, presetId), start); +} + +export function usePresetStarting(workspaceId: string, presetId: string) { + return useStore(launches, (pending) => + pending.has(presetKey(workspaceId, presetId)), + ); +} + +export function startPresetTerminal( + terminalId: string, + start: () => Promise, +) { + return track(terminalKey(terminalId), start); +} + +export function usePresetTerminalStarting(terminalId: string) { + return useStore(launches, (pending) => pending.has(terminalKey(terminalId))); +} + +export function afterPresetTerminalStart( + terminalId: string, + onSettled: () => void, +) { + const pending = launches.getState().get(terminalKey(terminalId)); + if (pending) void pending.then(onSettled, onSettled); + else onSettled(); +} From 600db59bba3f762d7eee4643153084ac4abda0ca Mon Sep 17 00:00:00 2001 From: Viktor Bystrov <18964918+ViktorBystrov72@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:20:25 +0500 Subject: [PATCH 2/2] fix(desktop): keep failed preset launches pending Wait for all parallel terminal creations before reporting the first rejection so a retry cannot overlap the active launch. --- .../usePresetExecution/usePresetExecution.ts | 11 +++--- .../$workspaceId/state/presetLaunches.test.ts | 34 +++++++++++++++++++ .../$workspaceId/state/presetLaunches.ts | 11 ++++++ 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts index 5ae4f1a4763..c359c967468 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePresetExecution/usePresetExecution.ts @@ -26,7 +26,10 @@ import { filterMatchingPresetsForProject } from "shared/preset-project-targeting import { getPresetsForTriggerField } from "shared/preset-trigger-selection"; import { quote } from "shell-quote"; import type { StoreApi } from "zustand/vanilla"; -import { runPresetOnce } from "../../state/presetLaunches"; +import { + runPresetOnce, + waitForPresetTerminalCreations, +} from "../../state/presetLaunches"; import type { PaneViewerData, TerminalPaneData } from "../../types"; import type { OpenAgentChat } from "../useAgentSessionLauncher"; import type { TerminalLauncher } from "../useTerminalLauncher"; @@ -274,7 +277,7 @@ export function usePresetExecution({ } case "new-tab-multi-pane": { - const ids = await Promise.all( + const ids = await waitForPresetTerminalCreations( launchCommands.length > 0 ? launchCommands.map((command) => createTerminal(command)) : [createTerminal()], @@ -289,7 +292,7 @@ export function usePresetExecution({ } case "new-tab-per-command": { - const ids = await Promise.all( + const ids = await waitForPresetTerminalCreations( launchCommands.map((command) => createTerminal(command)), ); for (const terminalId of ids) { @@ -311,7 +314,7 @@ export function usePresetExecution({ } case "active-tab-multi-pane": { - const ids = await Promise.all( + const ids = await waitForPresetTerminalCreations( launchCommands.length > 0 ? launchCommands.map((command) => createTerminal(command)) : [createTerminal()], diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts index 9ed555a3c5f..03ce7743a69 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.test.ts @@ -3,6 +3,7 @@ import { afterPresetTerminalStart, runPresetOnce, startPresetTerminal, + waitForPresetTerminalCreations, } from "./presetLaunches"; describe("preset launches", () => { @@ -34,6 +35,39 @@ describe("preset launches", () => { expect(retry).toHaveBeenCalledTimes(1); }); + it("keeps a failed multi-pane launch pending until the other creation settles", async () => { + const remaining = Promise.withResolvers(); + const failing = Promise.withResolvers(); + const firstError = new Error("first terminal failed"); + const reportError = mock((_error: unknown) => {}); + const retry = mock(async () => {}); + const initial = runPresetOnce("workspace", "multi-pane", async () => { + try { + await waitForPresetTerminalCreations([ + remaining.promise, + failing.promise, + ]); + } catch (error) { + reportError(error); + } + }); + + failing.reject(firstError); + try { + await new Promise((resolve) => setImmediate(resolve)); + expect(runPresetOnce("workspace", "multi-pane", retry)).toBe(initial); + expect(reportError).not.toHaveBeenCalled(); + } finally { + remaining.reject(new Error("second terminal failed")); + await initial; + } + + expect(reportError).toHaveBeenCalledTimes(1); + expect(reportError).toHaveBeenCalledWith(firstError); + await runPresetOnce("workspace", "multi-pane", retry); + expect(retry).toHaveBeenCalledTimes(1); + }); + it("waits for the pending terminal before running its cleanup", async () => { const hold = Promise.withResolvers(); const dispose = mock(() => {}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts index 857dd2798b0..0a078bdcb5d 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/state/presetLaunches.ts @@ -32,6 +32,17 @@ export function runPresetOnce( return track(presetKey(workspaceId, presetId), start); } +export async function waitForPresetTerminalCreations( + creations: readonly Promise[], +): Promise { + try { + return await Promise.all(creations); + } catch (error) { + await Promise.allSettled(creations); + throw error; + } +} + export function usePresetStarting(workspaceId: string, presetId: string) { return useStore(launches, (pending) => pending.has(presetKey(workspaceId, presetId)),