feat(tab-bar): add quick-launch CLI buttons (#933)
Introduce a dedicated detected-agents store slice that replaces the module-scoped detect-agents-cached cache, with a shared useDetectedAgents hook driving AgentsPane, composer, and the new QuickLaunchButton in TabBar. Extracts launchAgentInNewTab helper to share the startup-command path used by the tab bar's + button.
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Check, ChevronDown, ExternalLink, RefreshCw, Terminal } from 'lucide-react'
|
||||
import type { GlobalSettings, TuiAgent } from '../../../../shared/types'
|
||||
import { AGENT_CATALOG, AgentIcon } from '@/lib/agent-catalog'
|
||||
import { useDetectedAgents } from '@/hooks/useDetectedAgents'
|
||||
import { Button } from '../ui/button'
|
||||
import { Input } from '../ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -204,30 +205,17 @@ function AgentRow({
|
||||
}
|
||||
|
||||
export function AgentsPane({ settings, updateSettings }: AgentsPaneProps): React.JSX.Element {
|
||||
const [detectedIds, setDetectedIds] = useState<Set<string> | null>(null)
|
||||
const [isRefreshing, setIsRefreshing] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
void window.api.preflight.detectAgents().then((ids) => {
|
||||
setDetectedIds(new Set(ids))
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handleRefresh = useCallback(async (): Promise<void> => {
|
||||
// Why: refresh re-spawns the user's login shell to re-capture PATH
|
||||
// (preflight:refreshAgents on the main side). This handles the
|
||||
// "installed a new CLI, Orca doesn't see it yet" case without a restart.
|
||||
if (isRefreshing) {
|
||||
return
|
||||
}
|
||||
setIsRefreshing(true)
|
||||
try {
|
||||
const result = await window.api.preflight.refreshAgents()
|
||||
setDetectedIds(new Set(result.agents))
|
||||
} finally {
|
||||
setIsRefreshing(false)
|
||||
}
|
||||
}, [isRefreshing])
|
||||
const { detectedIds: detectedList, isRefreshing, refresh } = useDetectedAgents()
|
||||
// Why: refresh re-spawns the user's login shell to re-capture PATH
|
||||
// (preflight:refreshAgents on the main side). This handles the
|
||||
// "installed a new CLI, Orca doesn't see it yet" case without a restart.
|
||||
const handleRefresh = (): void => {
|
||||
void refresh()
|
||||
}
|
||||
const detectedIds = useMemo<Set<string> | null>(
|
||||
() => (detectedList ? new Set(detectedList) : null),
|
||||
[detectedList]
|
||||
)
|
||||
|
||||
const defaultAgent = settings.defaultTuiAgent
|
||||
const cmdOverrides = settings.agentCmdOverrides ?? {}
|
||||
@@ -338,7 +326,7 @@ export function AgentsPane({ settings, updateSettings }: AgentsPaneProps): React
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleRefresh()}
|
||||
onClick={handleRefresh}
|
||||
disabled={isRefreshing}
|
||||
title="Re-read your shell PATH and re-detect installed agents"
|
||||
className={cn(
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import React, { useCallback } from 'react'
|
||||
import { Settings as SettingsIcon } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
|
||||
import { AGENT_CATALOG, AgentIcon } from '@/lib/agent-catalog'
|
||||
import { useAppStore } from '@/store'
|
||||
import { useDetectedAgents } from '@/hooks/useDetectedAgents'
|
||||
import { launchAgentInNewTab } from '@/lib/launch-agent-in-new-tab'
|
||||
import { waitForAgentReady } from '@/lib/agent-ready-wait'
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
|
||||
export type QuickLaunchAgentMenuItemsProps = {
|
||||
worktreeId: string
|
||||
groupId: string
|
||||
/** Called after the tab is created so keyboard focus lands in the new xterm.
|
||||
* Reuses the TabBar's existing double-rAF handoff — this component does
|
||||
* not duplicate the focus logic. */
|
||||
onFocusTerminal: (tabId: string) => void
|
||||
}
|
||||
|
||||
function getCatalogEntry(agent: TuiAgent): { id: TuiAgent; label: string } | null {
|
||||
return AGENT_CATALOG.find((a) => a.id === agent) ?? null
|
||||
}
|
||||
|
||||
function orderAgents(
|
||||
defaultAgent: TuiAgent | 'blank' | null | undefined,
|
||||
detected: TuiAgent[]
|
||||
): TuiAgent[] {
|
||||
const inCatalogOrder = AGENT_CATALOG.filter((entry) => detected.includes(entry.id)).map(
|
||||
(entry) => entry.id
|
||||
)
|
||||
if (!defaultAgent || defaultAgent === 'blank' || !inCatalogOrder.includes(defaultAgent)) {
|
||||
return inCatalogOrder
|
||||
}
|
||||
// Why: surface the user's configured default first — matches the prior
|
||||
// split-button behavior where the default agent was the primary action.
|
||||
return [defaultAgent, ...inCatalogOrder.filter((id) => id !== defaultAgent)]
|
||||
}
|
||||
|
||||
function QuickLaunchAgentMenuItemsInner({
|
||||
worktreeId,
|
||||
groupId,
|
||||
onFocusTerminal
|
||||
}: QuickLaunchAgentMenuItemsProps): React.JSX.Element | null {
|
||||
const { detectedIds } = useDetectedAgents()
|
||||
const defaultAgent = useAppStore((s) => s.settings?.defaultTuiAgent)
|
||||
const openSettingsPage = useAppStore((s) => s.openSettingsPage)
|
||||
const openSettingsTarget = useAppStore((s) => s.openSettingsTarget)
|
||||
|
||||
const openAgentSettings = useCallback(() => {
|
||||
openSettingsTarget({ pane: 'agents', repoId: null })
|
||||
openSettingsPage()
|
||||
}, [openSettingsPage, openSettingsTarget])
|
||||
|
||||
const runLaunch = useCallback(
|
||||
(agent: TuiAgent) => {
|
||||
const entry = getCatalogEntry(agent)
|
||||
const label = entry?.label ?? agent
|
||||
const result = launchAgentInNewTab({ agent, worktreeId, groupId })
|
||||
if (!result) {
|
||||
toast.error(`Could not build launch command for ${label}.`)
|
||||
return
|
||||
}
|
||||
onFocusTerminal(result.tabId)
|
||||
|
||||
// Why: the watchdog guards against "queued startup command never ran" —
|
||||
// e.g. shell failed to spawn. Suppress the toast if the tab has been
|
||||
// closed or the worktree has been navigated away from before the
|
||||
// deadline (see §States: Launch failure handling).
|
||||
void waitForAgentReady(result.tabId, result.startupPlan.expectedProcess, {
|
||||
timeoutMs: 5000
|
||||
}).then((ready) => {
|
||||
if (ready.ready) {
|
||||
return
|
||||
}
|
||||
const state = useAppStore.getState()
|
||||
const stillOpen = Object.values(state.tabsByWorktree).some((tabs) =>
|
||||
tabs.some((t) => t.id === result.tabId)
|
||||
)
|
||||
if (!stillOpen) {
|
||||
return
|
||||
}
|
||||
if (state.activeWorktreeId !== worktreeId) {
|
||||
return
|
||||
}
|
||||
toast.message(`Couldn't launch ${label} — the terminal is still open.`)
|
||||
})
|
||||
},
|
||||
[worktreeId, groupId, onFocusTerminal]
|
||||
)
|
||||
|
||||
const agents = detectedIds ? orderAgents(defaultAgent, detectedIds) : []
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{agents.length === 0 ? (
|
||||
<DropdownMenuItem
|
||||
disabled
|
||||
className="gap-2 rounded-[7px] px-2 py-1.5 text-[12px] leading-5 text-muted-foreground"
|
||||
>
|
||||
No agents detected
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{agents.map((agent) => {
|
||||
const entry = getCatalogEntry(agent)
|
||||
const label = entry?.label ?? agent
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={agent}
|
||||
onSelect={() => runLaunch(agent)}
|
||||
className="gap-2 rounded-[7px] px-2 py-1.5 text-[12px] leading-5 font-medium"
|
||||
title={`Launch ${label} in a new terminal`}
|
||||
>
|
||||
<AgentIcon agent={agent} size={14} />
|
||||
{label}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
<DropdownMenuItem
|
||||
onSelect={openAgentSettings}
|
||||
className="gap-2 rounded-[7px] px-2 py-1.5 text-[12px] leading-5 font-medium text-muted-foreground"
|
||||
>
|
||||
<SettingsIcon className="size-4" />
|
||||
Agent settings…
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const QuickLaunchAgentMenuItems = React.memo(QuickLaunchAgentMenuItemsInner)
|
||||
@@ -12,6 +12,7 @@ import type { OpenFile } from '../../store/slices/editor'
|
||||
import SortableTab from './SortableTab'
|
||||
import EditorFileTab from './EditorFileTab'
|
||||
import BrowserTab from './BrowserTab'
|
||||
import { QuickLaunchAgentMenuItems } from './QuickLaunchButton'
|
||||
import { reconcileTabOrder } from './reconcile-order'
|
||||
import type { TabDragItemData } from '../tab-group/useTabDragSplit'
|
||||
import {
|
||||
@@ -428,6 +429,11 @@ function TabBarInner({
|
||||
<DropdownMenuShortcut>{NEW_FILE_SHORTCUT}</DropdownMenuShortcut>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<QuickLaunchAgentMenuItems
|
||||
worktreeId={worktreeId}
|
||||
groupId={resolvedGroupId}
|
||||
onFocusTerminal={focusTerminalTabSurface}
|
||||
/>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
@@ -11,7 +11,6 @@ import { parseGitHubIssueOrPRNumber, normalizeGitHubLinkQuery } from '@/lib/gith
|
||||
import type { RepoSlug } from '@/lib/github-links'
|
||||
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
import { buildAgentStartupPlan } from '@/lib/tui-agent-startup'
|
||||
import { detectAgentsCached } from '@/lib/detect-agents-cached'
|
||||
import { isGitRepoKind } from '../../../shared/repo-kind'
|
||||
import type {
|
||||
GitHubWorkItem,
|
||||
@@ -237,7 +236,12 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
|
||||
const [tuiAgent, setTuiAgent] = useState<TuiAgent>(
|
||||
persistDraft ? (newWorkspaceDraft?.agent ?? fallbackDefaultAgent) : fallbackDefaultAgent
|
||||
)
|
||||
const [detectedAgentIds, setDetectedAgentIds] = useState<Set<TuiAgent> | null>(null)
|
||||
const detectedAgentList = useAppStore((s) => s.detectedAgentIds)
|
||||
const ensureDetectedAgents = useAppStore((s) => s.ensureDetectedAgents)
|
||||
const detectedAgentIds = useMemo<Set<TuiAgent> | null>(
|
||||
() => (detectedAgentList ? new Set(detectedAgentList) : null),
|
||||
[detectedAgentList]
|
||||
)
|
||||
|
||||
const [yamlHooks, setYamlHooks] = useState<OrcaHooks | null>(null)
|
||||
const [checkedHooksRepoId, setCheckedHooksRepoId] = useState<string | null>(null)
|
||||
@@ -415,15 +419,15 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
|
||||
}
|
||||
}, [eligibleRepos, repoId, setRepoId])
|
||||
|
||||
// Detect installed agents once on mount (cached at module scope so the
|
||||
// page composer and quick-composer modal share a single IPC round-trip).
|
||||
// Detect installed agents once on mount via the shared store slice so the
|
||||
// page composer, quick-composer modal, settings pane, and tab-bar quick-launch
|
||||
// share a single IPC round-trip and stay in sync on refresh.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void detectAgentsCached().then((ids) => {
|
||||
void ensureDetectedAgents().then((ids) => {
|
||||
if (cancelled) {
|
||||
return
|
||||
}
|
||||
setDetectedAgentIds(new Set(ids))
|
||||
if (!newWorkspaceDraft?.agent && !settings?.defaultTuiAgent && ids.length > 0) {
|
||||
const firstInCatalogOrder = AGENT_CATALOG.find((a) => ids.includes(a.id))
|
||||
if (firstInCatalogOrder) {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { TuiAgent } from '../../../shared/types'
|
||||
|
||||
export type UseDetectedAgentsResult = {
|
||||
/** Null while detection is in flight on first load. */
|
||||
detectedIds: TuiAgent[] | null
|
||||
isLoading: boolean
|
||||
isRefreshing: boolean
|
||||
/** Re-runs `preflight.refreshAgents` and updates every subscribed surface in
|
||||
* the same tick. Idempotent while in flight: concurrent callers receive the
|
||||
* same pending promise. */
|
||||
refresh: () => Promise<TuiAgent[]>
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for detected agent IDs across the renderer.
|
||||
*
|
||||
* Why: previously AgentsPane, NewWorkspaceComposerCard, and
|
||||
* `detect-agents-cached.ts` each ran their own detection. A tab-bar button
|
||||
* that doesn't refresh when Settings → Agents refreshes would feel broken;
|
||||
* centralizing the state eliminates multi-owner drift.
|
||||
*/
|
||||
export function useDetectedAgents(): UseDetectedAgentsResult {
|
||||
const detectedIds = useAppStore((s) => s.detectedAgentIds)
|
||||
const isLoading = useAppStore((s) => s.isDetectingAgents)
|
||||
const isRefreshing = useAppStore((s) => s.isRefreshingAgents)
|
||||
const ensure = useAppStore((s) => s.ensureDetectedAgents)
|
||||
const refresh = useAppStore((s) => s.refreshDetectedAgents)
|
||||
|
||||
useEffect(() => {
|
||||
if (detectedIds === null) {
|
||||
void ensure()
|
||||
}
|
||||
}, [detectedIds, ensure])
|
||||
|
||||
return { detectedIds, isLoading, isRefreshing, refresh }
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { TuiAgent } from '../../../shared/types'
|
||||
|
||||
// Why: agent detection runs `which` for every agent binary on PATH — an IPC
|
||||
// round-trip that takes 50–200ms. The set of installed agents doesn't change
|
||||
// within a session, so cache the promise at module scope to collapse all
|
||||
// callers (composer page, quick-composer modal, "Use this task" flow, etc.)
|
||||
// onto a single resolve.
|
||||
let detectAgentsPromise: Promise<TuiAgent[]> | null = null
|
||||
|
||||
export function detectAgentsCached(): Promise<TuiAgent[]> {
|
||||
if (detectAgentsPromise) {
|
||||
return detectAgentsPromise
|
||||
}
|
||||
const pending = window.api.preflight
|
||||
.detectAgents()
|
||||
.then((ids) => ids as TuiAgent[])
|
||||
.catch(() => {
|
||||
// Allow a retry on the next mount if detection blew up (e.g. IPC
|
||||
// timeout during cold start).
|
||||
detectAgentsPromise = null
|
||||
return [] as TuiAgent[]
|
||||
})
|
||||
detectAgentsPromise = pending
|
||||
return pending
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useAppStore } from '@/store'
|
||||
import { buildAgentStartupPlan, type AgentStartupPlan } from '@/lib/tui-agent-startup'
|
||||
import { CLIENT_PLATFORM } from '@/lib/new-workspace'
|
||||
import { reconcileTabOrder } from '@/components/tab-bar/reconcile-order'
|
||||
import type { TuiAgent } from '../../../shared/types'
|
||||
|
||||
export type LaunchAgentInNewTabArgs = {
|
||||
agent: TuiAgent
|
||||
worktreeId: string
|
||||
/** The tab group the user clicked from. Keeps split-group launches in the
|
||||
* pane the user initiated from instead of falling through to the active group. */
|
||||
groupId?: string
|
||||
}
|
||||
|
||||
export type LaunchAgentInNewTabResult = {
|
||||
tabId: string
|
||||
startupPlan: AgentStartupPlan
|
||||
} | null
|
||||
|
||||
/**
|
||||
* Create a new terminal tab and queue the agent's empty-prompt launch command.
|
||||
*
|
||||
* Why: this is the single entry point for "launch agent X in a new tab" from
|
||||
* the tab-bar quick-launch menu. It mirrors the `+` button's path
|
||||
* (`createNewTerminalTab`) — createTab, flip `activeTabType` to terminal, and
|
||||
* persist the appended tab-bar order — then queues the empty-prompt agent
|
||||
* startup through the same `pendingStartupByTabId` channel the
|
||||
* new-workspace ("cmd+N") flow uses. TerminalPane consumes the queued command
|
||||
* on first mount and the local PTY provider writes it once the shell is ready
|
||||
* (see `pty-connection.ts`: startup-command path), so the CLI boots in exactly
|
||||
* the same way as a composer-initiated launch.
|
||||
*
|
||||
* Returns `null` when `buildAgentStartupPlan` cannot produce a plan (should
|
||||
* not happen with `allowEmptyPromptLaunch: true` but guarded for safety).
|
||||
*/
|
||||
export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentInNewTabResult {
|
||||
const { agent, worktreeId, groupId } = args
|
||||
const store = useAppStore.getState()
|
||||
|
||||
// Why: empty-prompt launch is the whole point of quick-launch — the user
|
||||
// just wants to get into the agent's input box with no prefilled prompt.
|
||||
const startupPlan = buildAgentStartupPlan({
|
||||
agent,
|
||||
prompt: '',
|
||||
cmdOverrides: store.settings?.agentCmdOverrides ?? {},
|
||||
platform: CLIENT_PLATFORM,
|
||||
allowEmptyPromptLaunch: true
|
||||
})
|
||||
if (!startupPlan) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Why: queue the startup command BEFORE TerminalPane mounts — it captures
|
||||
// `pendingStartupByTabId[tabId]` in useState on first render. If the queue
|
||||
// lands after mount the agent binary never starts; the user sees a bare shell.
|
||||
// Since both calls happen synchronously in the same React batch, the queue
|
||||
// is in place by the time the pane commits.
|
||||
const tab = store.createTab(worktreeId, groupId)
|
||||
store.queueTabStartupCommand(tab.id, { command: startupPlan.launchCommand })
|
||||
|
||||
// Why: match the `+` button's `createNewTerminalTab` sequence — without
|
||||
// `setActiveTabType('terminal')`, a worktree currently showing an editor
|
||||
// file keeps rendering the editor and the new terminal tab stays invisible.
|
||||
store.setActiveTabType('terminal')
|
||||
|
||||
// Why: persist the tab-bar order with the new terminal appended. Without
|
||||
// this, `reconcileTabOrder` falls back to terminals-first when the stored
|
||||
// order is unset, which can jump the new tab to index 0 instead of the end.
|
||||
const fresh = useAppStore.getState()
|
||||
const termIds = (fresh.tabsByWorktree[worktreeId] ?? []).map((t) => t.id)
|
||||
const editorIds = fresh.openFiles.filter((f) => f.worktreeId === worktreeId).map((f) => f.id)
|
||||
const browserIds = (fresh.browserTabsByWorktree?.[worktreeId] ?? []).map((t) => t.id)
|
||||
const base = reconcileTabOrder(
|
||||
fresh.tabBarOrderByWorktree[worktreeId],
|
||||
termIds,
|
||||
editorIds,
|
||||
browserIds
|
||||
)
|
||||
const order = base.filter((id) => id !== tab.id)
|
||||
order.push(tab.id)
|
||||
fresh.setTabBarOrder(worktreeId, order)
|
||||
|
||||
return { tabId: tab.id, startupPlan }
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { toast } from 'sonner'
|
||||
import { useAppStore } from '@/store'
|
||||
import { AGENT_CATALOG } from '@/lib/agent-catalog'
|
||||
import { detectAgentsCached } from '@/lib/detect-agents-cached'
|
||||
import { waitForAgentReady } from '@/lib/agent-ready-wait'
|
||||
import { buildAgentStartupPlan } from '@/lib/tui-agent-startup'
|
||||
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
@@ -106,7 +105,7 @@ export async function launchWorkItemDirect(args: LaunchWorkItemDirectArgs): Prom
|
||||
}
|
||||
|
||||
const settings = store.settings
|
||||
const detectedIds = new Set(await detectAgentsCached())
|
||||
const detectedIds = new Set(await store.ensureDetectedAgents())
|
||||
const effectiveAgent = pickAgent(settings?.defaultTuiAgent, detectedIds)
|
||||
|
||||
const setupResolution = await resolveSetupDecision(repoId, repo)
|
||||
|
||||
@@ -15,6 +15,7 @@ import { createBrowserSlice } from './slices/browser'
|
||||
import { createRateLimitSlice } from './slices/rate-limits'
|
||||
import { createSshSlice } from './slices/ssh'
|
||||
import { createDiffCommentsSlice } from './slices/diffComments'
|
||||
import { createDetectedAgentsSlice } from './slices/detected-agents'
|
||||
import { e2eConfig } from '@/lib/e2e-config'
|
||||
|
||||
export const useAppStore = create<AppState>()((...a) => ({
|
||||
@@ -32,7 +33,8 @@ export const useAppStore = create<AppState>()((...a) => ({
|
||||
...createBrowserSlice(...a),
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createDiffCommentsSlice(...a)
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a)
|
||||
}))
|
||||
|
||||
export type { AppState } from './types'
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { StateCreator } from 'zustand'
|
||||
import type { AppState } from '../types'
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
|
||||
export type DetectedAgentsSlice = {
|
||||
detectedAgentIds: TuiAgent[] | null
|
||||
isDetectingAgents: boolean
|
||||
isRefreshingAgents: boolean
|
||||
/** Runs `preflight.detectAgents` once per session. Subsequent callers reuse
|
||||
* the in-flight promise so every surface sees the same result. */
|
||||
ensureDetectedAgents: () => Promise<TuiAgent[]>
|
||||
/** Re-runs `preflight.refreshAgents` (re-reads shell PATH). Concurrent callers
|
||||
* receive the same pending promise; store fields update once on resolve so
|
||||
* every subscribed surface re-renders in the same tick. */
|
||||
refreshDetectedAgents: () => Promise<TuiAgent[]>
|
||||
}
|
||||
|
||||
// Why: these are module-scoped (not in the store) so we can deduplicate
|
||||
// concurrent callers without storing a Promise in Zustand state.
|
||||
let detectPromise: Promise<TuiAgent[]> | null = null
|
||||
let refreshPromise: Promise<TuiAgent[]> | null = null
|
||||
|
||||
export const createDetectedAgentsSlice: StateCreator<AppState, [], [], DetectedAgentsSlice> = (
|
||||
set,
|
||||
get
|
||||
) => ({
|
||||
detectedAgentIds: null,
|
||||
isDetectingAgents: false,
|
||||
isRefreshingAgents: false,
|
||||
|
||||
ensureDetectedAgents: () => {
|
||||
const existing = get().detectedAgentIds
|
||||
if (existing) {
|
||||
return Promise.resolve(existing)
|
||||
}
|
||||
if (detectPromise) {
|
||||
return detectPromise
|
||||
}
|
||||
set({ isDetectingAgents: true })
|
||||
const pending = window.api.preflight
|
||||
.detectAgents()
|
||||
.then((ids) => {
|
||||
const typed = ids as TuiAgent[]
|
||||
set({ detectedAgentIds: typed, isDetectingAgents: false })
|
||||
return typed
|
||||
})
|
||||
.catch(() => {
|
||||
// Why: allow a retry on the next call if detection blew up (IPC timeout
|
||||
// during cold start). Do not cache the failure.
|
||||
detectPromise = null
|
||||
set({ isDetectingAgents: false })
|
||||
return [] as TuiAgent[]
|
||||
})
|
||||
detectPromise = pending
|
||||
return pending
|
||||
},
|
||||
|
||||
refreshDetectedAgents: () => {
|
||||
if (refreshPromise) {
|
||||
return refreshPromise
|
||||
}
|
||||
set({ isRefreshingAgents: true })
|
||||
const pending = window.api.preflight
|
||||
.refreshAgents()
|
||||
.then((result) => {
|
||||
const typed = result.agents as TuiAgent[]
|
||||
set({ detectedAgentIds: typed, isRefreshingAgents: false })
|
||||
// Why: once refresh has run, treat its result as the current detection
|
||||
// snapshot so `ensureDetectedAgents` short-circuits.
|
||||
detectPromise = Promise.resolve(typed)
|
||||
return typed
|
||||
})
|
||||
.catch(() => {
|
||||
set({ isRefreshingAgents: false })
|
||||
return get().detectedAgentIds ?? []
|
||||
})
|
||||
.finally(() => {
|
||||
refreshPromise = null
|
||||
})
|
||||
refreshPromise = pending
|
||||
return pending
|
||||
}
|
||||
})
|
||||
@@ -99,6 +99,7 @@ import { createBrowserSlice } from './browser'
|
||||
import { createRateLimitSlice } from './rate-limits'
|
||||
import { createSshSlice } from './ssh'
|
||||
import { createDiffCommentsSlice } from './diffComments'
|
||||
import { createDetectedAgentsSlice } from './detected-agents'
|
||||
|
||||
function createTestStore() {
|
||||
return create<AppState>()((...a) => ({
|
||||
@@ -116,7 +117,8 @@ function createTestStore() {
|
||||
...createBrowserSlice(...a),
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createDiffCommentsSlice(...a)
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a)
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import { createBrowserSlice } from './browser'
|
||||
import { createRateLimitSlice } from './rate-limits'
|
||||
import { createSshSlice } from './ssh'
|
||||
import { createDiffCommentsSlice } from './diffComments'
|
||||
import { createDetectedAgentsSlice } from './detected-agents'
|
||||
|
||||
export const TEST_REPO = {
|
||||
id: 'repo1',
|
||||
@@ -48,7 +49,8 @@ export function createTestStore() {
|
||||
...createBrowserSlice(...a),
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createDiffCommentsSlice(...a)
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a)
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ import { createBrowserSlice } from './browser'
|
||||
import { createRateLimitSlice } from './rate-limits'
|
||||
import { createSshSlice } from './ssh'
|
||||
import { createDiffCommentsSlice } from './diffComments'
|
||||
import { createDetectedAgentsSlice } from './detected-agents'
|
||||
|
||||
const WT = 'repo1::/tmp/feature'
|
||||
|
||||
@@ -113,7 +114,8 @@ function createTestStore() {
|
||||
...createBrowserSlice(...a),
|
||||
...createRateLimitSlice(...a),
|
||||
...createSshSlice(...a),
|
||||
...createDiffCommentsSlice(...a)
|
||||
...createDiffCommentsSlice(...a),
|
||||
...createDetectedAgentsSlice(...a)
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { BrowserSlice } from './slices/browser'
|
||||
import type { RateLimitSlice } from './slices/rate-limits'
|
||||
import type { SshSlice } from './slices/ssh'
|
||||
import type { DiffCommentsSlice } from './slices/diffComments'
|
||||
import type { DetectedAgentsSlice } from './slices/detected-agents'
|
||||
|
||||
export type AppState = RepoSlice &
|
||||
WorktreeSlice &
|
||||
@@ -28,4 +29,5 @@ export type AppState = RepoSlice &
|
||||
BrowserSlice &
|
||||
RateLimitSlice &
|
||||
SshSlice &
|
||||
DiffCommentsSlice
|
||||
DiffCommentsSlice &
|
||||
DetectedAgentsSlice
|
||||
|
||||
Reference in New Issue
Block a user