@skyhook-io/radar-app 1.23.0 → 1.23.1

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 (38) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +14 -3
  3. package/src/api/client.ts +29 -3
  4. package/src/api/client.updateResource.secretExpiry.test.tsx +47 -0
  5. package/src/api/poll.ts +78 -0
  6. package/src/api/radarFeatures.ts +3 -0
  7. package/src/components/CloudFunnelButton.tsx +1 -0
  8. package/src/components/helm/HelmDrawerRouting.test.tsx +34 -1
  9. package/src/components/helm/HelmReleaseDrawer.tsx +6 -4
  10. package/src/components/helm/HelmView.tsx +4 -3
  11. package/src/components/helm/ObservedHelmNotice.tsx +39 -17
  12. package/src/components/helm/ObservedHelmRelease.test.tsx +62 -3
  13. package/src/components/helm/ObservedHelmReleaseDrawer.test.tsx +18 -0
  14. package/src/components/helm/ObservedHelmReleaseDrawer.tsx +4 -2
  15. package/src/components/issues/uncheckedSources.test.ts +8 -0
  16. package/src/components/issues/uncheckedSources.ts +3 -0
  17. package/src/components/nudges/activeNudges.test.ts +39 -0
  18. package/src/components/nudges/activeNudges.ts +76 -0
  19. package/src/components/poll/OssPoll.tsx +871 -0
  20. package/src/components/poll/mount.test.ts +12 -0
  21. package/src/components/poll/pollCloud.test.ts +23 -0
  22. package/src/components/poll/pollCloud.ts +6 -0
  23. package/src/components/poll/pollDefinition.ts +93 -0
  24. package/src/components/poll/pollFlow.test.ts +140 -0
  25. package/src/components/poll/pollFlow.ts +137 -0
  26. package/src/components/poll/pollSender.test.ts +137 -0
  27. package/src/components/poll/pollSender.ts +76 -0
  28. package/src/components/poll/pollStorage.test.ts +53 -0
  29. package/src/components/poll/pollStorage.ts +77 -0
  30. package/src/components/poll/round.json +350 -0
  31. package/src/components/product-hunt/ProductHuntNotice.tsx +2 -0
  32. package/src/components/resources/ImageFilesystemModal.test.tsx +21 -1
  33. package/src/components/resources/ImageFilesystemModal.tsx +42 -3
  34. package/src/components/resources/ResourcesView.tsx +22 -5
  35. package/src/components/ui/UpdateNotification.tsx +2 -0
  36. package/src/components/usage-data/UsageDataPrompt.tsx +2 -0
  37. package/src/components/whats-new/WhatsNew.tsx +2 -0
  38. package/src/components/whats-new/releaseNotes.ts +75 -1
