@skyhook-io/radar-app 1.18.1 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/package.json +4 -4
  2. package/src/App.tsx +23 -9
  3. package/src/api/client.deleteResource.test.tsx +111 -0
  4. package/src/api/client.resourceAudit.test.tsx +57 -0
  5. package/src/api/client.resourcePath.test.ts +107 -0
  6. package/src/api/client.ts +136 -37
  7. package/src/api/diagnose.test.ts +33 -2
  8. package/src/api/diagnose.ts +93 -3
  9. package/src/api/radarFeatures.ts +1 -0
  10. package/src/components/capacity/CapacityDemand.tsx +6 -3
  11. package/src/components/capacity/CapacityOverview.tsx +14 -7
  12. package/src/components/capacity/CapacityPoolDetail.tsx +7 -5
  13. package/src/components/capacity/ClusterSchedulingCard.tsx +3 -3
  14. package/src/components/capacity/shared.tsx +9 -5
  15. package/src/components/cnpg/CNPGOverview.tsx +4 -1
  16. package/src/components/cnpg/actions/useCNPGWriteGuard.tsx +1 -0
  17. package/src/components/diagnose/AIMarkdown.tsx +1 -1
  18. package/src/components/diagnose/ActivityTurn.tsx +34 -14
  19. package/src/components/diagnose/AgentControls.tsx +53 -6
  20. package/src/components/diagnose/AgentSetupNotice.tsx +1 -1
  21. package/src/components/diagnose/AgentSigninNotice.test.tsx +98 -0
  22. package/src/components/diagnose/AgentSigninNotice.tsx +61 -0
  23. package/src/components/diagnose/AnalysisStory.test.tsx +22 -0
  24. package/src/components/diagnose/AnalysisStory.tsx +17 -4
  25. package/src/components/diagnose/ApplyDialog.test.tsx +10 -0
  26. package/src/components/diagnose/ApplyDialog.tsx +8 -1
  27. package/src/components/diagnose/AssessmentCard.tsx +99 -8
  28. package/src/components/diagnose/DiagnoseContext.capacity.test.tsx +113 -0
  29. package/src/components/diagnose/DiagnoseContext.question.test.tsx +245 -0
  30. package/src/components/diagnose/DiagnoseContext.tsx +205 -9
  31. package/src/components/diagnose/DiagnoseSurface.test.tsx +54 -0
  32. package/src/components/diagnose/DiagnoseSurface.tsx +98 -21
  33. package/src/components/diagnose/EvidenceCard.tsx +67 -14
  34. package/src/components/diagnose/Home.test.tsx +182 -5
  35. package/src/components/diagnose/Home.tsx +168 -36
  36. package/src/components/diagnose/InvestigationCapacityNotice.test.tsx +246 -0
  37. package/src/components/diagnose/InvestigationCapacityNotice.tsx +241 -0
  38. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +97 -6
  39. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +119 -2
  40. package/src/components/diagnose/InvestigationEvidencePane.tsx +59 -11
  41. package/src/components/diagnose/InvestigationEvidenceSections.tsx +11 -6
  42. package/src/components/diagnose/InvestigationView.tsx +203 -42
  43. package/src/components/diagnose/LocalDiagnoseAction.tsx +23 -16
  44. package/src/components/diagnose/QuestionComposer.test.tsx +553 -0
  45. package/src/components/diagnose/QuestionComposer.tsx +487 -0
  46. package/src/components/diagnose/QuestionFocus.test.tsx +38 -0
  47. package/src/components/diagnose/QuestionFocus.tsx +123 -0
  48. package/src/components/diagnose/ResourcePicker.tsx +206 -0
  49. package/src/components/diagnose/StoryExcerpt.tsx +12 -3
  50. package/src/components/diagnose/assessmentCopy.ts +16 -0
  51. package/src/components/diagnose/investigationCase.runs.test.tsx +328 -0
  52. package/src/components/diagnose/investigationCase.ts +33 -1
  53. package/src/components/diagnose/investigationEvidence/adapters/changes.ts +36 -1
  54. package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +46 -0
  55. package/src/components/diagnose/investigationEvidence/adapters/crossplane.test.tsx +85 -0
  56. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +8 -0
  57. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +1 -0
  58. package/src/components/diagnose/investigationEvidence/adapters/posture.ts +29 -1
  59. package/src/components/diagnose/investigationEvidence/adapters/prometheus.test.ts +42 -1
  60. package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +29 -2
  61. package/src/components/diagnose/investigationEvidence/adapters/testdata/crossplane-paused-get-resource.json +28 -0
  62. package/src/components/diagnose/investigationEvidence/bodies/index.tsx +2 -0
  63. package/src/components/diagnose/investigationEvidence/bodies/metrics.test.tsx +111 -0
  64. package/src/components/diagnose/investigationEvidence/bodies/metrics.tsx +67 -16
  65. package/src/components/diagnose/investigationEvidence/bodies/workload.tsx +5 -1
  66. package/src/components/diagnose/investigationEvidence/builder.ts +3 -1
  67. package/src/components/diagnose/investigationEvidence/cardParts.tsx +7 -2
  68. package/src/components/diagnose/investigationEvidence/excerpt.test.ts +18 -5
  69. package/src/components/diagnose/investigationEvidence/excerpt.ts +22 -11
  70. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  71. package/src/components/diagnose/investigationEvidence/index.ts +1 -1
  72. package/src/components/diagnose/investigationEvidence/navigation.tsx +2 -0
  73. package/src/components/diagnose/investigationEvidence/observations.ts +7 -3
  74. package/src/components/diagnose/investigationEvidence/projection.test.ts +57 -3
  75. package/src/components/diagnose/investigationEvidence/types.ts +2 -0
  76. package/src/components/diagnose/investigationEvidencePartition.ts +6 -1
  77. package/src/components/diagnose/investigationEvidencePresentation.test.ts +36 -2
  78. package/src/components/diagnose/investigationEvidencePresentation.ts +33 -8
  79. package/src/components/diagnose/investigationFocus.test.ts +271 -0
  80. package/src/components/diagnose/investigationFocus.ts +132 -0
  81. package/src/components/diagnose/parts.test.tsx +20 -0
  82. package/src/components/diagnose/questionSuggestions.test.ts +111 -0
  83. package/src/components/diagnose/questionSuggestions.ts +150 -0
  84. package/src/components/diagnose/storyParts.test.tsx +66 -0
  85. package/src/components/diagnose/target.test.ts +143 -2
  86. package/src/components/diagnose/target.ts +109 -7
  87. package/src/components/diagnose/testdata/story-runs.json +474 -0
  88. package/src/components/diagnose/verdictText.test.tsx +87 -0
  89. package/src/components/diagnose/verdictText.ts +68 -0
  90. package/src/components/helm/ChartBrowser.tsx +4 -4
  91. package/src/components/helm/HelmReleaseDrawer.tsx +6 -2
  92. package/src/components/helm/HelmView.tsx +34 -23
  93. package/src/components/helm/InstallWizard.tsx +6 -2
  94. package/src/components/helm/ValuesViewer.test.tsx +1 -0
  95. package/src/components/helm/ValuesViewer.tsx +4 -2
  96. package/src/components/home/ClusterHealthCard.tsx +40 -59
  97. package/src/components/home/HomeAgentBlock.test.tsx +113 -0
  98. package/src/components/home/HomeAgentBlock.tsx +94 -0
  99. package/src/components/home/HomeView.tsx +5 -6
  100. package/src/components/home/MCPSetupDialog.test.tsx +27 -2
  101. package/src/components/home/MCPSetupDialog.tsx +14 -2
  102. package/src/components/home/RadarVersionLine.test.tsx +0 -14
  103. package/src/components/home/RadarVersionLine.tsx +3 -28
  104. package/src/components/home/mcpToolCatalog.ts +29 -2
  105. package/src/components/issues/IssuesPane.render.test.tsx +5 -5
  106. package/src/components/nav/PrimaryNavRail.tsx +34 -2
  107. package/src/components/product-hunt/ProductHuntNotice.render.test.tsx +120 -0
  108. package/src/components/product-hunt/ProductHuntNotice.test.ts +121 -0
  109. package/src/components/product-hunt/ProductHuntNotice.tsx +202 -0
  110. package/src/components/product-hunt/launchWindow.ts +78 -0
  111. package/src/components/product-hunt/useProductHuntRailEntry.test.tsx +76 -0
  112. package/src/components/product-hunt/useProductHuntRailEntry.ts +27 -0
  113. package/src/components/resources/CompositeRenderer.tsx +4 -0
  114. package/src/components/resources/ResourcesView.tsx +1 -1
  115. package/src/components/settings/LocalConnectionSettings.tsx +1 -0
  116. package/src/components/ui/Omnibar.investigate.test.tsx +105 -0
  117. package/src/components/ui/Omnibar.tsx +47 -3
  118. package/src/components/ui/RadarOmnibar.test.tsx +19 -0
  119. package/src/components/ui/RadarOmnibar.tsx +12 -0
  120. package/src/components/ui/SearchSyntaxHelp.test.tsx +39 -0
  121. package/src/components/ui/SearchSyntaxHelp.tsx +23 -2
  122. package/src/components/ui/UpdateNotification.test.tsx +2 -0
  123. package/src/components/ui/UpdateNotification.tsx +32 -5
  124. package/src/components/usage-data/UsageDataPrompt.tsx +19 -1
  125. package/src/components/whats-new/WhatsNewDialog.test.tsx +3 -3
  126. package/src/components/whats-new/releaseNotes.ts +60 -1
  127. package/src/components/workload/WorkloadView.tsx +10 -4
  128. package/src/components/workspace/layout.tsx +2 -1
  129. package/src/contexts/CapabilitiesContext.tsx +1 -0
  130. package/src/hooks/useAgentSignin.test.tsx +190 -0
  131. package/src/hooks/useAgentSignin.ts +160 -0
  132. package/src/hooks/useApproveAfterSignin.test.tsx +108 -0
  133. package/src/hooks/useGitOpsWriteGuard.test.tsx +126 -2
  134. package/src/hooks/useGitOpsWriteGuard.ts +25 -3
  135. package/src/hooks/useResolvedGitOpsOwner.ts +14 -9
  136. package/src/index.css +85 -0
