diff --git a/src/store/index.ts b/src/store/index.ts index f9d908d..90f8a04 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -165,6 +165,68 @@ export interface Filter { editedToday: boolean; } +// Background sync for Context Switcher (polling fallback for realtime) +let contextSyncInterval: number | undefined; + +export const startContextPolling = () => { + if (contextSyncInterval) { + clearInterval(contextSyncInterval); + contextSyncInterval = undefined; + } + + const ctx = currentTaskContext(); + if (typeof ctx === 'object' && 'userId' in ctx) { + contextSyncInterval = window.setInterval(async () => { + if (!pb.authStore.isValid) return; + + try { + // Fetch only recent updates (last 30s) to minimize payload + const timeStr = new Date(Date.now() - 30000).toISOString(); + const records = await pb.collection(TASGRID_COLLECTION).getFullList({ + filter: `user = "${ctx.userId}" && updated >= "${timeStr}"`, + sort: '-updated', + fields: LIST_FIELDS, + requestKey: 'context-poll' + }); + + if (records.length === 0) return; + + setStore("tasks", (currentTasks) => { + const taskMap = new Map(currentTasks.map(t => [t.id, t])); + let changed = false; + + records.forEach((r: any) => { + if (r.tags?.includes("__template__")) return; + + const existing = taskMap.get(r.id); + if (existing && existing.updated === r.updated) return; + + const newTask = mapRecordToTask(r); + if (existing && existing.content) { + newTask.content = existing.content; + } + taskMap.set(r.id, newTask); + changed = true; + }); + + if (changed) return Array.from(taskMap.values()); + return currentTasks; + }); + } catch (err: any) { + if (!err.isAbort) { + console.warn("Context poll failed:", err); + } + } + }, 5000); // 5 seconds + } +}; + +createEffect(() => { + // Re-run whenever ctx changes + currentTaskContext(); + startContextPolling(); +}); + export interface FilterTemplate { id: string; name: string;