xonecas.io
53129
Pa

PAT / commit 6439350

feat: bug fixes and make the llm aware of time and timezone

xonecas2025-12-19 6439350291b531480e5bbfecbd49cba8310d729e parent 50b5a93

9 files changed

app/api/settings/route.ts+10−1
@@ -9,6 +9,7 @@ type Settings = {
99 selectedModel?: string;
1010 location?: string;
1111 currentTime?: string;
12+ timezone?: string;
1213 };
1314
1415 export async function GET() {
@@ -33,7 +34,7 @@ export async function GET() {
3334
3435 export async function POST(request: Request) {
3536 try {
36- const { maxPromptLength, selectedModel, location, currentTime } = await request.json();
37+ const { maxPromptLength, selectedModel, location, currentTime, timezone } = await request.json();
3738
3839 let settings: Partial<Settings> = {};
3940
@@ -69,6 +70,14 @@ export async function POST(request: Request) {
6970 settings.currentTime = currentTime;
7071 }
7172
73+ // Validate and set timezone if provided
74+ if (timezone !== undefined) {
75+ if (typeof timezone !== "string") {
76+ return NextResponse.json({ error: "Invalid timezone value" }, { status: 400 });
77+ }
78+ settings.timezone = timezone;
79+ }
80+
7281 // Get existing settings and merge, prefering the ones in the request
7382 const existingSettings = await getCache<Settings>(SETTINGS_CACHE_KEY);
7483 if (existingSettings) {
app/api/threads/route.ts+24−3
@@ -11,6 +11,7 @@ type Settings = {
1111 selectedModel?: string;
1212 location?: string;
1313 currentTime?: string;
14+ timezone?: string;
1415 };
1516
1617 export async function POST(request: Request) {
@@ -30,10 +31,11 @@ export async function POST(request: Request) {
3031
3132 const threadId = newThread[0].id;
3233
33- // Get location and currentTime from settings
34+ // Get location, currentTime, and timezone from settings
3435 const settings = await getCache<Settings>(SETTINGS_CACHE_KEY);
3536 const location = settings?.location;
3637 const currentTime = settings?.currentTime;
38+ const timezone = settings?.timezone;
3739
3840 // Build system prompt with location and time if available
3941 let systemPrompt = `You are PAT, a helpful personal assistant. You must follow these guidelines:
@@ -42,9 +44,28 @@ export async function POST(request: Request) {
4244 - Reply with markdown whenever possible
4345 - When asked for code or text return it in a markdown code block`;
4446
45- if (location || currentTime) {
47+ if (location || currentTime || timezone) {
4648 systemPrompt += "\n\n";
47- if (currentTime) {
49+ if (currentTime && timezone) {
50+ // Format time in the user's timezone
51+ try {
52+ const timeDate = new Date(currentTime);
53+ const formattedTime = new Intl.DateTimeFormat("en-US", {
54+ timeZone: timezone,
55+ year: "numeric",
56+ month: "long",
57+ day: "numeric",
58+ hour: "numeric",
59+ minute: "2-digit",
60+ second: "2-digit",
61+ timeZoneName: "short",
62+ }).format(timeDate);
63+ systemPrompt += `Current time: ${formattedTime}\n`;
64+ } catch (error) {
65+ // Fallback to ISO string if timezone formatting fails
66+ systemPrompt += `Current time: ${currentTime}\n`;
67+ }
68+ } else if (currentTime) {
4869 systemPrompt += `Current time: ${currentTime}\n`;
4970 }
5071 if (location) {
app/page.tsx+10−2
@@ -14,8 +14,14 @@ import "./highlight-theme.css";
1414 export default function Home() {
1515 const [error, setError] = useState<string | null>(null);
1616 const { themeMode, handleThemeChange } = useTheme();
17- const { selectedModel, handleModelChange, maxPromptLength, handleMaxPromptLengthChange } =
18- useSettings(setError);
17+ const {
18+ selectedModel,
19+ handleModelChange,
20+ maxPromptLength,
21+ handleMaxPromptLengthChange,
22+ location,
23+ handleLocationChange,
24+ } = useSettings(setError);
1925 const {
2026 threads,
2127 totalThreadCount,
@@ -184,6 +190,8 @@ export default function Home() {
184190 void loadMoreThreads(8, setError);
185191 }}
186192 hasMoreThreads={hasMoreThreads}
193+ location={location}
194+ onLocationChange={handleLocationChange}
187195 />
188196 </div>
189197 );
src/components/SettingsModal.tsx+14−0
@@ -7,6 +7,8 @@ type SettingsModalProps = {
77 onClose: () => void;
88 themeMode: "device" | "dark" | "light";
99 onThemeChange: (mode: "device" | "dark" | "light") => void;
10+ location: string;
11+ onLocationChange: (location: string) => void;
1012 };
1113
1214 export default function SettingsModal({
@@ -14,6 +16,8 @@ export default function SettingsModal({
1416 onClose,
1517 themeMode,
1618 onThemeChange,
19+ location,
20+ onLocationChange,
1721 }: SettingsModalProps) {
1822 return (
1923 <Modal isOpen={isOpen} onClose={onClose}>
@@ -33,6 +37,16 @@ export default function SettingsModal({
3337 <option value="light">Light</option>
3438 </select>
3539 </div>
40+ <div className="flex flex-col gap-2">
41+ <label className="text-neutral-600 dark:text-neutral-400">Location</label>
42+ <input
43+ type="text"
44+ value={location}
45+ onChange={(e) => onLocationChange(e.target.value)}
46+ placeholder="Enter location name (e.g., New York, London)"
47+ className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-900 dark:text-neutral-200"
48+ />
49+ </div>
3650 </div>
3751 </Modal>
3852 );
src/components/Sidebar.tsx+6−0
@@ -18,6 +18,8 @@ type SidebarProps = {
1818 onThemeChange: (mode: "device" | "dark" | "light") => void;
1919 onLoadMore: () => void;
2020 hasMoreThreads: boolean;
21+ location: string;
22+ onLocationChange: (location: string) => void;
2123 };
2224
2325 export default function Sidebar({
@@ -29,6 +31,8 @@ export default function Sidebar({
2931 onThemeChange,
3032 onLoadMore,
3133 hasMoreThreads,
34+ location,
35+ onLocationChange,
3236 }: SidebarProps) {
3337 const [isSettingsOpen, setIsSettingsOpen] = useState(false);
3438
@@ -111,6 +115,8 @@ export default function Sidebar({
111115 onClose={() => setIsSettingsOpen(false)}
112116 themeMode={themeMode}
113117 onThemeChange={onThemeChange}
118+ location={location}
119+ onLocationChange={onLocationChange}
114120 />
115121 </>
116122 );
src/hooks/useSettings.ts+41−13
@@ -3,8 +3,7 @@ import { useState, useEffect } from "react";
33 export function useSettings(onError?: (error: string) => void) {
44 const [selectedModel, setSelectedModel] = useState<string>("gpt-oss");
55 const [maxPromptLength, setMaxPromptLength] = useState<"none" | 1024 | 4096>("none");
6- const [location, setLocation] = useState<string | undefined>(undefined);
7- const [currentTime, setCurrentTime] = useState<string | undefined>(undefined);
6+ const [location, setLocation] = useState<string>("");
87
98 // Load settings from API and validate model against available models
109 useEffect(() => {
@@ -24,8 +23,7 @@ export function useSettings(onError?: (error: string) => void) {
2423 const settings = settingsData.settings || {};
2524 const savedModel = settings.selectedModel || "";
2625 const savedMaxPromptLength = settings.maxPromptLength || "none";
27- const savedLocation = settings.location;
28- const savedCurrentTime = settings.currentTime;
26+ const savedLocation = settings.location || "";
2927
3028 // Get available models
3129 const modelsRes = await fetch("/api/models");
@@ -42,19 +40,25 @@ export function useSettings(onError?: (error: string) => void) {
4240
4341 // Set maxPromptLength
4442 setMaxPromptLength(savedMaxPromptLength);
45- // Set location and currentTime
46- setLocation(savedLocation);
47- setCurrentTime(savedCurrentTime);
4843
49- // Post current time in ISO format to settings on app start
44+ // Get browser timezone and post current time in ISO format to settings on app start
45+ const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
5046 const currentTimeISO = new Date().toISOString();
47+
48+ // Use timezone as default location if no location is set
49+ const locationToUse = savedLocation || browserTimezone;
50+ setLocation(locationToUse);
51+
5152 try {
5253 await fetch("/api/settings", {
5354 method: "POST",
5455 headers: { "Content-Type": "application/json" },
55- body: JSON.stringify({ currentTime: currentTimeISO }),
56+ body: JSON.stringify({
57+ currentTime: currentTimeISO,
58+ timezone: browserTimezone,
59+ ...(savedLocation ? {} : { location: browserTimezone }),
60+ }),
5661 });
57- setCurrentTime(currentTimeISO);
5862 } catch (error) {
5963 // Silently fail - don't block app startup if time update fails
6064 if (onError && error instanceof Error) {
@@ -94,8 +98,7 @@ export function useSettings(onError?: (error: string) => void) {
9498 // On error, keep defaults
9599 setSelectedModel("");
96100 setMaxPromptLength("none");
97- setLocation(undefined);
98- setCurrentTime(undefined);
101+ setLocation("");
99102 }
100103 };
101104
@@ -150,11 +153,36 @@ export function useSettings(onError?: (error: string) => void) {
150153 }
151154 };
152155
156+ const handleLocationChange = async (value: string) => {
157+ setLocation(value);
158+ // Save to API
159+ try {
160+ const res = await fetch("/api/settings", {
161+ method: "POST",
162+ headers: { "Content-Type": "application/json" },
163+ body: JSON.stringify({ location: value }),
164+ });
165+ if (!res.ok) {
166+ const errorData = await res.json().catch((parseError) => {
167+ throw new Error(
168+ `Failed to parse error response: ${parseError instanceof Error ? parseError.message : "Invalid JSON"}`
169+ );
170+ });
171+ throw new Error(errorData.error || res.statusText);
172+ }
173+ } catch (error) {
174+ if (onError && error instanceof Error) {
175+ onError(error.message);
176+ }
177+ }
178+ };
179+
153180 return {
154181 selectedModel,
155182 handleModelChange,
156183 maxPromptLength,
157184 handleMaxPromptLengthChange,
185+ location,
186+ handleLocationChange,
158187 };
159188 }
160-
src/lib/ollama/title.ts+0−1
@@ -71,4 +71,3 @@ export async function generateTitle(
7171 return null;
7272 }
7373 }
74-
src/lib/ollama/tools/weather.ts+8−1
@@ -51,10 +51,17 @@ export async function queryWeather(
5151 // Increment rate limit counter before making the request
5252 // This ensures all API attempts are counted, not just successful ones
5353 await weatherRateLimiter.increment();
54+
55+ // Extract city name: if query contains a forward slash assume it's the timezone, use everything after it
56+ // Otherwise use the query as-is. Replace underscores with spaces for readability.
57+ const sanitizedQuery = query.includes("/")
58+ ? query.split("/").slice(1).join("/").replace(/_/g, " ").trim()
59+ : query.trim();
60+
5461 // First, geocode the location to get coordinates
5562 const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
5663 const geocodeParams = new URLSearchParams({
57- name: query,
64+ name: sanitizedQuery,
5865 count: "1",
5966 language: "en",
6067 format: "json",
tsconfig.tsbuildinfo+1−1
@@ -1 +1 @@
1-{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_m …
1+{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_m …