@@ -0,0 +1,12 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import app from '../../App.tsx?raw'
3
+
4
+ // @skyhook-io/radar-app ships App, and with it the poll. A host embedding
5
+ // Radar must never see it or have it call /api/poll.
6
+ describe('poll mounting', () => {
7
+ it('is mounted only when Radar is not embedded', () => {
8
+ const mounts = app.match(/.*<OssPoll\b.*/g) ?? []
9
+ expect(mounts).toHaveLength(1)
10
+ expect(mounts[0]).toContain('!navCustomization.embedded &&')
11
+ })
12
+ })
@@ -0,0 +1,23 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, describe, expect, it } from 'vitest'
3
+ import { OPEN_CLOUD_FUNNEL_EVENT, readOpenRequest, type CloudFunnelOpenRequest } from '../cloudHints/cloudHints'
4
+ import { openCloudFromPoll } from './pollCloud'
5
+
6
+ describe('openCloudFromPoll', () => {
7
+ const seen: CloudFunnelOpenRequest[] = []
8
+ const listener = (e: Event) => seen.push(readOpenRequest(e))
9
+ afterEach(() => {
10
+ window.removeEventListener(OPEN_CLOUD_FUNNEL_EVENT, listener)
11
+ seen.length = 0
12
+ })
13
+
14
+ it("opens the Cloud dialog as the poll's entry, on the view the answer asked for", () => {
15
+ window.addEventListener(OPEN_CLOUD_FUNNEL_EVENT, listener)
16
+ openCloudFromPoll('self-managed')
17
+ openCloudFromPoll('pitch')
18
+ expect(seen).toEqual([
19
+ { entry: 'oss-poll', subject: null, view: 'self-managed' },
20
+ { entry: 'oss-poll', subject: null, view: 'pitch' },
21
+ ])
22
+ })
23
+ })
@@ -0,0 +1,6 @@
1
+ import { openCloudFunnel, type CloudFunnelView } from '../cloudHints/cloudHints'
2
+
3
+ // Opens the Radar Cloud dialog from the poll, on the view that fits the answer.
4
+ export function openCloudFromPoll(view: CloudFunnelView) {
5
+ openCloudFunnel('oss-poll', undefined, view)
6
+ }
@@ -0,0 +1,93 @@
1
+ import roundJSON from './round.json'
2
+
3
+ export type QuestionKind = 'single' | 'multi' | 'text'
4
+
5
+ export interface PollOption {
6
+ id: string
7
+ label: string
8
+ }
9
+
10
+ /** Shows a question only when an earlier one was answered with one of `anyOf`. */
11
+ export interface PollCondition {
12
+ question: string
13
+ anyOf: string[]
14
+ }
15
+
16
+ export interface PollQuestion {
17
+ id: string
18
+ kind: QuestionKind
19
+ title: string
20
+ hint?: string
21
+ /** The option that opens a free-text box when picked. */
22
+ textOption?: string
23
+ textPlaceholder?: string
24
+ /** An option that can't be combined with the others, such as "None of these". */
25
+ exclusive?: string
26
+ showIf?: PollCondition
27
+ /** Questions sharing a screen id are asked together, on one screen. */
28
+ screen?: string
29
+ /** The heading of a shared screen, set on its first question. */
30
+ screenTitle?: string
31
+ /** Options are shown in a per-person order; the exclusive option stays last. */
32
+ shuffle?: boolean
33
+ options: PollOption[]
34
+ }
35
+
36
+ export interface PollRound {
37
+ id: string
38
+ /** When the round stops being offered; the server enforces it. */
39
+ endsAt: string
40
+ questions: PollQuestion[]
41
+ }
42
+
43
+ export interface PollAnswer {
44
+ choices?: string[]
45
+ text?: string
46
+ }
47
+
48
+ export type PollAnswers = Record<string, PollAnswer>
49
+
50
+ // The file is shared with the Go server, which validates answers against it.
51
+ export const CURRENT_ROUND = roundJSON as PollRound
52
+
53
+ export const POLL_COPY = {
54
+ cardTitle: 'Got two minutes to help us improve Radar OSS?',
55
+ cardBody: 'Seven quick questions about how you use it. Anonymous.',
56
+ cardAccept: 'Sure',
57
+ cardLater: 'Not now',
58
+ cardNever: "Don't ask again",
59
+ intro: 'Every question is optional. Answers are anonymous, and Radar never sends cluster data.',
60
+ otherPlaceholder: 'Tell us more',
61
+ contactAsk: "Could one of Radar's founders set up a 20-minute call with you?",
62
+ contactYouWrote: 'You wrote:',
63
+ contactMore: "We'd love to hear more.",
64
+ contactNotSales: 'Not a sales call, just product feedback.',
65
+ almostDone: 'Almost done',
66
+ contactBody: "We'd love to hear how you use Radar and what gets in your way. Not a sales call.",
67
+ emailLabel: 'Your email',
68
+ emailPlaceholder: 'you@example.com',
69
+ emailHelp: "We'll see it next to your answers. Used only to reach you. No newsletter.",
70
+ contactYes: 'Sure, get in touch',
71
+ contactNo: 'No thanks',
72
+ emailNeeded: 'Add your email so we can reach you.',
73
+ sending: 'Sending…',
74
+ thanks: 'Thanks. This goes straight into what we build next.',
75
+ enough: 'Good to hear. Thanks for using Radar.',
76
+ selfHost: "You said a hosted service isn't an option. Radar Cloud also runs inside your own network, including air-gapped ones.",
77
+ freeTier: 'You mentioned price. Radar Cloud has a free tier, so you can try it on a few clusters without paying.',
78
+ // One sentence, then a pointer at the header's Radar Cloud button.
79
+ pointerLeadFirstHeard: "You hadn't heard of it, so in short:",
80
+ pointerLeadHeard: 'In case you want a quick look:',
81
+ pointerLeadLooked: "In case it's been a while since you looked:",
82
+ pointerWhat: "Radar Cloud is our hosted service for teams: alerts, AI root cause and every cluster in one place. There's a free tier.",
83
+ pointerWhere: "It's the cloud button in the top bar, whenever you want a look.",
84
+ sendFailed: "Couldn't send your answers. Try again in a moment.",
85
+ closed: 'This poll has closed. Thanks for taking the time.',
86
+ contactFailed: "Your answers arrived, but your email didn't go through.",
87
+ contactRetry: 'Send the email again',
88
+ tooLong: 'Your answers are too long to send. Shorten the longest one and try again.',
89
+ back: 'Back',
90
+ next: 'Next',
91
+ finish: 'Finish',
92
+ done: 'Done',
93
+ } as const
@@ -0,0 +1,140 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { CURRENT_ROUND, POLL_COPY, type PollQuestion } from './pollDefinition'
3
+ import { closingLine, looksLikeEmail, newSubmissionId, orderedOptions, pollScreens, pruneAnswers, toggleChoice } from './pollFlow'
4
+
5
+ const q = (id: string) => CURRENT_ROUND.questions.find((x) => x.id === id) as PollQuestion
6
+ const screenIds = (answers = {}) => pollScreens(answers).map((s) => s.questions.map((x) => x.id))
7
+
8
+ describe('screens', () => {
9
+ it('asks seven screens, with the shared ones grouped', () => {
10
+ expect(screenIds()).toEqual([['q1'], ['role', 'clusters'], ['company', 'others'], ['better'], ['pains'], ['discover'], ['cloud']])
11
+ })
12
+
13
+ it('adds the blocker question to the last screen for people who know Radar Cloud but do not use it', () => {
14
+ for (const status of ['heard', 'looked', 'tried']) {
15
+ expect(screenIds({ cloud: { choices: [status] } }).at(-1)).toEqual(['cloud', 'cloud_blocker'])
16
+ }
17
+ for (const status of ['first_heard', 'use']) {
18
+ expect(screenIds({ cloud: { choices: [status] } }).at(-1)).toEqual(['cloud'])
19
+ }
20
+ })
21
+
22
+ it('titles the grouped screens', () => {
23
+ const screens = pollScreens({})
24
+ expect(screens[1].title).toBe('A bit about you')
25
+ expect(screens[2].title).toBe('About where you work')
26
+ })
27
+ })
28
+
29
+ describe('orderedOptions', () => {
30
+ it('shuffles per person but keeps the exclusive option last', () => {
31
+ for (const seed of [1, 42, 99_999]) {
32
+ for (const id of ['pains', 'discover']) {
33
+ const got = orderedOptions(q(id), seed).map((o) => o.id)
34
+ expect(got.at(-1)).toBe(q(id).exclusive)
35
+ expect([...got].sort()).toEqual(q(id).options.map((o) => o.id).sort())
36
+ }
37
+ }
38
+ })
39
+
40
+ it('keeps one order for the same person', () => {
41
+ expect(orderedOptions(q('discover'), 7)).toEqual(orderedOptions(q('discover'), 7))
42
+ })
43
+
44
+ it('leaves unshuffled questions in their written order', () => {
45
+ expect(orderedOptions(q('q1'), 7)).toEqual(q('q1').options)
46
+ })
47
+ })
48
+
49
+ describe('pruneAnswers', () => {
50
+ it('drops blockers stranded by changing the Radar Cloud answer after going Back', () => {
51
+ expect(pruneAnswers({ cloud: { choices: ['use'] }, cloud_blocker: { choices: ['price'] } })).toEqual({ cloud: { choices: ['use'] } })
52
+ })
53
+
54
+ it('keeps "other" text only while "other" is picked', () => {
55
+ expect(pruneAnswers({ q1: { choices: ['debug'], text: 'stale' } })).toEqual({ q1: { choices: ['debug'] } })
56
+ expect(pruneAnswers({ q1: { choices: ['other'], text: ' ops ' } })).toEqual({ q1: { choices: ['other'], text: 'ops' } })
57
+ })
58
+ })
59
+
60
+ describe('toggleChoice', () => {
61
+ it('keeps "None of these" exclusive', () => {
62
+ expect(toggleChoice(q('pains'), ['screenshots'], 'none')).toEqual(['none'])
63
+ expect(toggleChoice(q('pains'), ['none'], 'screenshots')).toEqual(['screenshots'])
64
+ })
65
+ it('keeps "I knew all of these" exclusive', () => {
66
+ expect(toggleChoice(q('discover'), ['mcp', 'rbac'], 'knew_all')).toEqual(['knew_all'])
67
+ expect(toggleChoice(q('discover'), ['knew_all'], 'mcp')).toEqual(['mcp'])
68
+ })
69
+ it('toggles a single-choice answer off when clicked again', () => {
70
+ expect(toggleChoice(q('clusters'), ['one'], 'one')).toEqual([])
71
+ expect(toggleChoice(q('clusters'), ['one'], 'four_ten')).toEqual(['four_ten'])
72
+ })
73
+ })
74
+
75
+ describe('closingLine', () => {
76
+ it('thanks Radar Cloud users and people for whom open-source Radar is enough, with no Radar Cloud line', () => {
77
+ expect(closingLine({ cloud: { choices: ['use'] } }, true)).toEqual({ kind: 'enough' })
78
+ expect(closingLine({ cloud: { choices: ['looked'] }, cloud_blocker: { choices: ['oss_enough', 'price'] } }, true)).toEqual({ kind: 'enough' })
79
+ expect(closingLine({ cloud: { choices: ['use'] } }, false)).toEqual({ kind: 'enough' })
80
+ })
81
+
82
+ it('answers hosted-service objections with the self-hosted edition, ahead of price', () => {
83
+ expect(closingLine({ cloud: { choices: ['tried'] }, cloud_blocker: { choices: ['price', 'cant_connect'] } }, true)).toEqual({ kind: 'self_host' })
84
+ expect(closingLine({ cloud: { choices: ['looked'] }, cloud_blocker: { choices: ['not_comfortable'] } }, true)).toEqual({ kind: 'self_host' })
85
+ })
86
+
87
+ it('answers price with the free tier', () => {
88
+ expect(closingLine({ cloud: { choices: ['heard'] }, cloud_blocker: { choices: ['price'] } }, true)).toEqual({ kind: 'free_tier' })
89
+ })
90
+
91
+ it('gives everyone else the short version, with a lead-in that matches their answer', () => {
92
+ expect(closingLine({ cloud: { choices: ['first_heard'] } }, true)).toEqual({ kind: 'short', lead: 'first_heard' })
93
+ expect(closingLine({ cloud: { choices: ['heard'] } }, true)).toEqual({ kind: 'short', lead: 'heard' })
94
+ expect(closingLine({ cloud: { choices: ['looked'] }, cloud_blocker: { choices: ['no_time'] } }, true)).toEqual({ kind: 'short', lead: 'looked' })
95
+ expect(closingLine({ cloud: { choices: ['tried'] } }, true)).toEqual({ kind: 'short', lead: 'looked' })
96
+ expect(closingLine({}, true)).toEqual({ kind: 'short', lead: null })
97
+ })
98
+
99
+ it('never reads the other answers', () => {
100
+ const others = { pains: { choices: ['screenshots', 'kubeconfig'] }, clusters: { choices: ['more_ten'] } }
101
+ expect(closingLine({ ...others, cloud: { choices: ['heard'] } }, true)).toEqual(closingLine({ cloud: { choices: ['heard'] } }, true))
102
+ })
103
+
104
+ it('shows no Radar Cloud line where its hints are off', () => {
105
+ expect(closingLine({ cloud: { choices: ['first_heard'] } }, false)).toBeNull()
106
+ expect(closingLine({ cloud: { choices: ['looked'] }, cloud_blocker: { choices: ['cant_connect'] } }, false)).toBeNull()
107
+ })
108
+ })
109
+
110
+ describe('ids and email', () => {
111
+ it('makes submission ids the server accepts', () => {
112
+ const id = newSubmissionId()
113
+ expect(id).toMatch(/^[A-Za-z0-9-]{16,64}$/)
114
+ expect(newSubmissionId()).not.toBe(id)
115
+ })
116
+ it('accepts only email-shaped addresses for a call', () => {
117
+ expect(looksLikeEmail(' a@b.io ')).toBe(true)
118
+ expect(looksLikeEmail('a@b')).toBe(false)
119
+ expect(looksLikeEmail('')).toBe(false)
120
+ })
121
+ })
122
+
123
+ describe('copy', () => {
124
+ it('states the real length on the card', () => {
125
+ expect(POLL_COPY.cardBody).toBe('Seven quick questions about how you use it. Anonymous.')
126
+ expect(pollScreens({})).toHaveLength(7)
127
+ })
128
+ it('says "Last one" on the last screen only', () => {
129
+ const screens = pollScreens({})
130
+ expect(screens.at(-1)!.questions[0].title.startsWith('Last one.')).toBe(true)
131
+ expect(screens.slice(0, -1).some((s) => s.questions.some((x) => x.title.includes('Last one')))).toBe(false)
132
+ })
133
+ it('uses no em dashes anywhere', () => {
134
+ const all = JSON.stringify(CURRENT_ROUND) + JSON.stringify(POLL_COPY)
135
+ expect(all).not.toContain('—')
136
+ })
137
+ it('compiles in no Radar Cloud prices or limits', () => {
138
+ expect(JSON.stringify(POLL_COPY)).not.toMatch(/\$|\b\d+ clusters\b|\b\d+ investigations\b|trial/i)
139
+ })
140
+ })
@@ -0,0 +1,137 @@
1
+ import { CURRENT_ROUND, type PollAnswers, type PollCondition, type PollQuestion, type PollRound } from './pollDefinition'
2
+
3
+ function met(c: PollCondition, answers: PollAnswers): boolean {
4
+ const chosen = answers[c.question]?.choices ?? []
5
+ return chosen.some((id) => c.anyOf.includes(id))
6
+ }
7
+
8
+ /**
9
+ * The questions this person will see, in order. Recomputed after each answer.
10
+ * Conditions read only answers to questions still on the path: an answer left
11
+ * behind by going Back and changing an earlier one must not show a question.
12
+ */
13
+ export function visibleQuestions(answers: PollAnswers, round: PollRound = CURRENT_ROUND): PollQuestion[] {
14
+ const onPath: PollAnswers = {}
15
+ const out: PollQuestion[] = []
16
+ for (const q of round.questions) {
17
+ if (q.showIf && !met(q.showIf, onPath)) continue
18
+ out.push(q)
19
+ if (answers[q.id]) onPath[q.id] = answers[q.id]
20
+ }
21
+ return out
22
+ }
23
+
24
+ /**
25
+ * Drops answers to questions that are no longer asked. Going Back and
26
+ * changing the Radar Cloud answer must not send blockers for the branch the
27
+ * person left.
28
+ */
29
+ export function pruneAnswers(answers: PollAnswers, round: PollRound = CURRENT_ROUND): PollAnswers {
30
+ const out: PollAnswers = {}
31
+ for (const q of visibleQuestions(answers, round)) {
32
+ const a = answers[q.id]
33
+ if (!a) continue
34
+ const allowed = new Set(q.options.map((o) => o.id))
35
+ const choices = (a.choices ?? []).filter((id) => allowed.has(id))
36
+ const keepText = q.kind === 'text' || (q.textOption !== undefined && choices.includes(q.textOption))
37
+ const text = keepText ? a.text?.trim() ?? '' : ''
38
+ if (choices.length || text) out[q.id] = { ...(choices.length ? { choices } : {}), ...(text ? { text } : {}) }
39
+ }
40
+ return out
41
+ }
42
+
43
+ /**
44
+ * Applies a click on an option, enforcing the question's own rules: one
45
+ * choice for single, and an exclusive option such as "None of these".
46
+ */
47
+ export function toggleChoice(q: PollQuestion, current: string[] | undefined, id: string): string[] {
48
+ const chosen = current ?? []
49
+ if (q.kind === 'single') return chosen[0] === id ? [] : [id]
50
+ if (chosen.includes(id)) return chosen.filter((c) => c !== id)
51
+ if (q.exclusive && id === q.exclusive) return [id]
52
+ const without = q.exclusive ? chosen.filter((c) => c !== q.exclusive) : chosen
53
+ return [...without, id]
54
+ }
55
+
56
+ export interface PollScreen {
57
+ id: string
58
+ title?: string
59
+ questions: PollQuestion[]
60
+ }
61
+
62
+ /** The visible questions grouped into screens: consecutive questions sharing a screen id are asked together. */
63
+ export function pollScreens(answers: PollAnswers, round: PollRound = CURRENT_ROUND): PollScreen[] {
64
+ const out: PollScreen[] = []
65
+ for (const q of visibleQuestions(answers, round)) {
66
+ const last = out[out.length - 1]
67
+ if (q.screen && last?.id === q.screen) last.questions.push(q)
68
+ else out.push({ id: q.screen ?? q.id, title: q.screenTitle, questions: [q] })
69
+ }
70
+ return out
71
+ }
72
+
73
+ /**
74
+ * The options in this person's order. A shuffled question keeps one order for
75
+ * the whole poll (the seed is fixed when it opens), and its exclusive option,
76
+ * such as "None of these", always comes last.
77
+ */
78
+ export function orderedOptions(q: PollQuestion, seed: number) {
79
+ const options = q.options
80
+ if (!q.shuffle) return options
81
+ const last = options.filter((o) => o.id === q.exclusive)
82
+ const rest = options.filter((o) => o.id !== q.exclusive)
83
+ let state = (seed ^ hash(q.id)) >>> 0 || 1
84
+ const rand = () => {
85
+ state ^= state << 13
86
+ state ^= state >>> 17
87
+ state ^= state << 5
88
+ return (state >>> 0) / 0x100000000
89
+ }
90
+ for (let i = rest.length - 1; i > 0; i--) {
91
+ const j = Math.floor(rand() * (i + 1))
92
+ ;[rest[i], rest[j]] = [rest[j], rest[i]]
93
+ }
94
+ return [...rest, ...last]
95
+ }
96
+
97
+ function hash(text: string): number {
98
+ let h = 2166136261
99
+ for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619)
100
+ return h >>> 0
101
+ }
102
+
103
+ export type ClosingLine =
104
+ | { kind: 'enough' }
105
+ | { kind: 'self_host' }
106
+ | { kind: 'free_tier' }
107
+ | { kind: 'short'; lead: 'first_heard' | 'heard' | 'looked' | null }
108
+ | null
109
+
110
+ /**
111
+ * The one line under the thank-you, chosen only from the Radar Cloud answers
112
+ * (first match wins). Lines that mention Radar Cloud need its hints to be on
113
+ * here; "Good to hear" does not mention it and always shows.
114
+ */
115
+ export function closingLine(answers: PollAnswers, cloudHints: boolean): ClosingLine {
116
+ const status = answers.cloud?.choices?.[0]
117
+ const blockers = answers.cloud_blocker?.choices ?? []
118
+ if (status === 'use' || blockers.includes('oss_enough')) return { kind: 'enough' }
119
+ if (!cloudHints) return null
120
+ if (blockers.includes('cant_connect') || blockers.includes('not_comfortable')) return { kind: 'self_host' }
121
+ if (blockers.includes('price')) return { kind: 'free_tier' }
122
+ if (status === 'first_heard' || status === 'heard') return { kind: 'short', lead: status }
123
+ if (status === 'looked' || status === 'tried') return { kind: 'short', lead: 'looked' }
124
+ return { kind: 'short', lead: null }
125
+ }
126
+
127
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
128
+
129
+ export function looksLikeEmail(value: string): boolean {
130
+ return EMAIL.test(value.trim())
131
+ }
132
+
133
+ export function newSubmissionId(): string {
134
+ const bytes = new Uint8Array(16)
135
+ crypto.getRandomValues(bytes)
136
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('').replace(/^(.{8})(.{4})(.{4})(.{4})/, '$1-$2-$3-$4-')
137
+ }
@@ -0,0 +1,137 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { createPollSender, type PollSendBody } from './pollSender'
3
+
4
+ const ID = '0123456789abcdef-0001'
5
+
6
+ // A submit whose requests the test resolves or fails one at a time.
7
+ function controlledSubmit() {
8
+ const sent: PollSendBody[] = []
9
+ const pending: { resolve: () => void; reject: (e: Error) => void }[] = []
10
+ const submit = (body: PollSendBody) => {
11
+ sent.push(body)
12
+ return new Promise<string>((resolve, reject) => pending.push({ resolve: () => resolve('ok'), reject }))
13
+ }
14
+ const settle = async (ok = true) => {
15
+ const p = pending.shift()!
16
+ if (ok) p.resolve()
17
+ else p.reject(new Error('offline'))
18
+ // Microtasks only, so this also works under fake timers.
19
+ for (let i = 0; i < 10; i++) await Promise.resolve()
20
+ }
21
+ return { sent, submit, settle }
22
+ }
23
+
24
+ describe('createPollSender', () => {
25
+ it('sends each step under one id with a rising step number', async () => {
26
+ const { sent, submit, settle } = controlledSubmit()
27
+ const sender = createPollSender(submit, ID)
28
+ sender.progress({ q1: { choices: ['debug'] } })
29
+ await settle()
30
+ sender.progress({ q1: { choices: ['debug'] }, q2: { choices: ['one'] } })
31
+ await settle()
32
+ expect(sent.map((b) => [b.submissionId, b.seq, b.complete])).toEqual([
33
+ [ID, 1, undefined],
34
+ [ID, 2, undefined],
35
+ ])
36
+ expect(sent[1].answers).toEqual({ q1: { choices: ['debug'] }, q2: { choices: ['one'] } })
37
+ })
38
+
39
+ it('carries a changed answer after Back as a newer step that replaces the old one', async () => {
40
+ const { sent, submit, settle } = controlledSubmit()
41
+ const sender = createPollSender(submit, ID)
42
+ sender.progress({ q2: { choices: ['one'] } })
43
+ await settle()
44
+ sender.progress({ q2: { choices: ['four_ten'] } })
45
+ await settle()
46
+ expect(sent.at(-1)).toMatchObject({ seq: 2, answers: { q2: { choices: ['four_ten'] } } })
47
+ })
48
+
49
+ it('keeps one send in flight and sends only the newest answers after it', async () => {
50
+ const { sent, submit, settle } = controlledSubmit()
51
+ const sender = createPollSender(submit, ID)
52
+ sender.progress({ q1: { choices: ['debug'] } })
53
+ sender.progress({ q2: { choices: ['one'] } })
54
+ sender.progress({ q2: { choices: ['two_three'] } })
55
+ expect(sent).toHaveLength(1)
56
+ await settle()
57
+ expect(sent).toHaveLength(2)
58
+ expect(sent[1]).toMatchObject({ seq: 2, answers: { q2: { choices: ['two_three'] } } })
59
+ })
60
+
61
+ it('skips a send when nothing changed since the last one that landed', async () => {
62
+ const { sent, submit, settle } = controlledSubmit()
63
+ const sender = createPollSender(submit, ID)
64
+ sender.progress({ q1: { choices: ['debug'] } })
65
+ await settle()
66
+ sender.progress({ q1: { choices: ['debug'] } })
67
+ expect(sent).toHaveLength(1)
68
+ })
69
+
70
+ it('swallows a failed step and lets the next one carry the answers', async () => {
71
+ const { sent, submit, settle } = controlledSubmit()
72
+ const sender = createPollSender(submit, ID)
73
+ sender.progress({ q1: { choices: ['debug'] } })
74
+ await expect(settle(false)).resolves.toBeUndefined()
75
+ sender.progress({ q1: { choices: ['debug'] } })
76
+ expect(sent).toHaveLength(2)
77
+ expect(sent[1]).toMatchObject({ seq: 2, answers: { q1: { choices: ['debug'] } } })
78
+ })
79
+
80
+ it('finishes with the email, marked complete, numbered after any step still in flight', async () => {
81
+ const { sent, submit, settle } = controlledSubmit()
82
+ const sender = createPollSender(submit, ID)
83
+ sender.progress({ q1: { choices: ['debug'] } })
84
+ const done = sender.finish({ answers: { q1: { choices: ['debug'] } }, email: 'sam@example.com', wantsCall: true })
85
+ expect(sent[1]).toMatchObject({ seq: 2, complete: true, email: 'sam@example.com', wantsCall: true })
86
+ await settle()
87
+ await settle()
88
+ await expect(done).resolves.toBe('ok')
89
+ })
90
+
91
+ it('sends no more steps while a finish is in flight', async () => {
92
+ const { sent, submit } = controlledSubmit()
93
+ const sender = createPollSender(submit, ID)
94
+ void sender.finish({ answers: { q1: { choices: ['debug'] } } })
95
+ sender.progress({ q1: { choices: ['browse'] } })
96
+ expect(sent).toHaveLength(1)
97
+ })
98
+
99
+ it('after a failed finish, sends nothing until the person finishes again', async () => {
100
+ vi.useFakeTimers()
101
+ try {
102
+ const { sent, submit, settle } = controlledSubmit()
103
+ const sender = createPollSender(submit, ID)
104
+ const first = sender.finish({ answers: { better: { text: 'internal-name' } } })
105
+ await settle(false)
106
+ await expect(first).rejects.toThrow('offline')
107
+ // Never a partial send after a finish: it could undo one that landed.
108
+ sender.progress({})
109
+ await vi.advanceTimersByTimeAsync(60_000)
110
+ expect(sent).toHaveLength(1)
111
+ const corrected = { better: { text: 'faster logs' } }
112
+ void sender.finish({ answers: corrected })
113
+ expect(sent[1]).toMatchObject({ seq: 2, complete: true, answers: corrected })
114
+ } finally {
115
+ vi.useRealTimers()
116
+ }
117
+ })
118
+
119
+ it('resends a withdrawn answer after a send whose reply was lost', async () => {
120
+ const { sent, submit, settle } = controlledSubmit()
121
+ const sender = createPollSender(submit, ID)
122
+ sender.progress({ better: { text: 'internal-name' } })
123
+ await settle(false)
124
+ // The person goes Back and clears it: that empty snapshot must still go out.
125
+ sender.progress({})
126
+ expect(sent[1]).toMatchObject({ seq: 2, answers: {} })
127
+ })
128
+
129
+ it('never puts an email on a progress step', async () => {
130
+ const { sent, submit, settle } = controlledSubmit()
131
+ const sender = createPollSender(submit, ID)
132
+ sender.progress({ q7: { text: 'faster topology' } })
133
+ await settle()
134
+ expect(sent[0]).not.toHaveProperty('email')
135
+ expect(sent[0]).not.toHaveProperty('wantsCall')
136
+ })
137
+ })
@@ -0,0 +1,76 @@
1
+ import type { PollAnswers } from './pollDefinition'
2
+
3
+ export interface PollSendBody {
4
+ submissionId: string
5
+ seq: number
6
+ answers: PollAnswers
7
+ complete?: boolean
8
+ email?: string
9
+ wantsCall?: boolean
10
+ }
11
+
12
+ export interface PollSender<T> {
13
+ /** Sends the answers so far, quietly. A failure is carried by the next send. */
14
+ progress(answers: PollAnswers): void
15
+ /** The last send: the finished answers, plus the email when one was given. */
16
+ finish(body: { answers: PollAnswers; email?: string; wantsCall?: boolean }): Promise<T>
17
+ }
18
+
19
+ /**
20
+ * Sends a response as the person moves through the poll, so an unfinished one
21
+ * still counts. Every send carries all the answers so far under one id and a
22
+ * rising step number; the receiver keeps the highest, so a changed or skipped
23
+ * answer replaces the earlier one. One progress send is in flight at a time,
24
+ * and the newest answers wait behind it, so an older send can never land last.
25
+ */
26
+ export function createPollSender<T>(
27
+ submit: (body: PollSendBody) => Promise<T>,
28
+ submissionId: string,
29
+ onStepError?: (err: unknown) => void,
30
+ ): PollSender<T> {
31
+ let seq = 0
32
+ let running = false
33
+ let waiting: PollAnswers | null = null
34
+ // What the receiver is known to hold. Null after a failed send, which may
35
+ // still have landed: the next snapshot then goes out even if it looks the
36
+ // same as an earlier one, so a withdrawn answer can't stay behind.
37
+ let lastSent: string | null = JSON.stringify({})
38
+ let finished = false
39
+
40
+ const drain = async () => {
41
+ running = true
42
+ while (waiting && !finished) {
43
+ const answers = waiting
44
+ waiting = null
45
+ const key = JSON.stringify(answers)
46
+ if (key === lastSent) continue
47
+ try {
48
+ await submit({ submissionId, seq: ++seq, answers })
49
+ lastSent = key
50
+ } catch (err) {
51
+ lastSent = null
52
+ // The next send carries these answers too; the caller only hears about
53
+ // errors that change what the person should see, such as a closed round.
54
+ onStepError?.(err)
55
+ }
56
+ }
57
+ running = false
58
+ }
59
+
60
+ return {
61
+ progress(answers) {
62
+ if (finished) return
63
+ waiting = answers
64
+ if (!running) void drain()
65
+ },
66
+ finish(body) {
67
+ // Progress still in flight takes a lower step number, so this one wins.
68
+ // After a finish, only finishes follow: a partial send could undo one
69
+ // that landed. A failed finish is retried only when the person asks;
70
+ // closing sends nothing more.
71
+ finished = true
72
+ waiting = null
73
+ return submit({ submissionId, seq: ++seq, complete: true, ...body })
74
+ },
75
+ }
76
+ }