diff --git a/src/renderer/src/components/sidebar/LinearAgentSkillSetupDialog.tsx b/src/renderer/src/components/sidebar/LinearAgentSkillSetupDialog.tsx new file mode 100644 index 000000000..1dc807385 --- /dev/null +++ b/src/renderer/src/components/sidebar/LinearAgentSkillSetupDialog.tsx @@ -0,0 +1,167 @@ +import type { ComponentProps } from 'react' +import { CheckCircle2, Info } from 'lucide-react' +import { IntegrationStatusPill } from '@/components/integration-status-pill' +import { AgentSkillSetupPanel } from '@/components/settings/AgentSkillSetupPanel' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { + AGENT_SKILL_CLI_PREREQUISITE_NOTICE, + isOrcaCliAvailableOnPath +} from '@/lib/agent-skill-cli-prerequisite' +import { translate } from '@/i18n/i18n' + +type AgentSkillSetupPanelProps = ComponentProps + +type LinearAgentSkillSetupDialogProps = { + open: boolean + showSuccess: boolean + successDescription: string + missingLabel: string + command: string + terminalShellOverride?: string + installed: boolean + loading: boolean + error: string | null + getPrerequisiteStatus?: AgentSkillSetupPanelProps['getPrerequisiteStatus'] + onBeforeOpenTerminal: AgentSkillSetupPanelProps['onBeforeOpenTerminal'] + onRecheck: AgentSkillSetupPanelProps['onRecheck'] + onOpenChange: (open: boolean) => void + onDismissPermanently: () => void + onSnoozeForSession: () => void + onDone: () => void +} + +export function LinearAgentSkillSetupDialog({ + open, + showSuccess, + successDescription, + missingLabel, + command, + terminalShellOverride, + installed, + loading, + error, + getPrerequisiteStatus, + onBeforeOpenTerminal, + onRecheck, + onOpenChange, + onDismissPermanently, + onSnoozeForSession, + onDone +}: LinearAgentSkillSetupDialogProps): React.JSX.Element { + return ( + + + {showSuccess ? ( + <> +
+ + + {translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.successTitle', + 'Linear ticket access is ready' + )} + + {successDescription} + +
+ + + {translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.successStatus', + 'Linear ticket access ready' + )} + +
+
+ + + + + ) : ( + <> +
+ + + {translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.modalTitle', + 'Enable Linear ticket access' + )} + + + {translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.modalDescription', + 'Install the Linear skill from a terminal.' + )} + + +
+ +

+ {translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.modalPrompt', + 'Enable agents to read and edit the attached Linear ticket.' + )} +

+
+
+ + + + + + + )} +
+
+ ) +} diff --git a/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx b/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx index b291a3329..9ed0ccf32 100644 --- a/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx +++ b/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx @@ -65,6 +65,14 @@ vi.mock('../settings/AgentSkillSetupPanel', () => ({ + ) } @@ -104,12 +112,47 @@ async function renderPrompt( return container } +async function updatePrompt( + props: ComponentProps +): Promise { + await act(async () => { + root?.render() + }) + await act(async () => {}) +} + +function findBodyButton(label: string): HTMLButtonElement | undefined { + return Array.from(document.body.querySelectorAll('button')).find( + (button) => button.textContent === label + ) +} + +async function settleRender(): Promise { + await act(async () => {}) + await act(async () => {}) +} + +async function showSuccessfulModalRecheck(): Promise { + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + + mocks.getCliStatus.mockResolvedValue(cliStatus({})) + mocks.skillState.refresh.mockImplementationOnce(async () => { + mocks.skillState.installed = true + }) + + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() +} + describe('LinearAgentSkillSetupPrompt', () => { beforeEach(() => { mocks.skillState.installed = false mocks.skillState.loading = false mocks.skillState.error = null - mocks.skillState.refresh.mockClear() + mocks.skillState.refresh.mockReset() + mocks.skillState.refresh.mockImplementation(async () => {}) mocks.useInstalledAgentSkill.mockReset() mocks.useInstalledAgentSkill.mockReturnValue(mocks.skillState) mocks.getCliStatus.mockReset() @@ -381,6 +424,380 @@ describe('LinearAgentSkillSetupPrompt', () => { ) }) + it('keeps the modal open with success copy after a modal Re-check succeeds', async () => { + await showSuccessfulModalRecheck() + + expect(document.body.textContent).toContain('Linear ticket access is ready') + expect(document.body.textContent).toContain( + 'Agents can now read and update linked Linear tickets from this workspace.' + ) + expect(document.body.textContent).toContain('Linear ticket access ready') + expect(document.body.textContent).not.toContain('Mock install') + expect(document.body.textContent).not.toContain("Don't show again") + expect(document.body.textContent).not.toContain('Not now') + }) + + it('closes success with Done without permanent dismissal or session snooze', async () => { + await showSuccessfulModalRecheck() + + await act(async () => { + findBodyButton('Done')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + expect(window.localStorage.getItem(HOST_DISMISS_STORAGE_KEY)).toBeNull() + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + + await act(async () => { + root?.unmount() + }) + root = null + container?.remove() + container = null + + mocks.getCliStatus.mockResolvedValue( + cliStatus({ state: 'not_installed', pathConfigured: false }) + ) + mocks.skillState.installed = false + + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + }) + + it('closes success with the dialog close button without permanent dismissal or session snooze', async () => { + await showSuccessfulModalRecheck() + + await act(async () => { + findBodyButton('Close')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + expect(window.localStorage.getItem(HOST_DISMISS_STORAGE_KEY)).toBeNull() + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + + await act(async () => { + root?.unmount() + }) + root = null + container?.remove() + container = null + + mocks.getCliStatus.mockResolvedValue( + cliStatus({ state: 'not_installed', pathConfigured: false }) + ) + mocks.skillState.installed = false + + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + }) + + it('closes success with Escape without permanent dismissal or session snooze', async () => { + await showSuccessfulModalRecheck() + + await act(async () => { + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) + }) + await settleRender() + + expect(window.localStorage.getItem(HOST_DISMISS_STORAGE_KEY)).toBeNull() + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + }) + + it('closes success with outside click without permanent dismissal or session snooze', async () => { + await showSuccessfulModalRecheck() + + const overlay = document.body.querySelector('[data-slot="dialog-overlay"]') + await act(async () => { + overlay?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })) + overlay?.dispatchEvent(new PointerEvent('pointerup', { bubbles: true })) + overlay?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + expect(window.localStorage.getItem(HOST_DISMISS_STORAGE_KEY)).toBeNull() + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + }) + + it('still removes the inline prompt after an inline Re-check succeeds', async () => { + const rendered = await renderPrompt({ linked: true, remote: false }) + + mocks.getCliStatus.mockResolvedValue(cliStatus({})) + mocks.skillState.refresh.mockImplementationOnce(async () => { + mocks.skillState.installed = true + }) + + const recheckButton = Array.from(rendered.querySelectorAll('button')).find( + (button) => button.textContent === 'Re-check' + ) + await act(async () => { + recheckButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + expect(rendered.textContent).not.toContain('Set up Linear agent skill') + }) + + it('keeps the missing setup modal visible after a partial Re-check', async () => { + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + + mocks.getCliStatus.mockResolvedValue(cliStatus({})) + + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + expect(document.body.textContent).toContain('Linear agent skill is missing.') + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + }) + + it('keeps the modal mounted and the Re-check action loading during a slow modal check', async () => { + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + + let resolveCliStatus: (status: CliInstallStatus) => void = () => {} + let resolveSkillRefresh: () => void = () => {} + mocks.getCliStatus.mockReturnValue( + new Promise((resolve) => { + resolveCliStatus = resolve + }) + ) + mocks.skillState.refresh.mockReturnValue( + new Promise((resolve) => { + resolveSkillRefresh = resolve + }) + ) + + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + expect(mocks.panelProps.at(-1)).toEqual(expect.objectContaining({ loading: true })) + + resolveCliStatus(cliStatus({})) + mocks.skillState.installed = true + resolveSkillRefresh() + await settleRender() + }) + + it('ignores stale CLI success after the runtime context changes during Re-check', async () => { + await renderPrompt({ + linked: true, + remote: false, + surface: 'modal', + currentPlatform: 'win32', + settings: { + localAgentRuntime: 'wsl', + localAgentWslDistro: 'Fedora', + terminalWindowsShell: 'wsl.exe', + activeRuntimeEnvironmentId: null + } + }) + + let resolveWslStatus: (status: CliInstallStatus) => void = () => {} + mocks.getWslCliStatus.mockReturnValueOnce( + new Promise((resolve) => { + resolveWslStatus = resolve + }) + ) + mocks.skillState.refresh.mockReturnValueOnce(Promise.resolve()) + + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + mocks.getCliStatus.mockResolvedValue( + cliStatus({ state: 'not_installed', pathConfigured: false }) + ) + mocks.skillState.installed = true + await updatePrompt({ + linked: true, + remote: false, + surface: 'modal', + currentPlatform: 'win32', + settings: { + localAgentRuntime: 'host', + terminalWindowsShell: 'powershell.exe', + activeRuntimeEnvironmentId: null + } + }) + + resolveWslStatus(cliStatus({})) + await settleRender() + + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + expect(document.body.textContent).toContain('Orca CLI is missing.') + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + }) + + it('ignores stale prerequisite CLI status callbacks after the runtime context changes', async () => { + let reportHostCliStatus: ((status: CliInstallStatus) => void) | null = null + mocks.ensureCli.mockImplementationOnce( + async (options?: { onStatusChange?: (status: CliInstallStatus) => void }) => { + reportHostCliStatus = options?.onStatusChange ?? null + return null + } + ) + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + + await act(async () => { + findBodyButton('Mock install')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + mocks.getWslCliStatus.mockResolvedValue( + cliStatus({ state: 'not_installed', pathConfigured: false }) + ) + mocks.skillState.installed = true + await updatePrompt({ + linked: true, + remote: false, + surface: 'modal', + currentPlatform: 'win32', + settings: { + localAgentRuntime: 'wsl', + localAgentWslDistro: 'Fedora', + terminalWindowsShell: 'wsl.exe', + activeRuntimeEnvironmentId: null + } + }) + + await act(async () => { + reportHostCliStatus?.(cliStatus({})) + }) + await settleRender() + + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + expect(document.body.textContent).toContain('Orca CLI is missing.') + expect(document.body.textContent).not.toContain('Linear ticket access is ready') + }) + + it('accepts same-context prerequisite CLI status callbacks after a newer Re-check', async () => { + let reportHostCliStatus: ((status: CliInstallStatus) => void) | null = null + let resolveEnsureCli: () => void = () => {} + mocks.ensureCli.mockImplementationOnce( + async (options?: { onStatusChange?: (status: CliInstallStatus) => void }) => { + reportHostCliStatus = options?.onStatusChange ?? null + await new Promise((resolve) => { + resolveEnsureCli = resolve + }) + return null + } + ) + await renderPrompt({ linked: true, remote: false, surface: 'modal' }) + + await act(async () => { + findBodyButton('Mock install')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + + mocks.getCliStatus.mockResolvedValue( + cliStatus({ state: 'not_installed', pathConfigured: false }) + ) + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + await act(async () => { + reportHostCliStatus?.(cliStatus({})) + resolveEnsureCli() + }) + await settleRender() + + expect(document.body.textContent).toContain( + 'Enable agents to read and edit the attached Linear ticket.' + ) + expect(document.body.textContent).toContain('Linear agent skill is missing.') + expect(document.body.textContent).not.toContain('Orca CLI is missing.') + }) + + it('ignores older same-context CLI refreshes that finish after a newer Re-check', async () => { + const rendered = await renderPrompt({ linked: true, remote: false }) + const recheckButton = Array.from(rendered.querySelectorAll('button')).find( + (button) => button.textContent === 'Re-check' + ) + let resolveOlderCliStatus: (status: CliInstallStatus) => void = () => {} + mocks.getCliStatus.mockReturnValueOnce( + new Promise((resolve) => { + resolveOlderCliStatus = resolve + }) + ) + mocks.getCliStatus.mockResolvedValue(cliStatus({})) + mocks.skillState.refresh.mockImplementation(async () => { + mocks.skillState.installed = true + }) + + await act(async () => { + recheckButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + recheckButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + expect(rendered.textContent).not.toContain('Set up Linear agent skill') + + resolveOlderCliStatus(cliStatus({ state: 'not_installed', pathConfigured: false })) + await settleRender() + + expect(rendered.textContent).not.toContain('Set up Linear agent skill') + }) + + it('uses WSL-specific success copy for a selected WSL runtime', async () => { + await renderPrompt({ + linked: true, + remote: false, + surface: 'modal', + currentPlatform: 'win32', + settings: { + localAgentRuntime: 'wsl', + localAgentWslDistro: 'Fedora', + terminalWindowsShell: 'wsl.exe', + activeRuntimeEnvironmentId: null + } + }) + + mocks.getWslCliStatus.mockResolvedValue(cliStatus({})) + mocks.skillState.refresh.mockImplementationOnce(async () => { + mocks.skillState.installed = true + }) + + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + expect(document.body.textContent).toContain( + 'WSL agents can now use linked Linear tickets from this workspace.' + ) + }) + + it('uses remote-safe success copy for remote workspaces', async () => { + await renderPrompt({ linked: true, remote: true, surface: 'modal' }) + + mocks.getCliStatus.mockResolvedValue(cliStatus({})) + mocks.skillState.refresh.mockImplementationOnce(async () => { + mocks.skillState.installed = true + }) + + await act(async () => { + findBodyButton('Re-check')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settleRender() + + expect(document.body.textContent).toContain( + 'Host agents can now use linked Linear tickets. Remote agent environments may still need their own setup.' + ) + }) + it('permanently dismisses the modal-only prompt when requested', async () => { await renderPrompt({ linked: true, remote: false, surface: 'modal' }) diff --git a/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.tsx b/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.tsx index e260d304f..a330acb45 100644 --- a/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.tsx +++ b/src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.tsx @@ -1,16 +1,8 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' -import { Info, RefreshCw, TicketCheck, X } from 'lucide-react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { RefreshCw, TicketCheck, X } from 'lucide-react' import type { CliInstallStatus } from '../../../../shared/cli-install-types' import type { SkillDiscoveryTarget } from '../../../../shared/skills' import { Button } from '@/components/ui/button' -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle -} from '@/components/ui/dialog' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill @@ -20,12 +12,10 @@ import { buildAgentFeatureSkillInstallCommand } from '@/lib/agent-feature-install-commands' import { - AGENT_SKILL_CLI_PREREQUISITE_NOTICE, ensureOrcaCliAvailableForAgentSkillTerminal, isOrcaCliAvailableOnPath } from '@/lib/agent-skill-cli-prerequisite' import { cn } from '@/lib/utils' -import { AgentSkillSetupPanel } from '../settings/AgentSkillSetupPanel' import { buildSkillInstallCommandForRuntime, ensureWslCliAvailableForAgentSkillTerminal, @@ -39,6 +29,7 @@ import { readLocalDismissed, type LinearAgentSkillPromptSettings } from './linear-agent-skill-runtime' +import { LinearAgentSkillSetupDialog } from './LinearAgentSkillSetupDialog' import { translate } from '@/i18n/i18n' // Why: closing the workspace modal means "not now"; keep it quiet for this @@ -60,6 +51,8 @@ type LinearAgentSkillSetupPromptProps = { className?: string } +type SetupCheckResult = 'idle' | 'checking' | 'ready' + export function LinearAgentSkillSetupPrompt({ linked, remote, @@ -71,10 +64,25 @@ export function LinearAgentSkillSetupPrompt({ const [cliStatus, setCliStatus] = useState(null) const [cliLoading, setCliLoading] = useState(linked) const [setupDialogOpen, setSetupDialogOpen] = useState(false) + const [setupCheckResult, setSetupCheckResult] = useState('idle') + const [activeSetupCheckIdentity, setActiveSetupCheckIdentity] = useState(null) const agentRuntime = useMemo( () => getLinearPromptAgentRuntime(settings, currentPlatform, remote), [currentPlatform, remote, settings] ) + const setupCheckIdentity = useMemo( + () => + JSON.stringify({ + remote, + runtime: agentRuntime.runtime, + wslDistro: agentRuntime.wslDistro ?? null, + activeRuntimeEnvironmentId: settings?.activeRuntimeEnvironmentId ?? null + }), + [agentRuntime.runtime, agentRuntime.wslDistro, remote, settings?.activeRuntimeEnvironmentId] + ) + const currentSetupCheckIdentityRef = useRef(setupCheckIdentity) + const cliRefreshGenerationRef = useRef(0) + currentSetupCheckIdentityRef.current = setupCheckIdentity const skillDiscoveryTarget = useMemo( () => agentRuntime.runtime === 'wsl' @@ -114,33 +122,70 @@ export function LinearAgentSkillSetupPrompt({ setSessionSnoozed(sessionSnoozedRuntimeKeys.has(localDismissStorageKey)) }, [localDismissStorageKey]) + const writeCliStatusIfCurrent = useCallback( + (requestIdentity: string, requestGeneration: number, write: () => void): void => { + if ( + requestGeneration === cliRefreshGenerationRef.current && + currentSetupCheckIdentityRef.current === requestIdentity + ) { + write() + } + }, + [] + ) + + const writeCliStatusForIdentity = useCallback((requestIdentity: string, write: () => void) => { + if (currentSetupCheckIdentityRef.current === requestIdentity) { + write() + } + }, []) + const refreshCliStatus = useCallback(async (): Promise => { + const requestIdentity = setupCheckIdentity + const requestGeneration = ++cliRefreshGenerationRef.current + const writeIfCurrent = (write: () => void): void => { + writeCliStatusIfCurrent(requestIdentity, requestGeneration, write) + } + if (!linked) { - setCliStatus(null) - setCliLoading(false) + writeIfCurrent(() => { + setCliStatus(null) + setCliLoading(false) + }) return } setCliLoading(true) try { - setCliStatus( - await (agentRuntime.runtime === 'wsl' - ? window.api.cli.getWslInstallStatus(getWslCliDistroRequest(agentRuntime)) - : window.api.cli.getInstallStatus()) - ) + const nextStatus = await (agentRuntime.runtime === 'wsl' + ? window.api.cli.getWslInstallStatus(getWslCliDistroRequest(agentRuntime)) + : window.api.cli.getInstallStatus()) + writeIfCurrent(() => setCliStatus(nextStatus)) } catch { - setCliStatus(null) + writeIfCurrent(() => setCliStatus(null)) } finally { - setCliLoading(false) + writeIfCurrent(() => setCliLoading(false)) } - }, [agentRuntime, linked]) + }, [agentRuntime, linked, setupCheckIdentity, writeCliStatusIfCurrent]) useEffect(() => { void refreshCliStatus() }, [refreshCliStatus]) const cliAvailable = isOrcaCliAvailableOnPath(cliStatus) - const missingSetup = - linked && !dismissed && !cliLoading && !skill.loading && !(cliAvailable && skill.installed) + const setupReady = linked && !cliLoading && !skill.loading && cliAvailable && skill.installed + const missingSetup = linked && !dismissed && !cliLoading && !skill.loading && !setupReady + const explicitCheckMatchesContext = activeSetupCheckIdentity === setupCheckIdentity + const showCheckingModal = + surface === 'modal' && + setupDialogOpen && + setupCheckResult === 'checking' && + explicitCheckMatchesContext + const showSuccessModal = + surface === 'modal' && + setupDialogOpen && + setupCheckResult === 'ready' && + explicitCheckMatchesContext + const showSetupModal = setupDialogOpen && (missingSetup || showCheckingModal || showSuccessModal) useEffect(() => { if (surface === 'modal' && missingSetup) { @@ -148,12 +193,51 @@ export function LinearAgentSkillSetupPrompt({ } }, [missingSetup, surface]) + useEffect(() => { + if (setupCheckResult === 'idle') { + return + } + if (!explicitCheckMatchesContext) { + setSetupCheckResult('idle') + setActiveSetupCheckIdentity(null) + return + } + // Why: refreshes update CLI and skill state independently, so success is + // promoted only after the current render observes both ready for this target. + if (setupCheckResult === 'checking' && setupReady) { + setSetupCheckResult('ready') + return + } + if (missingSetup) { + setSetupCheckResult('idle') + } + }, [explicitCheckMatchesContext, missingSetup, setupCheckResult, setupReady]) + const dismissPermanently = (): void => { localStorage.setItem(localDismissStorageKey, '1') setLocalDismissed(true) setSetupDialogOpen(false) } + const closeSuccessModal = (): void => { + setSetupDialogOpen(false) + } + + const successDescription = remote + ? translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.successDescriptionRemote', + 'Host agents can now use linked Linear tickets. Remote agent environments may still need their own setup.' + ) + : agentRuntime.runtime === 'wsl' + ? translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.successDescriptionWsl', + 'WSL agents can now use linked Linear tickets from this workspace.' + ) + : translate( + 'auto.components.sidebar.LinearAgentSkillSetupPrompt.successDescription', + 'Agents can now read and update linked Linear tickets from this workspace.' + ) + const snoozeForSession = (): void => { sessionSnoozedRuntimeKeys.add(localDismissStorageKey) setSessionSnoozed(true) @@ -176,115 +260,76 @@ export function LinearAgentSkillSetupPrompt({ 'Linear agent skill is missing.' ) - if (!missingSetup) { + if (surface !== 'modal' && !missingSetup) { + return null + } + + if (surface === 'modal' && !showSetupModal) { return null } const setupDialog = ( - window.api.cli.getWslInstallStatus(getWslCliDistroRequest(agentRuntime)) + : undefined + } + onBeforeOpenTerminal={async () => { + const requestIdentity = setupCheckIdentity + const writeIfCurrent = (write: () => void): void => { + writeCliStatusForIdentity(requestIdentity, write) + } + const nextStatus = + agentRuntime.runtime === 'wsl' + ? await ensureWslCliAvailableForAgentSkillTerminal(agentRuntime) + : await ensureOrcaCliAvailableForAgentSkillTerminal({ + onStatusChange: (nextCliStatus) => { + writeIfCurrent(() => setCliStatus(nextCliStatus)) + } + }) + if (agentRuntime.runtime === 'wsl') { + writeIfCurrent(() => setCliStatus(nextStatus)) + } + }} + onRecheck={async () => { + if (surface === 'modal') { + setActiveSetupCheckIdentity(setupCheckIdentity) + setSetupCheckResult('checking') + await Promise.all([refreshCliStatus(), skill.refresh()]) + return + } + await refreshCliStatus() + await skill.refresh() + }} onOpenChange={(open) => { if (open) { setSetupDialogOpen(true) return } + if (showSuccessModal) { + closeSuccessModal() + return + } if (surface === 'modal') { snoozeForSession() return } setSetupDialogOpen(false) }} - > - -
- - - {translate( - 'auto.components.sidebar.LinearAgentSkillSetupPrompt.modalTitle', - 'Enable Linear ticket access' - )} - - - {translate( - 'auto.components.sidebar.LinearAgentSkillSetupPrompt.modalDescription', - 'Install the Linear skill from a terminal.' - )} - - -
- -

- {translate( - 'auto.components.sidebar.LinearAgentSkillSetupPrompt.modalPrompt', - 'Enable agents to read and edit the attached Linear ticket.' - )} -

-
-
- window.api.cli.getWslInstallStatus(getWslCliDistroRequest(agentRuntime)) - : undefined - } - isPrerequisiteAvailable={isOrcaCliAvailableOnPath} - onBeforeOpenTerminal={async () => { - const nextStatus = - agentRuntime.runtime === 'wsl' - ? await ensureWslCliAvailableForAgentSkillTerminal(agentRuntime) - : await ensureOrcaCliAvailableForAgentSkillTerminal({ - onStatusChange: setCliStatus - }) - if (agentRuntime.runtime === 'wsl') { - setCliStatus(nextStatus) - } - }} - onRecheck={async () => { - await refreshCliStatus() - await skill.refresh() - }} - /> - - - - -
-
+ onDismissPermanently={dismissPermanently} + onSnoozeForSession={snoozeForSession} + onDone={closeSuccessModal} + /> ) if (surface === 'modal') { diff --git a/src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx b/src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx new file mode 100644 index 000000000..c2e3a282d --- /dev/null +++ b/src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx @@ -0,0 +1,163 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { + DiscoveredSkill, + SkillDiscoveryResult, + SkillDiscoveryTarget +} from '../../../shared/skills' +import { + GLOBAL_AGENT_SKILL_SOURCE_KINDS, + type InstalledAgentSkillState, + _installedAgentSkillDiscoveryInternalsForTests, + useInstalledAgentSkill +} from './useInstalledAgentSkills' + +let root: Root | null = null +let container: HTMLDivElement | null = null +let latestState: InstalledAgentSkillState | null = null + +function skill(overrides: Partial): DiscoveredSkill { + return { + id: 'skill-1', + name: 'Example Skill', + description: null, + providers: ['agent-skills'], + sourceKind: 'home', + sourceLabel: 'Agent skills home', + rootPath: '/Users/test/.agents/skills', + directoryPath: '/Users/test/.agents/skills/example-skill', + skillFilePath: '/Users/test/.agents/skills/example-skill/SKILL.md', + installed: true, + fileCount: 1, + updatedAt: null, + ...overrides + } +} + +function discoveryResult(skills: DiscoveredSkill[] = []): SkillDiscoveryResult { + return { + skills, + sources: [], + scannedAt: Date.now() + } +} + +function deferred(): { + promise: Promise + resolve: (value: T) => void + reject: (reason?: unknown) => void +} { + let resolve!: (value: T) => void + let reject!: (reason?: unknown) => void + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise + reject = rejectPromise + }) + return { promise, resolve, reject } +} + +function Probe({ discoveryTarget }: { discoveryTarget?: SkillDiscoveryTarget }): null { + latestState = useInstalledAgentSkill('linear-tickets', { + discoveryTarget, + sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS + }) + return null +} + +async function renderProbe(discoveryTarget?: SkillDiscoveryTarget): Promise { + if (!container) { + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + } + await act(async () => { + root?.render() + }) +} + +afterEach(async () => { + if (root) { + await act(async () => { + root?.unmount() + }) + } + root = null + container?.remove() + container = null + latestState = null + _installedAgentSkillDiscoveryInternalsForTests.reset() + vi.restoreAllMocks() + Reflect.deleteProperty(window, 'api') +}) + +describe('useInstalledAgentSkill', () => { + it('ignores stale discovery results after the discovery target changes', async () => { + const hostScan = deferred() + const wslScan = deferred() + const discover = vi + .fn<(target?: SkillDiscoveryTarget) => Promise>() + .mockReturnValueOnce(hostScan.promise) + .mockReturnValueOnce(wslScan.promise) + Object.defineProperty(window, 'api', { + configurable: true, + value: { skills: { discover } } + }) + + await renderProbe() + await renderProbe({ runtime: 'wsl', wslDistro: 'Fedora' }) + + wslScan.resolve(discoveryResult([])) + await act(async () => { + await wslScan.promise + }) + + expect(latestState?.installed).toBe(false) + + hostScan.resolve(discoveryResult([skill({ name: 'linear-tickets' })])) + await act(async () => { + await hostScan.promise + }) + + expect(latestState?.installed).toBe(false) + expect(discover).toHaveBeenNthCalledWith(1, undefined) + expect(discover).toHaveBeenNthCalledWith(2, { runtime: 'wsl', wslDistro: 'Fedora' }) + }) + + it('ignores same-target background discovery results when a forced refresh is waiting', async () => { + const backgroundScan = deferred() + const forcedScan = deferred() + const discover = vi + .fn<(target?: SkillDiscoveryTarget) => Promise>() + .mockReturnValueOnce(backgroundScan.promise) + .mockReturnValueOnce(forcedScan.promise) + Object.defineProperty(window, 'api', { + configurable: true, + value: { skills: { discover } } + }) + + await renderProbe() + + const forcedRefresh = latestState?.refresh() ?? Promise.resolve() + + backgroundScan.resolve(discoveryResult([skill({ name: 'linear-tickets' })])) + await act(async () => { + await backgroundScan.promise + await Promise.resolve() + }) + + expect(latestState?.installed).toBe(false) + expect(discover).toHaveBeenCalledTimes(2) + + forcedScan.resolve(discoveryResult([])) + await act(async () => { + await forcedRefresh + }) + + expect(latestState?.installed).toBe(false) + expect(discover).toHaveBeenNthCalledWith(1, undefined) + expect(discover).toHaveBeenNthCalledWith(2, undefined) + }) +}) diff --git a/src/renderer/src/hooks/useInstalledAgentSkills.ts b/src/renderer/src/hooks/useInstalledAgentSkills.ts index a31d4857d..41ec7edc1 100644 --- a/src/renderer/src/hooks/useInstalledAgentSkills.ts +++ b/src/renderer/src/hooks/useInstalledAgentSkills.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { DiscoveredSkill, SkillDiscoveryResult, @@ -163,48 +163,64 @@ export function useInstalledAgentSkill( const [result, setResult] = useState(cachedDiscovery) const [loading, setLoading] = useState(enabled && !cachedDiscovery) const [error, setError] = useState(null) + const currentDiscoveryTargetKeyRef = useRef(discoveryTargetKey) + const refreshGenerationRef = useRef(0) + currentDiscoveryTargetKeyRef.current = discoveryTargetKey // Why: skill scans can outlive transient settings/onboarding panels; keep // the module cache update but skip React state writes after unmount. const mountedRef = useMountedRef() const refresh = useCallback( async (force = true): Promise => { - if (!enabled) { - if (mountedRef.current) { - setLoading(false) + const requestDiscoveryTargetKey = discoveryTargetKey + const requestGeneration = ++refreshGenerationRef.current + const writeIfCurrent = (write: () => void): void => { + if ( + mountedRef.current && + requestGeneration === refreshGenerationRef.current && + currentDiscoveryTargetKeyRef.current === requestDiscoveryTargetKey + ) { + write() } + } + + if (!enabled) { + writeIfCurrent(() => { + setLoading(false) + }) return } - if (mountedRef.current) { + writeIfCurrent(() => { setLoading(true) - } + }) try { const next = await discoverInstalledAgentSkills(force, discoveryTarget) - if (!mountedRef.current) { - return - } - setResult(next) - setError(null) + writeIfCurrent(() => { + setResult(next) + setError(null) + }) } catch (refreshError) { - if (!mountedRef.current) { - return - } - setError( - refreshError instanceof Error ? refreshError.message : 'Could not scan installed skills.' - ) + writeIfCurrent(() => { + setError( + refreshError instanceof Error + ? refreshError.message + : 'Could not scan installed skills.' + ) + }) } finally { - if (mountedRef.current) { + writeIfCurrent(() => { setLoading(false) - } + }) } }, - [discoveryTarget, enabled, mountedRef] + [discoveryTarget, discoveryTargetKey, enabled, mountedRef] ) useEffect(() => { const nextCachedDiscovery = cachedDiscoveryByTarget.get(discoveryTargetKey) ?? null setResult(nextCachedDiscovery) setLoading(enabled && !nextCachedDiscovery) + setError(null) }, [discoveryTargetKey, enabled]) useEffect(() => { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 38e960297..0729b847e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -3959,6 +3959,12 @@ "terminalTitle": "Install Linear agent skill", "terminalAria": "Linear agent skill installer terminal", "install": "Install CLI & Skill", + "successTitle": "Linear ticket access is ready", + "successDescription": "Agents can now read and update linked Linear tickets from this workspace.", + "successDescriptionWsl": "WSL agents can now use linked Linear tickets from this workspace.", + "successDescriptionRemote": "Host agents can now use linked Linear tickets. Remote agent environments may still need their own setup.", + "successStatus": "Linear ticket access ready", + "done": "Done", "wslCopy": "Install it for WSL agent handoffs from linked Linear work.", "wslLabel": "WSL default" }, diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 3b9934dbd..b5868c1c5 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -3959,6 +3959,12 @@ "terminalTitle": "Instalar habilidad de Agent de Linear", "terminalAria": "Terminal de instalación de la habilidad de Agent de Linear", "install": "Instalar CLI y habilidad", + "successTitle": "El acceso a tickets de Linear está listo", + "successDescription": "Los Agents ya pueden leer y actualizar tickets de Linear enlazados desde este espacio de trabajo.", + "successDescriptionWsl": "Los Agents de WSL ya pueden usar tickets de Linear enlazados desde este espacio de trabajo.", + "successDescriptionRemote": "Los Agents del host ya pueden usar tickets de Linear enlazados. Los entornos de Agent remotos aún pueden necesitar su propia configuración.", + "successStatus": "Acceso a tickets de Linear listo", + "done": "Listo", "wslCopy": "Instálala para traspasos de Agent en WSL desde trabajo Linear enlazado.", "wslLabel": "WSL predeterminado" }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 8e88b9ff7..c46bd03ec 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -3959,6 +3959,12 @@ "terminalTitle": "Linear agent スキルをインストール", "terminalAria": "Linear agent スキルのインストール terminal", "install": "CLI とスキルをインストール", + "successTitle": "Linear チケットアクセスの準備ができました", + "successDescription": "Agents はこのワークスペースからリンクされた Linear チケットを読み取り、更新できるようになりました。", + "successDescriptionWsl": "WSL agents はこのワークスペースからリンクされた Linear チケットを使用できるようになりました。", + "successDescriptionRemote": "ホスト agents はリンクされた Linear チケットを使用できるようになりました。リモート agent 環境ではまだ独自の設定が必要な場合があります。", + "successStatus": "Linear チケットアクセス準備完了", + "done": "完了", "wslCopy": "リンクされた Linear 作業からの WSL agent 引き継ぎ用にインストールします。", "wslLabel": "WSL 既定" }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index cfd76f2a1..b6e366530 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -3959,6 +3959,12 @@ "terminalTitle": "Linear agent 스킬 설치", "terminalAria": "Linear agent 스킬 설치 terminal", "install": "CLI 및 스킬 설치", + "successTitle": "Linear 티켓 접근이 준비되었습니다", + "successDescription": "이제 agents가 이 워크스페이스에서 연결된 Linear 티켓을 읽고 업데이트할 수 있습니다.", + "successDescriptionWsl": "이제 WSL agents가 이 워크스페이스에서 연결된 Linear 티켓을 사용할 수 있습니다.", + "successDescriptionRemote": "이제 호스트 agents가 연결된 Linear 티켓을 사용할 수 있습니다. 원격 agent 환경에는 자체 설정이 여전히 필요할 수 있습니다.", + "successStatus": "Linear 티켓 접근 준비됨", + "done": "완료", "wslCopy": "연결된 Linear 작업에서 WSL agent 인계를 위해 설치합니다.", "wslLabel": "WSL 기본값" }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index cd600d3aa..8ec689d4e 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -3959,6 +3959,12 @@ "terminalTitle": "安装 Linear agent 技能", "terminalAria": "Linear agent 技能安装 terminal", "install": "安装 CLI 和技能", + "successTitle": "Linear 议题访问已就绪", + "successDescription": "Agent 现在可以从此工作区读取和更新已链接的 Linear 议题。", + "successDescriptionWsl": "WSL Agent 现在可以从此工作区使用已链接的 Linear 议题。", + "successDescriptionRemote": "主机 Agent 现在可以使用已链接的 Linear 议题。远程 Agent 环境可能仍需要单独设置。", + "successStatus": "Linear 议题访问已就绪", + "done": "完成", "wslCopy": "为已链接 Linear 工作的 WSL agent 交接安装此项。", "wslLabel": "WSL 默认值" },