Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([voice-weather-settings-location]): configurable home location for weather_now
Adam Eivy1f681837d6f9
diff --git a/client/src/components/settings/GeneralTab.jsx b/client/src/components/settings/GeneralTab.jsxindex d2db7ce021..88c6879aa1 100644--- a/client/src/components/settings/GeneralTab.jsx+++ b/client/src/components/settings/GeneralTab.jsx@@ -5,20 +5,68 @@ import BrailleSpinner from '../BrailleSpinner';import ThemePickerPanel from '../ThemePickerPanel';import { getSettings, updateSettings } from '../../services/api';+// Coordinate inputs are free text so a partially-typed "-" or "37." isn't+// clobbered mid-edit; parse + range-check only on save. Both blank = clear.+const isBlank = (v) => v === '' || v === null || v === undefined;+const parseCoord = (v) => {+ if (isBlank(v)) return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : NaN; // NaN signals "non-empty but not a number"+};+export function GeneralTab() {const [loading, setLoading] = useState(true);const [timezone, setTimezone] = useState('');const [saving, setSaving] = useState(false);+ const [lat, setLat] = useState('');+ const [lon, setLon] = useState('');+ const [savingLocation, setSavingLocation] = useState(false);const detectedTz = Intl.DateTimeFormat().resolvedOptions().timeZone;const allTimezones = useMemo(() => Intl.supportedValuesOf?.('timeZone') ?? [], []);useEffect(() => {getSettings()- .then(settings => setTimezone(settings?.timezone || ''))+ .then(settings => {+ setTimezone(settings?.timezone || '');+ setLat(settings?.location?.lat != null ? String(settings.location.lat) : '');+ setLon(settings?.location?.lon != null ? String(settings.location.lon) : '');+ }).catch(() => toast.error('Failed to load settings')).finally(() => setLoading(false));}, []);+ const handleSaveLocation = async () => {+ // Both-or-neither: weather needs a full pair, and a half-set pair would+ // silently mix a custom value with the tool's default coordinate.+ if (isBlank(lat) !== isBlank(lon)) {+ toast.error('Enter both latitude and longitude, or clear both.');+ return;+ }+ const parsedLat = parseCoord(lat);+ const parsedLon = parseCoord(lon);+ if (Number.isNaN(parsedLat) || Number.isNaN(parsedLon)) {+ toast.error('Latitude and longitude must be numbers.');+ return;+ }+ if (parsedLat !== null && (parsedLat < -90 || parsedLat > 90)) {+ toast.error('Latitude must be between -90 and 90.');+ return;+ }+ if (parsedLon !== null && (parsedLon < -180 || parsedLon > 180)) {+ toast.error('Longitude must be between -180 and 180.');+ return;+ }+ setSavingLocation(true);+ try {+ await updateSettings({ location: { lat: parsedLat, lon: parsedLon } });+ toast.success(parsedLat === null ? 'Location cleared' : `Location set to ${parsedLat}, ${parsedLon}`);+ } catch (err) {+ toast.error(err.message || 'Failed to save location');+ } finally {+ setSavingLocation(false);+ }+ };+const handleSave = async (tz) => {const tzToSave = tz || detectedTz;if (!tzToSave) {@@ -106,6 +154,48 @@ export function GeneralTab() {))}</datalist></div>++ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">+ <h3 className="text-lg font-semibold text-white mb-4">Location</h3>+ <p className="text-sm text-gray-400 mb-4">+ Your home coordinates. Used by the voice assistant's weather command when you+ ask “what's the weather?” without naming a place. Leave both blank to use a default location.+ </p>+ <div className="flex flex-col sm:flex-row sm:items-end gap-2 sm:gap-3">+ <div className="flex-1 sm:max-w-[10rem]">+ <label htmlFor="loc-lat" className="block text-xs text-gray-400 mb-1">Latitude (-90 to 90)</label>+ <input+ id="loc-lat"+ type="text"+ inputMode="decimal"+ value={lat}+ onChange={e => setLat(e.target.value)}+ placeholder="37.7749"+ className="w-full min-w-0 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </div>+ <div className="flex-1 sm:max-w-[10rem]">+ <label htmlFor="loc-lon" className="block text-xs text-gray-400 mb-1">Longitude (-180 to 180)</label>+ <input+ id="loc-lon"+ type="text"+ inputMode="decimal"+ value={lon}+ onChange={e => setLon(e.target.value)}+ placeholder="-122.4194"+ className="w-full min-w-0 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"+ />+ </div>+ <button+ onClick={handleSaveLocation}+ disabled={savingLocation}+ className="inline-flex items-center justify-center min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 whitespace-nowrap"+ >+ <Save size={14} className="inline mr-1" />+ {savingLocation ? 'Saving...' : 'Save'}+ </button>+ </div>+ </div></div>);}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex da24f9c4e9..761ba9f290 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1315,6 +1315,20 @@ export const sharingSettingsPatchSchema = z.object({sharingBio: z.string().trim().max(2000).optional(),}).strict();+// Geographic home location for location-aware features — the `weather_now`+// voice tool today, any future location-dependent surface tomorrow. Stored on+// `settings.location`. lat/lon are nullable so the user can clear a saved+// location and fall the consuming tool back to its default. The refine enforces+// both-or-neither so a half-set pair can't pin a nonsensical coordinate+// (e.g. a custom latitude with a default longitude).+export const locationSettingsSchema = z.object({+ lat: z.number().min(-90).max(90).nullable().optional(),+ lon: z.number().min(-180).max(180).nullable().optional(),+}).strict().refine(+ (d) => (d.lat == null) === (d.lon == null),+ { message: 'Provide both lat and lon, or neither.' },+);+// Subscription creation: persistent (bucket, record) tuple. Series + universe// are the subscribable kinds (records that change over time and benefit from// auto-re-export). Media is one-shot via /buckets/:id/export.diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 4c3e7ea0cd..52f68ef6b8 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -13,7 +13,8 @@ import {normalizeReviewers,buildReviewWithArgs,createCosTaskSchema,- featureProviderConfigSchema+ featureProviderConfigSchema,+ locationSettingsSchema} from './validation.js';describe('validation.js', () => {@@ -707,4 +708,40 @@ describe('validation.js', () => {expect(out).toEqual({ name: 'x' });});});++ describe('locationSettingsSchema', () => {+ it('accepts a valid lat/lon pair', () => {+ const r = locationSettingsSchema.safeParse({ lat: 37.7749, lon: -122.4194 });+ expect(r.success).toBe(true);+ expect(r.data).toEqual({ lat: 37.7749, lon: -122.4194 });+ });++ it('accepts an empty object (no location set)', () => {+ expect(locationSettingsSchema.safeParse({}).success).toBe(true);+ });++ it('accepts both fields null (cleared location)', () => {+ expect(locationSettingsSchema.safeParse({ lat: null, lon: null }).success).toBe(true);+ });++ it('rejects only one coordinate set (both-or-neither)', () => {+ expect(locationSettingsSchema.safeParse({ lat: 37.7749 }).success).toBe(false);+ expect(locationSettingsSchema.safeParse({ lat: 37.7749, lon: null }).success).toBe(false);+ expect(locationSettingsSchema.safeParse({ lon: -122.4194 }).success).toBe(false);+ });++ it('rejects out-of-range coordinates', () => {+ expect(locationSettingsSchema.safeParse({ lat: 91, lon: 0 }).success).toBe(false);+ expect(locationSettingsSchema.safeParse({ lat: 0, lon: 181 }).success).toBe(false);+ expect(locationSettingsSchema.safeParse({ lat: -91, lon: 0 }).success).toBe(false);+ });++ it('rejects non-number coordinates', () => {+ expect(locationSettingsSchema.safeParse({ lat: '37.7', lon: '-122.4' }).success).toBe(false);+ });++ it('rejects unknown keys (strict)', () => {+ expect(locationSettingsSchema.safeParse({ lat: 1, lon: 1, alt: 100 }).success).toBe(false);+ });+ });});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 8c91dc043d..207223795c 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -7,7 +7,7 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -63,6 +63,13 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.codeReview !== undefined) {validateRequest(codeReviewSettingsSchema.partial(), req.body.codeReview);}+ // Home location ({ lat, lon }) read by the weather_now voice tool. The schema+ // already makes both fields optional + nullable (clearing falls back to the+ // tool default), and the refine enforces both-or-neither — so validate the+ // whole slice rather than .partial()ing away that pairing rule.+ if (req.body?.location !== undefined) {+ validateRequest(locationSettingsSchema, req.body.location);+ }const merged = await updateSettings(req.body);// The queue caches codex.parallelLimit in-process; sync it from the// merged value so a save takes effect without a restart and withoutdiff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex a1bbdb7ed9..3a55883f54 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -1654,16 +1654,20 @@ const TOOLS = [},execute: async ({ lat, lon } = {}) => {// Resolve location: explicit params > settings.location > default.- const settings = await getSettings().catch(() => ({}));- const cfgLat = Number(settings?.location?.lat);- const cfgLon = Number(settings?.location?.lon);+ // numOrNull guards both paths so a null/empty/cleared coordinate falls+ // through to the default — `Number(null)` is 0 (a valid-but-wrong 0,0+ // coordinate), so reusing this helper for the config values is what keeps+ // a cleared `settings.location` from pinning the Gulf of Guinea.const numOrNull = (v) => {if (v === undefined || v === null || v === '') return null;const n = Number(v);return Number.isFinite(n) ? n : null;};- const resolvedLat = numOrNull(lat) ?? (Number.isFinite(cfgLat) ? cfgLat : null) ?? DEFAULT_LAT;- const resolvedLon = numOrNull(lon) ?? (Number.isFinite(cfgLon) ? cfgLon : null) ?? DEFAULT_LON;+ const settings = await getSettings().catch(() => ({}));+ const cfgLat = numOrNull(settings?.location?.lat);+ const cfgLon = numOrNull(settings?.location?.lon);+ const resolvedLat = numOrNull(lat) ?? cfgLat ?? DEFAULT_LAT;+ const resolvedLon = numOrNull(lon) ?? cfgLon ?? DEFAULT_LON;if (resolvedLat < -90 || resolvedLat > 90 || resolvedLon < -180 || resolvedLon > 180) {return { ok: false, summary: 'Latitude must be -90..90 and longitude -180..180.' };}diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex 4828ee05a8..4a5b8ba6b7 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -70,6 +70,8 @@ vi.mock('../feeds.js', () => ({// 'completed' event the real providers emit on imageGenEvents — without// that, the tool's await would hang for 5 minutes.const codexEnabledRef = { value: false };+// Drives settings.location for the weather_now configured-location tests.+const settingsLocationRef = { value: null };// Hoisting note: vi.mock factories run before the module under test loads,// so we can't import imageGenEvents up here. Instead, do the import lazily@@ -100,7 +102,10 @@ vi.mock('../imageGen/index.js', () => ({IMAGE_GEN_MODES: ['external', 'local', 'codex'],}));vi.mock('../settings.js', () => ({- getSettings: vi.fn(async () => ({ imageGen: { codex: { enabled: codexEnabledRef.value } } })),+ getSettings: vi.fn(async () => ({+ imageGen: { codex: { enabled: codexEnabledRef.value } },+ location: settingsLocationRef.value,+ })),}));// askService.runAsk is an async generator. Default mock yields a small@@ -1050,6 +1055,35 @@ describe('weather_now', () => {expect(r.ok).toBe(false);expect(r.summary).toMatch(/Couldn't reach the weather service/);});+ it('uses the configured settings.location when no coordinates are passed', async () => {+ weatherFetchRef.value = { ok: true, json: async () => ({ current: { temperature_2m: 55, weather_code: 0 } }) };+ settingsLocationRef.value = { lat: 51.5074, lon: -0.1278 };+ const r = await dispatchTool('weather_now', {});+ expect(r.ok).toBe(true);+ expect(r.lat).toBe(51.5074);+ expect(r.lon).toBe(-0.1278);+ settingsLocationRef.value = null;+ });+ it('lets explicit coordinates override the configured location', async () => {+ weatherFetchRef.value = { ok: true, json: async () => ({ current: { temperature_2m: 55, weather_code: 0 } }) };+ settingsLocationRef.value = { lat: 51.5074, lon: -0.1278 };+ const r = await dispatchTool('weather_now', { lat: 40, lon: -74 });+ expect(r.ok).toBe(true);+ expect(r.lat).toBe(40);+ expect(r.lon).toBe(-74);+ settingsLocationRef.value = null;+ });+ it('falls back to the default location when settings.location is null-cleared', async () => {+ weatherFetchRef.value = { ok: true, json: async () => ({ current: { temperature_2m: 55, weather_code: 0 } }) };+ // Number(null) is 0, so a naive resolver would pin 0,0 — assert the helper+ // treats a null coordinate as absent and falls through to the default.+ settingsLocationRef.value = { lat: null, lon: null };+ const r = await dispatchTool('weather_now', {});+ expect(r.ok).toBe(true);+ expect(r.lat).toBe(37.7749);+ expect(r.lon).toBe(-122.4194);+ settingsLocationRef.value = null;+ });});describe('timer_set', () => {