@skyhook-io/radar-app 1.18.2 → 1.20.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.
- package/README.md +1 -1
- package/package.json +7 -7
- package/src/App.tsx +31 -6
- package/src/api/application-evidence.ts +63 -0
- package/src/api/argoSync.test.ts +22 -0
- package/src/api/client.audit-gating.test.tsx +48 -0
- package/src/api/client.kueuePosition.test.ts +32 -0
- package/src/api/client.kueueQueueWorkloads.test.tsx +71 -0
- package/src/api/client.resource-identity.test.ts +3 -0
- package/src/api/client.resourceIssues.test.tsx +239 -0
- package/src/api/client.resourcePath.test.ts +3 -0
- package/src/api/client.ts +285 -55
- package/src/api/config.ts +21 -0
- package/src/api/diagnose.test.ts +33 -2
- package/src/api/diagnose.ts +97 -3
- package/src/api/radarFeatures.render.test.tsx +33 -1
- package/src/api/radarFeatures.test.ts +47 -0
- package/src/api/radarFeatures.ts +41 -1
- package/src/api/rbac.settled.test.tsx +42 -0
- package/src/api/rbac.test.ts +18 -0
- package/src/api/rbac.ts +37 -7
- package/src/api/traffic.ts +9 -4
- package/src/api/usage-data.fixtures.ts +3 -1
- package/src/api/usage-data.test.tsx +134 -0
- package/src/api/usage-data.ts +35 -7
- package/src/api/workloadPodsPolling.test.ts +26 -0
- package/src/components/CloudConnectFlow.test.tsx +86 -0
- package/src/components/CloudConnectFlow.tsx +65 -27
- package/src/components/CloudFunnelButton.test.tsx +140 -5
- package/src/components/CloudFunnelButton.tsx +50 -9
- package/src/components/ConnectionErrorView.test.tsx +34 -0
- package/src/components/ConnectionErrorView.tsx +35 -11
- package/src/components/ContextSwitcher.tsx +5 -2
- package/src/components/SwitchAwareConnectionError.test.tsx +43 -0
- package/src/components/SwitchAwareConnectionError.tsx +85 -0
- package/src/components/application-evidence/ApplicationEvidenceAction.flow.test.tsx +234 -0
- package/src/components/application-evidence/ApplicationEvidenceAction.test.tsx +144 -0
- package/src/components/application-evidence/ApplicationEvidenceAction.tsx +218 -0
- package/src/components/capacity/CapacityDemand.tsx +3 -2
- package/src/components/capacity/demandSummary.test.ts +38 -0
- package/src/components/capacity/shared.tsx +12 -1
- package/src/components/cost/ApplicationCostTab.tsx +4 -0
- package/src/components/cost/CostTrendChart.tsx +2 -0
- package/src/components/cost/WorkloadCostTab.tsx +4 -0
- package/src/components/cost/source.test.ts +5 -0
- package/src/components/cost/source.ts +11 -0
- package/src/components/diagnose/AIMarkdown.tsx +4 -1
- package/src/components/diagnose/ActivityTurn.tsx +34 -14
- package/src/components/diagnose/AgentControls.tsx +53 -6
- package/src/components/diagnose/AgentSetupNotice.test.tsx +17 -0
- package/src/components/diagnose/AgentSetupNotice.tsx +22 -4
- package/src/components/diagnose/AgentSigninNotice.test.tsx +98 -0
- package/src/components/diagnose/AgentSigninNotice.tsx +61 -0
- package/src/components/diagnose/AnalysisStory.test.tsx +22 -0
- package/src/components/diagnose/AnalysisStory.tsx +17 -4
- package/src/components/diagnose/AssessmentCard.tsx +39 -8
- package/src/components/diagnose/ContinueInAgentButton.mounted.test.tsx +182 -0
- package/src/components/diagnose/ContinueInAgentButton.test.tsx +128 -0
- package/src/components/diagnose/ContinueInAgentButton.tsx +303 -0
- package/src/components/diagnose/DiagnoseContext.capacity.test.tsx +113 -0
- package/src/components/diagnose/DiagnoseContext.question.test.tsx +245 -0
- package/src/components/diagnose/DiagnoseContext.tsx +272 -10
- package/src/components/diagnose/DiagnoseSurface.test.tsx +54 -0
- package/src/components/diagnose/DiagnoseSurface.tsx +151 -134
- package/src/components/diagnose/EvidenceCard.tsx +67 -14
- package/src/components/diagnose/ExampleInvestigationLink.tsx +20 -0
- package/src/components/diagnose/Home.test.tsx +208 -5
- package/src/components/diagnose/Home.tsx +187 -36
- package/src/components/diagnose/InvestigationCapacityNotice.test.tsx +246 -0
- package/src/components/diagnose/InvestigationCapacityNotice.tsx +241 -0
- package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +97 -6
- package/src/components/diagnose/InvestigationEvidencePane.test.tsx +57 -0
- package/src/components/diagnose/InvestigationEvidencePane.tsx +59 -11
- package/src/components/diagnose/InvestigationEvidenceSections.tsx +50 -23
- package/src/components/diagnose/InvestigationView.tsx +249 -54
- package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +450 -0
- package/src/components/diagnose/LocalDiagnoseAction.tsx +365 -39
- package/src/components/diagnose/NextStepJump.test.tsx +92 -0
- package/src/components/diagnose/NextStepJump.tsx +75 -0
- package/src/components/diagnose/QuestionComposer.test.tsx +553 -0
- package/src/components/diagnose/QuestionComposer.tsx +495 -0
- package/src/components/diagnose/QuestionFocus.test.tsx +38 -0
- package/src/components/diagnose/QuestionFocus.tsx +123 -0
- package/src/components/diagnose/ResourcePicker.tsx +206 -0
- package/src/components/diagnose/StoryExcerpt.tsx +12 -3
- package/src/components/diagnose/assessmentCopy.ts +5 -0
- package/src/components/diagnose/exampleInvestigation.events.json +191 -0
- package/src/components/diagnose/exampleInvestigation.loadFailure.test.tsx +94 -0
- package/src/components/diagnose/exampleInvestigation.test.tsx +248 -0
- package/src/components/diagnose/exampleInvestigation.ts +121 -0
- package/src/components/diagnose/investigationCase.runs.test.tsx +328 -0
- package/src/components/diagnose/investigationCase.test.tsx +9 -1
- package/src/components/diagnose/investigationCase.ts +33 -1
- package/src/components/diagnose/investigationEvidence/adapters/applicationFindings.test.ts +739 -0
- package/src/components/diagnose/investigationEvidence/adapters/coverage.test.tsx +46 -0
- package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +58 -2
- package/src/components/diagnose/investigationEvidence/adapters/issues.ts +9 -0
- package/src/components/diagnose/investigationEvidence/adapters/posture.ts +29 -1
- package/src/components/diagnose/investigationEvidence/adapters/prometheus.test.ts +40 -0
- package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +27 -1
- package/src/components/diagnose/investigationEvidence/bodies/metrics.test.tsx +111 -0
- package/src/components/diagnose/investigationEvidence/bodies/metrics.tsx +67 -16
- package/src/components/diagnose/investigationEvidence/builder.ts +30 -0
- package/src/components/diagnose/investigationEvidence/excerpt.test.ts +18 -5
- package/src/components/diagnose/investigationEvidence/excerpt.ts +22 -11
- package/src/components/diagnose/investigationEvidence/index.ts +1 -1
- package/src/components/diagnose/investigationEvidence/navigation.tsx +2 -0
- package/src/components/diagnose/investigationEvidence/observations.ts +121 -2
- package/src/components/diagnose/investigationEvidence/projection.test.ts +85 -3
- package/src/components/diagnose/investigationEvidence/types.ts +7 -0
- package/src/components/diagnose/investigationEvidencePartition.ts +6 -1
- package/src/components/diagnose/investigationFocus.test.ts +271 -0
- package/src/components/diagnose/investigationFocus.ts +132 -0
- package/src/components/diagnose/investigationState.ts +28 -0
- package/src/components/diagnose/lastInvestigation.test.ts +95 -0
- package/src/components/diagnose/lastInvestigation.ts +58 -0
- package/src/components/diagnose/launch.test.ts +125 -1
- package/src/components/diagnose/launch.ts +57 -10
- package/src/components/diagnose/parts.test.tsx +20 -0
- package/src/components/diagnose/questionSuggestions.test.ts +111 -0
- package/src/components/diagnose/questionSuggestions.ts +150 -0
- package/src/components/diagnose/storyParts.test.tsx +13 -0
- package/src/components/diagnose/target.test.ts +143 -2
- package/src/components/diagnose/target.ts +109 -7
- package/src/components/diagnose/testdata/story-runs.json +474 -0
- package/src/components/diagnose/toolCallLabel.test.ts +10 -4
- package/src/components/diagnose/verdictText.test.tsx +87 -0
- package/src/components/diagnose/verdictText.ts +68 -0
- package/src/components/execution/BatchExecutionView.tsx +24 -11
- package/src/components/execution/JobSetAdmission.test.tsx +42 -0
- package/src/components/execution/JobSetAdmission.tsx +18 -3
- package/src/components/execution/JobSetMemberComparison.tsx +2 -1
- package/src/components/execution/runState.test.ts +14 -0
- package/src/components/execution/runState.ts +8 -0
- package/src/components/gitops/GitOpsView.rollbackGate.test.tsx +202 -0
- package/src/components/gitops/GitOpsView.syncRequest.test.tsx +369 -0
- package/src/components/gitops/GitOpsView.tsx +86 -17
- package/src/components/gitops/RemoteDestinationCloudHint.tsx +2 -3
- package/src/components/gitops/destination-toast.test.ts +1 -1
- package/src/components/gitops/destination-toast.ts +2 -2
- package/src/components/home/ClusterHealthCard.tsx +13 -39
- package/src/components/home/HomeAgentBlock.test.tsx +141 -0
- package/src/components/home/HomeAgentBlock.tsx +103 -0
- package/src/components/home/HomeDiagramCard.tsx +47 -0
- package/src/components/home/HomeView.tsx +86 -47
- package/src/components/home/MCPSetupDialog.test.tsx +95 -5
- package/src/components/home/MCPSetupDialog.tsx +30 -5
- package/src/components/home/ProblemsPanel.investigate.test.tsx +171 -0
- package/src/components/home/ProblemsPanel.test.tsx +3 -1
- package/src/components/home/RadarVersionLine.test.tsx +0 -14
- package/src/components/home/RadarVersionLine.tsx +3 -28
- package/src/components/home/TopologyPreview.test.tsx +73 -0
- package/src/components/home/TopologyPreview.tsx +120 -233
- package/src/components/home/TrafficSummary.test.tsx +63 -0
- package/src/components/home/TrafficSummary.tsx +135 -138
- package/src/components/home/mcpToolCatalog.ts +23 -10
- package/src/components/issues/IssuesPane.test.ts +11 -0
- package/src/components/issues/IssuesPane.tsx +15 -5
- package/src/components/issues/uncheckedSources.test.ts +20 -1
- package/src/components/issues/uncheckedSources.ts +18 -0
- package/src/components/kueue/KueuePendingPosition.tsx +35 -0
- package/src/components/kueue/useRelatedObjects.test.tsx +219 -0
- package/src/components/kueue/useRelatedReads.test.ts +56 -0
- package/src/components/kueue/useRelatedReads.ts +205 -0
- package/src/components/logs/MultiPodLogsTab.test.tsx +93 -0
- package/src/components/logs/MultiPodLogsTab.tsx +120 -0
- package/src/components/logs/PodLogsUnavailable.test.tsx +18 -0
- package/src/components/logs/PodLogsUnavailable.tsx +21 -0
- package/src/components/logs/RayClusterLogsTab.reselect.test.tsx +67 -0
- package/src/components/logs/RayClusterLogsTab.test.tsx +167 -0
- package/src/components/logs/RayClusterLogsTab.tsx +109 -0
- package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +3 -2
- package/src/components/logs/rayClusterPods.ts +32 -0
- package/src/components/outageSince.test.ts +21 -0
- package/src/components/outageSince.ts +10 -0
- package/src/components/resource/PrometheusCharts.overlays.test.ts +12 -0
- package/src/components/resource/PrometheusCharts.tsx +3 -40
- package/src/components/resources/crd/CRDSchemaTab.test.tsx +28 -0
- package/src/components/resources/crd/CRDSchemaTab.tsx +13 -0
- package/src/components/resources/crd/host.tsx +14 -0
- package/src/components/resources/renderers/CustomResourceDefinitionRenderer.test.tsx +27 -0
- package/src/components/resources/renderers/CustomResourceDefinitionRenderer.tsx +12 -0
- package/src/components/resources/renderers/JobAdmissionRenderers.test.tsx +4 -1
- package/src/components/resources/renderers/JobAdmissionRenderers.tsx +4 -3
- package/src/components/resources/renderers/KueueHostRenderers.test.tsx +117 -0
- package/src/components/resources/renderers/KueueQueueRenderers.test.tsx +97 -0
- package/src/components/resources/renderers/KueueQueueRenderers.tsx +139 -0
- package/src/components/resources/renderers/KueueWorkloadRenderer.test.tsx +7 -1
- package/src/components/resources/renderers/KueueWorkloadRenderer.tsx +47 -7
- package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.test.tsx +67 -0
- package/src/components/resources/renderers/OpenTelemetryCollectorRenderer.tsx +31 -0
- package/src/components/resources/renderers/RayClusterRenderer.test.tsx +81 -3
- package/src/components/resources/renderers/RayClusterRenderer.tsx +19 -4
- package/src/components/traffic/TrafficView.tsx +3 -3
- package/src/components/ui/Omnibar.investigate.test.tsx +105 -0
- package/src/components/ui/Omnibar.tsx +47 -3
- package/src/components/ui/RadarOmnibar.test.tsx +1 -0
- package/src/components/ui/RadarOmnibar.tsx +11 -0
- package/src/components/ui/command-items-crd.test.tsx +23 -0
- package/src/components/ui/command-items.ts +2 -1
- package/src/components/useContextSwitchFlow.test.tsx +61 -0
- package/src/components/useContextSwitchFlow.tsx +21 -4
- package/src/components/whats-new/WhatsNew.test.ts +10 -3
- package/src/components/whats-new/WhatsNew.tsx +5 -1
- package/src/components/whats-new/WhatsNewDialog.test.tsx +18 -4
- package/src/components/whats-new/releaseNotes.ts +136 -4
- package/src/components/workload/RelatedFindingsSection.test.tsx +126 -0
- package/src/components/workload/RelatedFindingsSection.tsx +80 -0
- package/src/components/workload/WorkloadView.test.ts +10 -1
- package/src/components/workload/WorkloadView.tsx +85 -98
- package/src/components/workload/issueResourceOpener.test.ts +20 -0
- package/src/components/workload/issueResourceOpener.ts +17 -0
- package/src/context/ConnectionContext.tsx +133 -60
- package/src/context/ConnectionProvider.retry.test.tsx +176 -0
- package/src/context/ContextSwitchContext.tsx +14 -1
- package/src/context/DiagnoseCustomization.tsx +3 -0
- package/src/context/clusterConnected.ts +10 -0
- package/src/contexts/CapabilitiesContext.tsx +6 -4
- package/src/hooks/useAgentSignin.test.tsx +190 -0
- package/src/hooks/useAgentSignin.ts +160 -0
- package/src/hooks/useApproveAfterSignin.test.tsx +108 -0
- package/src/hooks/useElementSize.ts +30 -0
- package/src/integrations/resourceHost.test.tsx +1 -0
- package/src/integrations/resourceHost.ts +5 -1
- package/src/integrations/resourceHosts.test.tsx +21 -4
- package/src/integrations/resourceHosts.tsx +12 -0
- package/src/main.tsx +5 -0
- package/src/utils/related-findings.ts +46 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act } from 'react'
|
|
3
|
+
import { createRoot, type Root } from 'react-dom/client'
|
|
4
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { ConnectionProvider, useConnection } from './ConnectionContext'
|
|
7
|
+
|
|
8
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
|
|
9
|
+
|
|
10
|
+
let root: Root
|
|
11
|
+
let container: HTMLDivElement
|
|
12
|
+
let retries: number
|
|
13
|
+
const seen = vi.fn<(value: ReturnType<typeof useConnection>) => void>()
|
|
14
|
+
const latest = () => seen.mock.lastCall?.[0]
|
|
15
|
+
let focused: boolean
|
|
16
|
+
let pollContext: string
|
|
17
|
+
|
|
18
|
+
function Probe() {
|
|
19
|
+
seen(useConnection())
|
|
20
|
+
return null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function jsonResponse(status: number, body: unknown) {
|
|
24
|
+
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function advance(ms: number) {
|
|
28
|
+
await act(async () => {
|
|
29
|
+
await vi.advanceTimersByTimeAsync(ms)
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
beforeEach(async () => {
|
|
34
|
+
vi.useFakeTimers()
|
|
35
|
+
retries = 0
|
|
36
|
+
seen.mockClear()
|
|
37
|
+
focused = false
|
|
38
|
+
pollContext = 'prod'
|
|
39
|
+
vi.spyOn(document, 'hasFocus').mockImplementation(() => focused)
|
|
40
|
+
vi.stubGlobal('fetch', vi.fn(async (input: string) => {
|
|
41
|
+
const url = new URL(String(input), 'http://localhost')
|
|
42
|
+
if (url.pathname === '/api/connection/retry') {
|
|
43
|
+
retries += 1
|
|
44
|
+
return jsonResponse(503, { error: 'cluster unreachable', errorType: 'network' })
|
|
45
|
+
}
|
|
46
|
+
if (url.pathname === '/api/connection') {
|
|
47
|
+
return jsonResponse(200, {
|
|
48
|
+
state: 'disconnected',
|
|
49
|
+
context: pollContext,
|
|
50
|
+
error: 'cluster unreachable',
|
|
51
|
+
errorType: 'network',
|
|
52
|
+
disconnectedAt: '2026-10-30T14:02:00Z',
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
return jsonResponse(404, { error: 'not found' })
|
|
56
|
+
}))
|
|
57
|
+
|
|
58
|
+
container = document.createElement('div')
|
|
59
|
+
document.body.appendChild(container)
|
|
60
|
+
root = createRoot(container)
|
|
61
|
+
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
|
62
|
+
await act(async () => {
|
|
63
|
+
root.render(
|
|
64
|
+
<QueryClientProvider client={client}>
|
|
65
|
+
<ConnectionProvider>
|
|
66
|
+
<Probe />
|
|
67
|
+
</ConnectionProvider>
|
|
68
|
+
</QueryClientProvider>,
|
|
69
|
+
)
|
|
70
|
+
})
|
|
71
|
+
// Let the first status poll land.
|
|
72
|
+
await advance(100)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
afterEach(() => {
|
|
76
|
+
act(() => root.unmount())
|
|
77
|
+
container.remove()
|
|
78
|
+
vi.restoreAllMocks()
|
|
79
|
+
vi.unstubAllGlobals()
|
|
80
|
+
vi.useRealTimers()
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
// Attempts land at 10s, 30s, 70s, 130s and 190s (10s doubling to a 60s cap).
|
|
84
|
+
const FIVE_ATTEMPTS_MS = 190_000
|
|
85
|
+
|
|
86
|
+
describe('ConnectionProvider auto-retry', () => {
|
|
87
|
+
it('carries the outage start from the server', () => {
|
|
88
|
+
expect(latest()?.connection.state).toBe('disconnected')
|
|
89
|
+
expect(latest()?.connection.disconnectedAt).toBe('2026-10-30T14:02:00Z')
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('keeps retrying every minute while someone is looking', async () => {
|
|
93
|
+
focused = true
|
|
94
|
+
await advance(FIVE_ATTEMPTS_MS)
|
|
95
|
+
expect(retries).toBe(5)
|
|
96
|
+
await advance(60_000)
|
|
97
|
+
expect(retries).toBe(6)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it('slows to every five minutes when nobody is looking, then retries at once on return', async () => {
|
|
101
|
+
await advance(FIVE_ATTEMPTS_MS)
|
|
102
|
+
expect(retries).toBe(5)
|
|
103
|
+
|
|
104
|
+
await advance(60_000)
|
|
105
|
+
expect(retries).toBe(5)
|
|
106
|
+
await advance(240_000)
|
|
107
|
+
expect(retries).toBe(6)
|
|
108
|
+
await advance(30_000)
|
|
109
|
+
|
|
110
|
+
focused = true
|
|
111
|
+
await act(async () => {
|
|
112
|
+
window.dispatchEvent(new Event('focus'))
|
|
113
|
+
document.dispatchEvent(new Event('visibilitychange'))
|
|
114
|
+
})
|
|
115
|
+
await advance(10)
|
|
116
|
+
// focus and visibilitychange together are one return, so one retry.
|
|
117
|
+
expect(retries).toBe(7)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('alt-tabbing back and forth retries no more than every ten seconds', async () => {
|
|
121
|
+
focused = true
|
|
122
|
+
await advance(15_000)
|
|
123
|
+
expect(retries).toBe(1) // the scheduled attempt at 10s
|
|
124
|
+
// Back to the window every 3s for 30s, as when switching to a terminal
|
|
125
|
+
// to fix the VPN and back.
|
|
126
|
+
for (let i = 0; i < 10; i++) {
|
|
127
|
+
await act(async () => {
|
|
128
|
+
window.dispatchEvent(new Event('blur'))
|
|
129
|
+
window.dispatchEvent(new Event('focus'))
|
|
130
|
+
document.dispatchEvent(new Event('visibilitychange'))
|
|
131
|
+
})
|
|
132
|
+
await advance(3_000)
|
|
133
|
+
}
|
|
134
|
+
// 30s of returns: at most one attempt per ten seconds, scheduled ones included.
|
|
135
|
+
expect(retries).toBeLessThanOrEqual(4)
|
|
136
|
+
expect(retries).toBeGreaterThanOrEqual(3)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('retries at once when the network comes back', async () => {
|
|
140
|
+
focused = true
|
|
141
|
+
await advance(15_000)
|
|
142
|
+
const before = retries
|
|
143
|
+
await act(async () => {
|
|
144
|
+
window.dispatchEvent(new Event('online'))
|
|
145
|
+
})
|
|
146
|
+
await advance(10)
|
|
147
|
+
expect(retries).toBe(before + 1)
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
describe('ConnectionProvider auto-retry across contexts and background windows', () => {
|
|
152
|
+
it('retries at once when the network comes back, even in a hidden window', async () => {
|
|
153
|
+
await advance(FIVE_ATTEMPTS_MS)
|
|
154
|
+
const before = retries
|
|
155
|
+
const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
|
|
156
|
+
await act(async () => {
|
|
157
|
+
window.dispatchEvent(new Event('online'))
|
|
158
|
+
})
|
|
159
|
+
await advance(10)
|
|
160
|
+
expect(retries).toBe(before + 1)
|
|
161
|
+
visibility.mockRestore()
|
|
162
|
+
})
|
|
163
|
+
it('starts a fresh count and backoff for another context', async () => {
|
|
164
|
+
await advance(FIVE_ATTEMPTS_MS)
|
|
165
|
+
expect(retries).toBe(5)
|
|
166
|
+
// The next status poll reports a different context that is also down.
|
|
167
|
+
pollContext = 'staging'
|
|
168
|
+
await advance(30_000)
|
|
169
|
+
await advance(100)
|
|
170
|
+
expect(latest()?.connection.context).toBe('staging')
|
|
171
|
+
const before = retries
|
|
172
|
+
// A fresh outage retries after the initial 10s, not the unattended 5 minutes.
|
|
173
|
+
await advance(10_500)
|
|
174
|
+
expect(retries).toBe(before + 1)
|
|
175
|
+
})
|
|
176
|
+
})
|
|
@@ -9,8 +9,19 @@ export interface ParsedContextInfo {
|
|
|
9
9
|
clusterName: string
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
// A switch Radar refused before leaving the current cluster, because the new
|
|
13
|
+
// one didn't answer. The app shows the connection error screen for it while
|
|
14
|
+
// staying connected to the current cluster underneath.
|
|
15
|
+
export interface FailedSwitch {
|
|
16
|
+
context: string
|
|
17
|
+
error: string
|
|
18
|
+
errorType: string
|
|
19
|
+
}
|
|
20
|
+
|
|
12
21
|
interface ContextSwitchState {
|
|
13
22
|
isSwitching: boolean
|
|
23
|
+
failedSwitch: FailedSwitch | null
|
|
24
|
+
setFailedSwitch: (failed: FailedSwitch | null) => void
|
|
14
25
|
targetContext: ParsedContextInfo | null
|
|
15
26
|
progressMessage: string | null
|
|
16
27
|
startSwitch: (context: ParsedContextInfo) => void
|
|
@@ -29,8 +40,10 @@ export function ContextSwitchProvider({ children }: { children: ReactNode }) {
|
|
|
29
40
|
const [isSwitching, setIsSwitching] = useState(false)
|
|
30
41
|
const [targetContext, setTargetContext] = useState<ParsedContextInfo | null>(null)
|
|
31
42
|
const [progressMessage, setProgressMessage] = useState<string | null>(null)
|
|
43
|
+
const [failedSwitch, setFailedSwitch] = useState<FailedSwitch | null>(null)
|
|
32
44
|
|
|
33
45
|
const startSwitch = useCallback((context: ParsedContextInfo) => {
|
|
46
|
+
setFailedSwitch(null)
|
|
34
47
|
setIsSwitching(true)
|
|
35
48
|
setTargetContext(context)
|
|
36
49
|
setProgressMessage(null)
|
|
@@ -57,7 +70,7 @@ export function ContextSwitchProvider({ children }: { children: ReactNode }) {
|
|
|
57
70
|
}, [])
|
|
58
71
|
|
|
59
72
|
return (
|
|
60
|
-
<ContextSwitchContext.Provider value={{ isSwitching, targetContext, progressMessage, startSwitch, updateProgress, endSwitch, setOpenAfterSwitch, takeOpenAfterSwitch }}>
|
|
73
|
+
<ContextSwitchContext.Provider value={{ isSwitching, failedSwitch, setFailedSwitch, targetContext, progressMessage, startSwitch, updateProgress, endSwitch, setOpenAfterSwitch, takeOpenAfterSwitch }}>
|
|
61
74
|
{children}
|
|
62
75
|
</ContextSwitchContext.Provider>
|
|
63
76
|
)
|
|
@@ -39,6 +39,9 @@ export type RenderDiagnoseAction = (ctx: {
|
|
|
39
39
|
/** Coarse health of the resource (from its status badge), so the entry point can
|
|
40
40
|
* adapt: an urgent "Investigate" on a problem vs. a quiet "ask AI" when fine/unknown. */
|
|
41
41
|
health?: "problem" | "healthy" | "unknown";
|
|
42
|
+
/** The object's metadata.creationTimestamp, when loaded. An investigation
|
|
43
|
+
* that started before it was of an earlier object with the same name. */
|
|
44
|
+
createdAt?: string;
|
|
42
45
|
}) => ReactNode;
|
|
43
46
|
|
|
44
47
|
/**
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createContext, useContext } from 'react'
|
|
2
|
+
|
|
3
|
+
// Whether the cluster is connected right now, for data hooks that poll it.
|
|
4
|
+
// Kept apart from ConnectionContext so api hooks can read it without a
|
|
5
|
+
// circular import. Defaults to true outside the provider (tests, hosts).
|
|
6
|
+
export const ClusterConnectedContext = createContext(true)
|
|
7
|
+
|
|
8
|
+
export function useClusterConnected(): boolean {
|
|
9
|
+
return useContext(ClusterConnectedContext)
|
|
10
|
+
}
|
|
@@ -159,6 +159,9 @@ export function useNamespacedCapabilities(namespace: string | undefined) {
|
|
|
159
159
|
console.warn('Failed to fetch namespace capabilities, using global:', namespace, error)
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
+
// A failed refetch keeps the last successful namespace answer; with none,
|
|
163
|
+
// the global value is not an answer for this namespace.
|
|
164
|
+
const namespaceUnknown = Boolean(namespace && !nsCaps && (isPending || error))
|
|
162
165
|
return useMemo(() => ({
|
|
163
166
|
canExec: nsCaps?.exec ?? globalCaps.exec,
|
|
164
167
|
canViewLogs: nsCaps?.logs ?? globalCaps.logs,
|
|
@@ -166,8 +169,7 @@ export function useNamespacedCapabilities(namespace: string | undefined) {
|
|
|
166
169
|
canHelmWrite: nsCaps?.helmWrite ?? globalCaps.helmWrite,
|
|
167
170
|
workloadWrites: nsCaps?.workloadWrites ?? globalCaps.workloadWrites,
|
|
168
171
|
workloadWritesPending: Boolean(namespace && isPending),
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}), [globalCaps.exec, globalCaps.logs, globalCaps.portForward, globalCaps.helmWrite, globalCaps.workloadWrites, error, isPending, namespace, nsCaps])
|
|
172
|
+
helmWriteUnknown: namespaceUnknown,
|
|
173
|
+
logsUnknown: namespaceUnknown,
|
|
174
|
+
}), [globalCaps.exec, globalCaps.logs, globalCaps.portForward, globalCaps.helmWrite, globalCaps.workloadWrites, isPending, namespace, nsCaps, namespaceUnknown])
|
|
173
175
|
}
|
|
@@ -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
|
+
}
|