@@ -295,6 +295,7 @@ function useActionsBarProps(
295
295
  cascadeEnabled: boolean,
296
296
  nodeUID: string,
297
297
  ) {
298
+ const [deletePreviewOpen, setDeletePreviewOpen] = useState(false)
298
299
  const { showCopied } = useToast()
299
300
  const { features } = useCapabilitiesContext()
300
301
  const openTerminal = useOpenTerminal()
@@ -359,14 +360,14 @@ function useActionsBarProps(
359
360
 
360
361
  const {
361
362
  data: cascadePreview,
362
- isLoading: cascadeLoading,
363
+ isFetching: cascadeLoading,
363
364
  isError: cascadeError,
364
365
  } = useCascadeDeletePreview(
365
366
  kind,
366
367
  namespace,
367
368
  name,
368
369
  group,
369
- cascadeEnabled,
370
+ cascadeEnabled && deletePreviewOpen,
370
371
  )
371
372
 
372
373
  const canNodeWrite = useCanNodeWrite()
@@ -403,8 +404,10 @@ function useActionsBarProps(
403
404
  onDelete: (
404
405
  params: Parameters<typeof deleteMutation.mutate>[0],
405
406
  callbacks?: { onSuccess?: () => void },
406
- ) => deleteMutation.mutate(params, { onSuccess: callbacks?.onSuccess }),
407
+ ) => deleteMutation.mutate(params, { onSuccess: result => { if (!result.outcomeUnknown) callbacks?.onSuccess?.() } }),
407
408
  isDeleting: deleteMutation.isPending,
409
+ onDeletePreviewOpenChange: setDeletePreviewOpen,
410
+ cascadeDetail: cascadePreview,
408
411
  cascadeDependents: cascadePreview?.dependents,
409
412
  cascadeLoading,
410
413
  cascadeRootResolved: cascadePreview?.rootResolved,
@@ -1027,6 +1030,7 @@ export function WorkloadView({
1027
1030
  guard: imageGuard,
1028
1031
  onSelectionChange: setImageSelection,
1029
1032
  selectionKey: setImageSelectionKey(imageSelection),
1033
+ onOpenManager: handleOpenGitOpsResource,
1030
1034
  onOpenOwner: owner
1031
1035
  ? imageOwnerVerified
1032
1036
  ? () => handleOpenGitOpsResource(owner)
@@ -1327,7 +1331,9 @@ export function WorkloadView({
1327
1331
  hasOverviewLead={hasOperationalIssues || Boolean(schedulingEvidence && schedulingEvidence.state !== 'reported')}
1328
1332
  hasOperationalIssues={hasOperationalIssues}
1329
1333
  operationalIssuesPending={issuesPending}
1330
- onOpenGitOpsResource={gitopsOwnerObject ? handleOpenGitOpsResource : undefined}
1334
+ // A manager answer's chip links only managers the server found; a
1335
+ // disagreement has no lead, so no owner object, but its managers link.
1336
+ onOpenGitOpsResource={gitopsOwnerObject || relationships?.ownership?.manager ? handleOpenGitOpsResource : undefined}
1331
1337
  resolvedGitOpsOwner={gitopsOwner}
1332
1338
  gitOpsOwnerVerified={gitOpsOwnerVerified}
1333
1339
  gitOpsOwnerPending={gitOpsOwnerPending}
@@ -30,7 +30,8 @@ export function ScreenEmptyState({
30
30
  }) {
31
31
  return (
32
32
  <div className="flex min-h-0 flex-1 items-center justify-center bg-theme-base p-6">
33
- <div className="max-w-md text-center">
33
+ {/* Phones: shrink to the screen so wide content (YAML) scrolls inside itself. */}
34
+ <div className="max-w-md text-center phone:w-full phone:min-w-0">
34
35
  <Icon className="mx-auto h-9 w-9 text-theme-text-tertiary/50" />
35
36
  <h2 className="mt-3 text-lg font-medium text-theme-text-primary">
36
37
  {title}
@@ -43,6 +43,7 @@ const restrictedCapabilities: Capabilities = {
43
43
  rollouts: false,
44
44
  },
45
45
  mcpEnabled: false,
46
+ mcpExecTools: false,
46
47
  deployment: { mode: 'local' },
47
48
  }
48
49
 
@@ -0,0 +1,190 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
+ import { useAgentSignin, type AgentSigninCheck } from './useAgentSignin'
7
+ import type { AgentSigninStatus, ExecutionProfile } from '../api/diagnose'
8
+
9
+ const mocks = vi.hoisted(() => ({
10
+ support: 'supported' as 'supported' | 'unsupported' | 'unknown',
11
+ fetch: vi.fn<(agent: string, profile: string, refresh: boolean) => Promise<AgentSigninStatus>>(),
12
+ }))
13
+ vi.mock('../api/client', () => ({
14
+ useRadarFeature: () => ({ support: mocks.support, gatedKey: [], guard: (fn: () => unknown) => fn() }),
15
+ }))
16
+ vi.mock('../api/diagnose', () => ({
17
+ fetchAgentSignin: (agent: string, profile: string, refresh: boolean) => mocks.fetch(agent, profile, refresh),
18
+ }))
19
+
20
+ const signedOut: AgentSigninStatus = { agent: 'claude', state: 'signed-out', signinCmd: 'claude auth login' }
21
+ const signedIn: AgentSigninStatus = { agent: 'claude', state: 'signed-in' }
22
+
23
+ const seen = {} as { latest: AgentSigninCheck }
24
+ function Probe({ agent, profile, enabled }: { agent: string; profile: ExecutionProfile; enabled: boolean }) {
25
+ seen.latest = useAgentSignin(agent, profile, enabled)
26
+ return null
27
+ }
28
+
29
+ // Lets React Query settle: a resolved fetch reaches the component a few
30
+ // ticks later.
31
+ async function settle() {
32
+ for (let i = 0; i < 5; i++) {
33
+ await act(async () => {
34
+ await new Promise((resolve) => setTimeout(resolve, 0))
35
+ })
36
+ }
37
+ }
38
+
39
+ async function mount(agent = 'claude', enabled = true, profile: ExecutionProfile = 'safeguarded') {
40
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
41
+ const root = createRoot(document.createElement('div'))
42
+ await act(async () => {
43
+ root.render(
44
+ <QueryClientProvider client={client}>
45
+ <Probe agent={agent} profile={profile} enabled={enabled} />
46
+ </QueryClientProvider>,
47
+ )
48
+ })
49
+ await settle()
50
+ return root
51
+ }
52
+
53
+ beforeEach(() => {
54
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
55
+ })
56
+ afterEach(() => {
57
+ mocks.support = 'supported'
58
+ mocks.fetch.mockReset()
59
+ })
60
+
61
+ it('reports a signed-out agent with its sign-in command, for the profile in use', async () => {
62
+ mocks.fetch.mockResolvedValue(signedOut)
63
+ const root = await mount('claude', true, 'full-local')
64
+ expect(mocks.fetch).toHaveBeenCalledWith('claude', 'full-local', false)
65
+ expect(seen.latest.status).toEqual(signedOut)
66
+ expect(seen.latest.pending).toBe(false)
67
+ root.unmount()
68
+ })
69
+
70
+ it.each<AgentSigninStatus['state']>(['signed-in', 'unknown'])('passes a %s answer through without a sign-in command', async (state) => {
71
+ mocks.fetch.mockResolvedValue({ agent: 'claude', state })
72
+ const root = await mount()
73
+ expect(seen.latest.status?.state).toBe(state)
74
+ expect(seen.latest.status?.signinCmd).toBeUndefined()
75
+ root.unmount()
76
+ })
77
+
78
+ it('leaves the consent step alone when the check fails', async () => {
79
+ mocks.fetch.mockRejectedValue(new Error('agent sign-in: 501'))
80
+ const root = await mount()
81
+ expect(seen.latest.status).toBeUndefined()
82
+ root.unmount()
83
+ })
84
+
85
+ it('asks nothing when disabled, without an agent, or on a Radar without the endpoint', async () => {
86
+ for (const [agent, enabled, support] of [
87
+ ['claude', false, 'supported'],
88
+ ['', true, 'supported'],
89
+ ['claude', true, 'unsupported'],
90
+ ] as const) {
91
+ mocks.support = support
92
+ const root = await mount(agent, enabled)
93
+ expect(seen.latest.status).toBeUndefined()
94
+ expect(await seen.latest.settle()).toBeUndefined()
95
+ root.unmount()
96
+ }
97
+ expect(mocks.fetch).not.toHaveBeenCalled()
98
+ })
99
+
100
+ it('re-check bypasses the cache and replaces the answer', async () => {
101
+ mocks.fetch.mockResolvedValueOnce(signedOut)
102
+ const root = await mount()
103
+ mocks.fetch.mockResolvedValueOnce(signedIn)
104
+ await act(async () => seen.latest.recheck())
105
+ await settle()
106
+ expect(mocks.fetch).toHaveBeenLastCalledWith('claude', 'safeguarded', true)
107
+ expect(seen.latest.status?.state).toBe('signed-in')
108
+ expect(seen.latest.rechecking).toBe(false)
109
+ root.unmount()
110
+ })
111
+
112
+ it('a failed re-check becomes unknown rather than refetching the stale answer', async () => {
113
+ // The server's cache would keep answering "signed out" to a plain fetch.
114
+ mocks.fetch.mockImplementation(async (_agent, _profile, refresh) => {
115
+ if (refresh) throw new Error('network')
116
+ return signedOut
117
+ })
118
+ const root = await mount()
119
+ const plainFetches = () => mocks.fetch.mock.calls.filter(([, , refresh]) => !refresh).length
120
+ expect(plainFetches()).toBe(1)
121
+ await act(async () => seen.latest.recheck())
122
+ await settle()
123
+ expect(seen.latest.status?.state).toBe('unknown')
124
+ expect(plainFetches()).toBe(1)
125
+ root.unmount()
126
+ })
127
+
128
+ it('applies only the newest of overlapping re-checks', async () => {
129
+ mocks.fetch.mockResolvedValueOnce(signedOut)
130
+ const root = await mount()
131
+ let resolveOlder!: (s: AgentSigninStatus) => void
132
+ mocks.fetch.mockImplementationOnce(() => new Promise((resolve) => { resolveOlder = resolve }))
133
+ mocks.fetch.mockResolvedValueOnce(signedIn)
134
+ await act(async () => seen.latest.recheck())
135
+ await act(async () => seen.latest.recheck())
136
+ await settle()
137
+ expect(seen.latest.status?.state).toBe('signed-in')
138
+ await act(async () => resolveOlder(signedOut))
139
+ await settle()
140
+ expect(seen.latest.status?.state).toBe('signed-in')
141
+ expect(seen.latest.rechecking).toBe(false)
142
+ root.unmount()
143
+ })
144
+
145
+ it('settle waits for the running check', async () => {
146
+ let resolve!: (s: AgentSigninStatus) => void
147
+ mocks.fetch.mockImplementation(() => new Promise((r) => { resolve = r }))
148
+ const root = await mount()
149
+ expect(seen.latest.pending).toBe(true)
150
+ let settled: AgentSigninStatus | undefined
151
+ const waiting = seen.latest.settle().then((s) => { settled = s })
152
+ await settle()
153
+ expect(settled).toBeUndefined()
154
+ await act(async () => resolve(signedOut))
155
+ await waiting
156
+ expect(settled).toEqual(signedOut)
157
+ expect(mocks.fetch).toHaveBeenCalledTimes(1)
158
+ root.unmount()
159
+ })
160
+
161
+ it('settle gives up when the answer never arrives', async () => {
162
+ mocks.fetch.mockImplementation(() => new Promise(() => {}))
163
+ const root = await mount()
164
+ vi.useFakeTimers()
165
+ try {
166
+ let settled = 'waiting' as AgentSigninStatus | undefined | 'waiting'
167
+ const waiting = seen.latest.settle().then((s) => { settled = s })
168
+ await vi.advanceTimersByTimeAsync(2_400)
169
+ expect(settled).toBe('waiting')
170
+ await vi.advanceTimersByTimeAsync(200)
171
+ await waiting
172
+ expect(settled).toBeUndefined()
173
+ } finally {
174
+ vi.useRealTimers()
175
+ }
176
+ root.unmount()
177
+ })
178
+
179
+ it('checks again when the user comes back to the window while signed out', async () => {
180
+ mocks.fetch.mockResolvedValueOnce(signedOut)
181
+ const root = await mount()
182
+ mocks.fetch.mockResolvedValueOnce(signedIn)
183
+ await act(async () => {
184
+ window.dispatchEvent(new Event('focus'))
185
+ })
186
+ await settle()
187
+ expect(mocks.fetch).toHaveBeenLastCalledWith('claude', 'safeguarded', true)
188
+ expect(seen.latest.status?.state).toBe('signed-in')
189
+ root.unmount()
190
+ })
@@ -0,0 +1,160 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
2
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
3
+ import { useRadarFeature } from '../api/client'
4
+ import { getApiBase } from '../api/config'
5
+ import { fetchAgentSignin, type AgentSigninStatus, type ExecutionProfile } from '../api/diagnose'
6
+
7
+ export interface AgentSigninCheck {
8
+ /** The agent's answer; undefined while checking, on failure, or when not checked. */
9
+ status?: AgentSigninStatus
10
+ /** A check is running and has not answered yet. */
11
+ pending: boolean
12
+ rechecking: boolean
13
+ recheck: () => void
14
+ /** Resolves with the answer once the running check settles (undefined on failure or when not checked). */
15
+ settle: () => Promise<AgentSigninStatus | undefined>
16
+ }
17
+
18
+ // The server caches its answer for a minute; matching it keeps a reopened
19
+ // consent card from asking again.
20
+ const SIGNIN_STALE_MS = 60_000
21
+ // Longest an early Approve waits for the answer: the server's 2s command
22
+ // timeout plus the round trip.
23
+ const SETTLE_MAX_MS = 2_500
24
+
25
+ /**
26
+ * Asks whether a local agent CLI is signed in for runs with this profile, for
27
+ * the consent step. Never blocks: the card renders at once and the answer
28
+ * arrives within the server's timeout. An error, an older Radar without the
29
+ * endpoint, or an "unknown" answer all leave the consent step as it was
30
+ * without the check.
31
+ */
32
+ export function useAgentSignin(agent: string, profile: ExecutionProfile, enabled: boolean): AgentSigninCheck {
33
+ const { support } = useRadarFeature('agentSigninCheck')
34
+ const active = enabled && !!agent && support !== 'unsupported'
35
+ const queryClient = useQueryClient()
36
+ const apiBase = getApiBase()
37
+ const query = useQuery({
38
+ queryKey: ['agent-signin', apiBase, agent, profile],
39
+ queryFn: ({ signal }) => fetchAgentSignin(agent, profile, false, signal),
40
+ enabled: active,
41
+ staleTime: SIGNIN_STALE_MS,
42
+ retry: false,
43
+ refetchOnWindowFocus: false,
44
+ })
45
+
46
+ // A click and a window-focus re-check can overlap; only the newest may
47
+ // apply its answer or clear the spinner.
48
+ const seq = useRef(0)
49
+ const [rechecking, setRechecking] = useState(false)
50
+ const recheck = useCallback(() => {
51
+ const key = ['agent-signin', apiBase, agent, profile]
52
+ const mine = ++seq.current
53
+ setRechecking(true)
54
+ void queryClient.cancelQueries({ queryKey: key, exact: true })
55
+ fetchAgentSignin(agent, profile, true)
56
+ .then((status) => {
57
+ if (mine === seq.current) queryClient.setQueryData(key, status)
58
+ })
59
+ .catch(() => {
60
+ // Unknown, not removed: a removed query refetches and the server's
61
+ // cache would hand back the stale "signed out".
62
+ if (mine === seq.current) queryClient.setQueryData(key, { agent, state: 'unknown' } satisfies AgentSigninStatus)
63
+ })
64
+ .finally(() => {
65
+ if (mine === seq.current) setRechecking(false)
66
+ })
67
+ }, [agent, profile, apiBase, queryClient])
68
+
69
+ const settle = useCallback(async () => {
70
+ if (!active) return undefined
71
+ const answer = queryClient
72
+ .fetchQuery({
73
+ queryKey: ['agent-signin', apiBase, agent, profile],
74
+ queryFn: ({ signal }) => fetchAgentSignin(agent, profile, false, signal),
75
+ staleTime: SIGNIN_STALE_MS,
76
+ retry: false,
77
+ })
78
+ .catch(() => undefined)
79
+ // The server answers within its own timeout, but a request can still sit
80
+ // in the browser's queue behind other connections; Approve must not.
81
+ let timer: ReturnType<typeof setTimeout> | undefined
82
+ const giveUp = new Promise<undefined>((resolve) => {
83
+ timer = setTimeout(() => resolve(undefined), SETTLE_MAX_MS)
84
+ })
85
+ try {
86
+ return await Promise.race([answer, giveUp])
87
+ } finally {
88
+ clearTimeout(timer)
89
+ }
90
+ }, [active, agent, profile, apiBase, queryClient])
91
+
92
+ const status = active && !query.isError ? query.data : undefined
93
+ const pending = active && query.isFetching && !query.data
94
+ const signedOut = status?.state === 'signed-out'
95
+ // Signing in happens in a terminal; coming back to the window is when to
96
+ // look again, as the agent list does after an install.
97
+ useEffect(() => {
98
+ if (!signedOut) return
99
+ const onFocus = () => recheck()
100
+ window.addEventListener('focus', onFocus)
101
+ return () => window.removeEventListener('focus', onFocus)
102
+ }, [signedOut, recheck])
103
+
104
+ return { status, pending, rechecking, recheck, settle }
105
+ }
106
+
107
+ /**
108
+ * Consent actions that respect a sign-in check still in flight. Approving
109
+ * before it answers would start the run the warning is there to prevent, so
110
+ * Approve waits for it (bounded by settle) and stops on a signed-out answer,
111
+ * which then shows; approving again proceeds. The wait belongs to one
112
+ * approval: Cancel, unmounting, or a new attemptKey (another agent, profile
113
+ * or consent request) abandons it, and its answer approves nothing.
114
+ */
115
+ export function useApproveAfterSignin({
116
+ approve,
117
+ cancel,
118
+ signin,
119
+ attemptKey,
120
+ }: {
121
+ approve: () => void
122
+ cancel: () => void
123
+ signin: Pick<AgentSigninCheck, 'pending' | 'settle'>
124
+ attemptKey: string
125
+ }) {
126
+ const [waiting, setWaiting] = useState(false)
127
+ const attempt = useRef(0)
128
+ const abandon = useCallback(() => {
129
+ attempt.current++
130
+ setWaiting(false)
131
+ }, [])
132
+ useEffect(() => abandon, [abandon, attemptKey])
133
+
134
+ // The approval in effect when the answer lands: the consent request may
135
+ // have been replaced by another target while waiting.
136
+ const latestApprove = useRef(approve)
137
+ useLayoutEffect(() => {
138
+ latestApprove.current = approve
139
+ }, [approve])
140
+ const { pending, settle } = signin
141
+ const approveWhenChecked = useCallback(() => {
142
+ if (!pending) {
143
+ latestApprove.current()
144
+ return
145
+ }
146
+ const mine = ++attempt.current
147
+ setWaiting(true)
148
+ void settle().then((status) => {
149
+ if (mine !== attempt.current) return
150
+ setWaiting(false)
151
+ if (status?.state !== 'signed-out') latestApprove.current()
152
+ })
153
+ }, [pending, settle])
154
+ const cancelAndAbandon = useCallback(() => {
155
+ abandon()
156
+ cancel()
157
+ }, [abandon, cancel])
158
+
159
+ return { approve: approveWhenChecked, cancel: cancelAndAbandon, waiting }
160
+ }
@@ -0,0 +1,108 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { beforeEach, expect, it, vi } from 'vitest'
5
+ import { useApproveAfterSignin } from './useAgentSignin'
6
+ import type { AgentSigninStatus } from '../api/diagnose'
7
+
8
+ vi.mock('../api/client', () => ({ useRadarFeature: () => ({ support: 'supported' }) }))
9
+ vi.mock('../api/diagnose', () => ({ fetchAgentSignin: vi.fn() }))
10
+
11
+ type Actions = ReturnType<typeof useApproveAfterSignin>
12
+ const seen = {} as { actions: Actions }
13
+
14
+ function Probe(props: Parameters<typeof useApproveAfterSignin>[0]) {
15
+ seen.actions = useApproveAfterSignin(props)
16
+ return null
17
+ }
18
+
19
+ function deferred() {
20
+ let resolve!: (s: AgentSigninStatus | undefined) => void
21
+ const promise = new Promise<AgentSigninStatus | undefined>((r) => { resolve = r })
22
+ return { promise, resolve }
23
+ }
24
+
25
+ const signedOut: AgentSigninStatus = { agent: 'claude', state: 'signed-out', signinCmd: 'claude auth login' }
26
+
27
+ let root: Root
28
+ let approve: ReturnType<typeof vi.fn<() => void>>
29
+ let cancel: ReturnType<typeof vi.fn<() => void>>
30
+
31
+ async function render(pending: boolean, settle: () => Promise<AgentSigninStatus | undefined>, attemptKey = 'claude:safeguarded') {
32
+ await act(async () => {
33
+ root.render(<Probe approve={approve} cancel={cancel} signin={{ pending, settle }} attemptKey={attemptKey} />)
34
+ })
35
+ }
36
+
37
+ beforeEach(() => {
38
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
39
+ root = createRoot(document.createElement('div'))
40
+ approve = vi.fn()
41
+ cancel = vi.fn()
42
+ })
43
+
44
+ it('approves at once when no check is running', async () => {
45
+ const settle = vi.fn()
46
+ await render(false, settle)
47
+ await act(async () => seen.actions.approve())
48
+ expect(approve).toHaveBeenCalledTimes(1)
49
+ expect(settle).not.toHaveBeenCalled()
50
+ root.unmount()
51
+ })
52
+
53
+ it('waits for a running check and stops on signed out', async () => {
54
+ const answer = deferred()
55
+ await render(true, () => answer.promise)
56
+ await act(async () => seen.actions.approve())
57
+ expect(seen.actions.waiting).toBe(true)
58
+ expect(approve).not.toHaveBeenCalled()
59
+ await act(async () => answer.resolve(signedOut))
60
+ expect(seen.actions.waiting).toBe(false)
61
+ expect(approve).not.toHaveBeenCalled()
62
+ root.unmount()
63
+ })
64
+
65
+ it.each<[string, AgentSigninStatus | undefined]>([
66
+ ['signed in', { agent: 'claude', state: 'signed-in' }],
67
+ ['unknown', { agent: 'claude', state: 'unknown' }],
68
+ ['no answer (timeout or failure)', undefined],
69
+ ])('approves after a running check answers %s', async (_label, status) => {
70
+ const answer = deferred()
71
+ await render(true, () => answer.promise)
72
+ await act(async () => seen.actions.approve())
73
+ await act(async () => answer.resolve(status))
74
+ expect(approve).toHaveBeenCalledTimes(1)
75
+ root.unmount()
76
+ })
77
+
78
+ it('Cancel abandons the wait', async () => {
79
+ const answer = deferred()
80
+ await render(true, () => answer.promise)
81
+ await act(async () => seen.actions.approve())
82
+ await act(async () => seen.actions.cancel())
83
+ expect(cancel).toHaveBeenCalledTimes(1)
84
+ expect(seen.actions.waiting).toBe(false)
85
+ await act(async () => answer.resolve({ agent: 'claude', state: 'signed-in' }))
86
+ expect(approve).not.toHaveBeenCalled()
87
+ root.unmount()
88
+ })
89
+
90
+ it('switching agent or profile abandons the wait', async () => {
91
+ const answer = deferred()
92
+ await render(true, () => answer.promise)
93
+ await act(async () => seen.actions.approve())
94
+ await render(true, () => answer.promise, 'codex:safeguarded')
95
+ expect(seen.actions.waiting).toBe(false)
96
+ await act(async () => answer.resolve(undefined))
97
+ expect(approve).not.toHaveBeenCalled()
98
+ root.unmount()
99
+ })
100
+
101
+ it('leaving the card abandons the wait', async () => {
102
+ const answer = deferred()
103
+ await render(true, () => answer.promise)
104
+ await act(async () => seen.actions.approve())
105
+ root.unmount()
106
+ await act(async () => answer.resolve(undefined))
107
+ expect(approve).not.toHaveBeenCalled()
108
+ })