import {expect, test} from 'bun:test' import {needs} from '@/lib/needs' import type {Hosted} from '@/lib/stream' import type {AdminRequest, Decision} from '@/lib/types' const hosted = (id: string, status: Hosted['status'], updated: number, archived = false): Hosted => ({kind: 'hosted', id, title: id, status, branch: '', owner: `session-${id}`, by: '', created: updated, updated, base: 'main', archived}) as Hosted const decision = (id: string, at: number, answer?: string): Decision => ({id, question: '?', options: [], by: 'a', with: [], at, answer}) test('open questions first, oldest first; then permissions; then sessions stuck starting', () => { const now = 10_000 const got = needs( [decision('d2', 500), decision('d1', 100), decision('d0', 50, 'yes')], [hosted('s1', 'needs_permission', 9000), hosted('s2', 'starting', now - 400), hosted('s3', 'starting', now - 60), hosted('s4', 'working', 0)], now, ) expect(got.map((n) => (n.kind === 'decision' ? n.decision.id : n.kind === 'admin' ? n.request.id : n.session.id))).toEqual(['d1', 'd2', 's1', 's2']) expect(got[3]).toMatchObject({kind: 'stuck', for_s: 400}) }) test('what only the person can do comes after permissions, oldest first; put off or at work, it waits', () => { const now = 10_000 const awaits = (at: number, snooze?: number) => ({awaits: {text: 'Paste a token', by: 'session-x', at, snooze}}) const got = needs( [], [ {...hosted('s1', 'waiting', 0), ...awaits(900)}, {...hosted('s2', 'stopped', 0), ...awaits(100)}, {...hosted('s3', 'needs_permission', 0)}, {...hosted('s4', 'waiting', 0), ...awaits(50, now + 60)}, {...hosted('s5', 'working', 0), ...awaits(50)}, {...hosted('s6', 'waiting', 0, true), ...awaits(50)}, ], now, ) expect(got.map((n) => (n.kind === 'decision' || n.kind === 'admin' ? '' : `${n.kind}:${n.session.id}`))).toEqual(['permission:s3', 'awaits:s2', 'awaits:s1']) }) test('an archived session asks nothing of the person', () => { expect(needs([], [hosted('s1', 'needs_permission', 0, true)], 1)).toEqual([]) }) test('a session asking for root comes first; answered, it asks nothing', () => { const req = (id: string, state: string): AdminRequest => ({id, session: 'session-s9', reason: 'restart caddy', minutes: 30, at: 1, state}) const got = needs([decision('d1', 100)], [], 1000, [req('a2', 'asked'), req('a1', 'open'), req('a0', 'declined')]) expect(got.map((n) => (n.kind === 'admin' ? n.request.id : n.kind === 'decision' ? n.decision.id : ''))).toEqual(['a2', 'd1']) })