Skip to content

The agent that grows with you

fix(tui): move weather widget to Open-Meteo

Vitor Cepeda Lopesb5821a578d96
diff --git a/ui-tui/src/__tests__/weatherApp.test.ts b/ui-tui/src/__tests__/weatherApp.test.ts
index 35a9818850c..379183e6095 100644
--- a/ui-tui/src/__tests__/weatherApp.test.ts
+++ b/ui-tui/src/__tests__/weatherApp.test.ts
@@ -8,19 +8,24 @@ import type { WidgetInput } from '../sdk/types.js'
const key = (overrides: Partial<WidgetInput['key']> = {}, ch = ''): WidgetInput =>
({ ch, key: { ctrl: false, escape: false, return: false, ...overrides } }) as WidgetInput
-const wttrReply = (weatherCode: string) => ({
- current_condition: [
- {
- FeelsLikeC: '20',
- humidity: '40',
- temp_C: '22',
- weatherCode,
- weatherDesc: [{ value: 'Sunny' }],
- windspeedKmph: '7'
- }
- ],
- nearest_area: [{ areaName: [{ value: 'Austin' }], country: [{ value: 'USA' }] }]
-})
+const ipGeoReply = {
+ city: 'Cascais',
+ country: 'Portugal',
+ latitude: 38.6968,
+ longitude: -9.4215,
+ success: true,
+ timezone: { id: 'Europe/Lisbon' }
+}
+
+const openMeteoForecast = {
+ current: {
+ apparent_temperature: 20,
+ relative_humidity_2m: 40,
+ temperature_2m: 22,
+ weather_code: 0,
+ wind_speed_10m: 7
+ }
+}
const activeState = () => getOverlayState().ambient.find(a => a.appId === 'weather')?.state as undefined | WeatherState
@@ -28,11 +33,84 @@ beforeEach(() => resetOverlayState())
afterEach(() => vi.unstubAllGlobals())
describe('weather reference app (async contract)', () => {
+ it('uses Open-Meteo for a named location', async () => {
+ const fetchMock = vi.fn(async (input: string | URL | Request) => {
+ const url = String(input)
+
+ if (url.startsWith('https://geocoding-api.open-meteo.com/')) {
+ return {
+ json: async () => ({
+ results: [
+ { country: 'USA', latitude: 30.2672, longitude: -97.7431, name: 'Austin', timezone: 'America/Chicago' }
+ ]
+ }),
+ ok: true
+ }
+ }
+
+ if (url.startsWith('https://api.open-meteo.com/')) {
+ return { json: async () => openMeteoForecast, ok: true }
+ }
+
+ throw new Error(`unexpected weather URL: ${url}`)
+ })
+
+ vi.stubGlobal('fetch', fetchMock)
+
+ launchWidget('weather', 'Austin')
+ await vi.waitFor(() => expect(activeState()?.phase.kind).toBe('ready'))
+
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(activeState()?.phase).toMatchObject({
+ kind: 'ready',
+ report: { area: 'Austin, USA', condition: 'Clear sky', tempC: '22', weatherCode: 0 }
+ })
+ })
+
+ it('geolocates by IP when the location is blank', async () => {
+ const fetchMock = vi.fn(async (input: string | URL | Request) => {
+ const url = String(input)
+
+ if (url.startsWith('https://ipwho.is/')) {
+ return {
+ json: async () => ipGeoReply,
+ ok: true
+ }
+ }
+
+ if (url.startsWith('https://api.open-meteo.com/')) {
+ return { json: async () => openMeteoForecast, ok: true }
+ }
+
+ throw new Error(`unexpected weather URL: ${url}`)
+ })
+
+ vi.stubGlobal('fetch', fetchMock)
+
+ launchWidget('weather', '')
+ await vi.waitFor(() => expect(activeState()?.phase.kind).toBe('ready'))
+
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(activeState()?.phase).toMatchObject({
+ kind: 'ready',
+ report: { area: 'Cascais, Portugal', tempC: '22' }
+ })
+ })
+
it('launches into loading, lands the fetch via updateWidget', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () => ({ json: async () => wttrReply('113'), ok: true }))
- )
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({
+ json: async () => ({
+ results: [
+ { country: 'USA', latitude: 30.2672, longitude: -97.7431, name: 'Austin', timezone: 'America/Chicago' }
+ ]
+ }),
+ ok: true
+ })
+ .mockResolvedValueOnce({ json: async () => openMeteoForecast, ok: true })
+
+ vi.stubGlobal('fetch', fetchMock)
expect(launchWidget('weather', 'Austin')).toBeNull()
expect(activeState()?.phase.kind).toBe('loading')
@@ -41,25 +119,28 @@ describe('weather reference app (async contract)', () => {
const phase = activeState()!.phase
- expect(phase).toMatchObject({ kind: 'ready', report: { area: 'Austin, USA', tempC: '22', weatherCode: 113 } })
+ expect(phase).toMatchObject({ kind: 'ready', report: { area: 'Austin, USA', tempC: '22', weatherCode: 0 } })
})
it('a late resolution cannot resurrect a closed app', async () => {
- let resolve!: (value: unknown) => void
+ let resolveForecast!: (value: unknown) => void
- vi.stubGlobal(
- 'fetch',
- vi.fn(() => new Promise(r => (resolve = r)))
- )
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({ json: async () => ipGeoReply, ok: true })
+ .mockImplementationOnce(() => new Promise(resolve => (resolveForecast = resolve)))
+
+ vi.stubGlobal('fetch', fetchMock)
launchWidget('weather', '')
expect(activeState()?.phase.kind).toBe('loading')
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
- // Toggle closed while in flight (ambient dismissal), then resolve.
+ // Toggle closed while the final forecast is in flight, then complete it.
expect(launchWidget('weather', '')).toBeNull()
expect(getOverlayState().ambient).toEqual([])
- resolve({ json: async () => wttrReply('113'), ok: true })
- await new Promise(r => setTimeout(r, 0))
+ resolveForecast({ json: async () => openMeteoForecast, ok: true })
+ await new Promise(resolve => setTimeout(resolve, 0))
expect(getOverlayState().ambient).toEqual([])
})
@@ -78,7 +159,7 @@ describe('weather reference app (async contract)', () => {
it('r refreshes; Esc/q/Enter close', () => {
vi.stubGlobal(
'fetch',
- vi.fn(async () => ({ json: async () => wttrReply('113'), ok: true }))
+ vi.fn(async () => ({ json: async () => ipGeoReply, ok: true }))
)
const state: WeatherState = { location: 'x', phase: { kind: 'error', message: 'boom' } }
diff --git a/ui-tui/src/sdk/apps/weather.tsx b/ui-tui/src/sdk/apps/weather.tsx
index eedd51e1a70..a8850e683cd 100644
--- a/ui-tui/src/sdk/apps/weather.tsx
+++ b/ui-tui/src/sdk/apps/weather.tsx
@@ -42,20 +42,51 @@ interface Report {
windKmph: string
}
-// WWO weather codes → art bucket. Table-driven; unknown codes read as cloud.
+// WMO weather codes → art bucket. Table-driven; unknown codes read as cloud.
type Art = 'cloud' | 'fog' | 'rain' | 'snow' | 'sun' | 'thunder'
const ART_BY_CODE: readonly [codes: readonly number[], art: Art][] = [
- [[113], 'sun'],
- [[116, 119, 122], 'cloud'],
- [[143, 248, 260], 'fog'],
- [[176, 263, 266, 293, 296, 299, 302, 305, 308, 353, 356, 359], 'rain'],
- [[179, 182, 185, 227, 230, 320, 323, 326, 329, 332, 335, 338, 350, 368, 371, 374, 377], 'snow'],
- [[200, 386, 389, 392, 395], 'thunder']
+ [[0], 'sun'],
+ [[1, 2, 3], 'cloud'],
+ [[45, 48], 'fog'],
+ [[51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 80, 81, 82], 'rain'],
+ [[71, 73, 75, 77, 85, 86], 'snow'],
+ [[95, 96, 99], 'thunder']
]
const artFor = (code: number): Art => ART_BY_CODE.find(([codes]) => codes.includes(code))?.[1] ?? 'cloud'
+const CONDITION_BY_CODE: Readonly<Record<number, string>> = {
+ 0: 'Clear sky',
+ 1: 'Mainly clear',
+ 2: 'Partly cloudy',
+ 3: 'Overcast',
+ 45: 'Fog',
+ 48: 'Rime fog',
+ 51: 'Light drizzle',
+ 53: 'Drizzle',
+ 55: 'Heavy drizzle',
+ 56: 'Light freezing drizzle',
+ 57: 'Freezing drizzle',
+ 61: 'Light rain',
+ 63: 'Rain',
+ 65: 'Heavy rain',
+ 66: 'Light freezing rain',
+ 67: 'Freezing rain',
+ 71: 'Light snow',
+ 73: 'Snow',
+ 75: 'Heavy snow',
+ 77: 'Snow grains',
+ 80: 'Light rain showers',
+ 81: 'Rain showers',
+ 82: 'Heavy rain showers',
+ 85: 'Light snow showers',
+ 86: 'Heavy snow showers',
+ 95: 'Thunderstorm',
+ 96: 'Thunderstorm with hail',
+ 99: 'Severe thunderstorm with hail'
+}
+
const ART: Record<Art, readonly string[]> = {
sun: [' \\ / ', ' .-. ', ' ― ( ) ― ', " `-' ", ' / \\ '],
cloud: [' ', ' .--. ', ' .-( ). ', ' (___.__)__) ', ' '],
@@ -77,43 +108,121 @@ const artColor = (art: Art, t: Theme): string =>
thunder: t.color.warn
})[art]
+interface Coordinates {
+ area: string
+ latitude: number
+ longitude: number
+ timezone: string
+}
+
+async function geocodeLocation(location: string): Promise<Coordinates> {
+ const params = new URLSearchParams({ count: '1', format: 'json', language: 'en', name: location })
+
+ const res = await fetch(`https://geocoding-api.open-meteo.com/v1/search?${params}`, {
+ headers: { 'User-Agent': 'hermes-tui-weather' },
+ signal: AbortSignal.timeout(10_000)
+ })
+
+ if (!res.ok) {
+ throw new Error(`Open-Meteo geocoding answered ${res.status}`)
+ }
+
+ const data = (await res.json()) as {
+ results?: { country?: string; latitude?: number; longitude?: number; name?: string; timezone?: string }[]
+ }
+
+ const place = data.results?.[0]
+
+ if (!place || place.latitude === undefined || place.longitude === undefined) {
+ throw new Error(`location not found: ${location}`)
+ }
+
+ return {
+ area: [place.name, place.country].filter(Boolean).join(', ') || location,
+ latitude: place.latitude,
+ longitude: place.longitude,
+ timezone: place.timezone ?? 'auto'
+ }
+}
+
+async function geolocateByIp(): Promise<Coordinates> {
+ const fields = 'success,city,country,latitude,longitude,timezone'
+
+ const res = await fetch(`https://ipwho.is/?fields=${fields}`, {
+ headers: { 'User-Agent': 'hermes-tui-weather' },
+ signal: AbortSignal.timeout(10_000)
+ })
+
+ if (!res.ok) {
+ throw new Error(`IP geolocation answered ${res.status}`)
+ }
+
+ const data = (await res.json()) as {
+ city?: string
+ country?: string
+ latitude?: number
+ longitude?: number
+ success?: boolean
+ timezone?: { id?: string }
+ }
+
+ if (data.success !== true || data.latitude === undefined || data.longitude === undefined) {
+ throw new Error('automatic location could not be resolved')
+ }
+
+ return {
+ area: [data.city, data.country].filter(Boolean).join(', ') || 'here',
+ latitude: data.latitude,
+ longitude: data.longitude,
+ timezone: data.timezone?.id ?? 'auto'
+ }
+}
+
async function fetchReport(location: string): Promise<Report> {
- const res = await fetch(`https://wttr.in/${encodeURIComponent(location)}?format=j1`, {
+ const place = location ? await geocodeLocation(location) : await geolocateByIp()
+
+ const params = new URLSearchParams({
+ current: 'temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,weather_code',
+ latitude: String(place.latitude),
+ longitude: String(place.longitude),
+ timezone: place.timezone
+ })
+
+ const res = await fetch(`https://api.open-meteo.com/v1/forecast?${params}`, {
headers: { 'User-Agent': 'hermes-tui-weather' },
signal: AbortSignal.timeout(10_000)
})
if (!res.ok) {
- throw new Error(`wttr.in answered ${res.status}`)
+ throw new Error(`Open-Meteo forecast answered ${res.status}`)
}
const data = (await res.json()) as {
- current_condition?: {
- FeelsLikeC?: string
- humidity?: string
- temp_C?: string
- weatherCode?: string
- weatherDesc?: { value?: string }[]
- windspeedKmph?: string
- }[]
- nearest_area?: { areaName?: { value?: string }[]; country?: { value?: string }[] }[]
+ current?: {
+ apparent_temperature?: number
+ relative_humidity_2m?: number
+ temperature_2m?: number
+ weather_code?: number
+ wind_speed_10m?: number
+ }
}
- const now = data.current_condition?.[0]
- const area = data.nearest_area?.[0]
+ const now = data.current
if (!now) {
throw new Error('no current conditions in reply')
}
+ const weatherCode = now.weather_code ?? -1
+
return {
- area: [area?.areaName?.[0]?.value, area?.country?.[0]?.value].filter(Boolean).join(', ') || location || 'here',
- condition: now.weatherDesc?.[0]?.value ?? 'unknown',
- feelsC: now.FeelsLikeC ?? '?',
- humidity: now.humidity ?? '?',
- tempC: now.temp_C ?? '?',
- weatherCode: Number(now.weatherCode ?? 116),
- windKmph: now.windspeedKmph ?? '?'
+ area: place.area,
+ condition: CONDITION_BY_CODE[weatherCode] ?? 'Unknown conditions',
+ feelsC: String(now.apparent_temperature ?? '?'),
+ humidity: String(now.relative_humidity_2m ?? '?'),
+ tempC: String(now.temperature_2m ?? '?'),
+ weatherCode,
+ windKmph: String(now.wind_speed_10m ?? '?')
}
}
@@ -130,7 +239,7 @@ function load(location: string): void {
export const weatherApp = defineWidgetApp<WeatherState>({
id: 'weather',
- help: 'current conditions with themed ASCII art (wttr.in)',
+ help: 'current conditions with themed ASCII art (Open-Meteo)',
mode: 'ambient',
usage: USAGE,