YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: 10000x the data-table with AI search
Louis Beaumont6fa77ab36eaf
diff --git a/pipes/data-table/bun.lockb b/pipes/data-table/bun.lockbindex a78718edd..d97721b28 100755Binary files a/pipes/data-table/bun.lockb and b/pipes/data-table/bun.lockb differdiff --git a/pipes/data-table/package.json b/pipes/data-table/package.jsonindex f49e2eef6..85a014ceb 100644--- a/pipes/data-table/package.json+++ b/pipes/data-table/package.json@@ -1,6 +1,6 @@{"name": "data-table",- "version": "0.1.3",+ "version": "0.1.4","private": true,"scripts": {"dev": "next dev --turbopack",@@ -11,7 +11,7 @@"dependencies": {"@radix-ui/react-accordion": "^1.2.2","@radix-ui/react-checkbox": "^1.1.3",- "@radix-ui/react-dialog": "^1.1.3",+ "@radix-ui/react-dialog": "^1.1.6","@radix-ui/react-dropdown-menu": "^2.1.3","@radix-ui/react-label": "^2.1.1","@radix-ui/react-popover": "^1.1.3",@@ -34,7 +34,7 @@"ai": "^4.0.18","class-variance-authority": "^0.7.1","clsx": "^2.1.1",- "cmdk": "1.0.0",+ "cmdk": "1.0.4","date-fns": "^4.1.0","framer-motion": "^11.14.4","install": "^0.13.0",@@ -50,6 +50,7 @@"react-day-picker": "8.10.1","react-dom": "^19.0.0","react-markdown": "^9.0.1",+ "react-resizable-panels": "^2.1.7","react-syntax-highlighter": "^15.6.1","remark-gfm": "^4.0.0","remark-math": "^6.0.0",diff --git a/pipes/data-table/src/app/api/settings/route.ts b/pipes/data-table/src/app/api/settings/route.tsindex e53911f12..4646b26ad 100644--- a/pipes/data-table/src/app/api/settings/route.ts+++ b/pipes/data-table/src/app/api/settings/route.ts@@ -1,24 +1,62 @@-// app/api/settings/route.tsimport { pipe } from "@screenpipe/js";import { NextResponse } from "next/server";-import { getDefaultSettings } from "@screenpipe/browser";-// Force Node.js runtime-export const runtime = "nodejs"; // Add this line+import { promises as fs } from "fs";+import path from "path";++export const runtime = "nodejs";export const dynamic = "force-dynamic";export async function GET() {- const defaultSettings = getDefaultSettings();-try {const settingsManager = pipe.settings;if (!settingsManager) {throw new Error("settingsManager not found");}- const rawSettings = await settingsManager.getAll();- return NextResponse.json(rawSettings);++ // get home dir+ const homeDir = process.env.HOME;++ // Load persisted settings if they exist+ const screenpipeDir =+ process.env.SCREENPIPE_DIR ||+ (homeDir && path.join(homeDir, ".screenpipe")) ||+ process.cwd();+ const settingsPath = path.join(+ screenpipeDir,+ "pipes",+ "obsidian",+ "pipe.json"+ );++ try {+ const settingsContent = await fs.readFile(settingsPath, "utf8");+ const persistedSettings = JSON.parse(settingsContent);++ // Merge with current settings+ const rawSettings = await settingsManager.getAll();+ return NextResponse.json({+ ...rawSettings,+ customSettings: {+ ...rawSettings.customSettings,+ ["obsidian"]: {+ ...(rawSettings.customSettings?.["obsidian"] || {}),+ ...persistedSettings,+ },+ },+ });+ } catch (err) {+ console.log("route err", err);+ // If no persisted settings, return normal settings+ const rawSettings = await settingsManager.getAll();+ console.log("route rawSettings", rawSettings);+ return NextResponse.json(rawSettings);+ }} catch (error) {console.error("failed to get settings:", error);- return NextResponse.json(defaultSettings);+ return NextResponse.json(+ { error: "failed to get settings" },+ { status: 500 }+ );}}@@ -30,18 +68,37 @@ export async function PUT(request: Request) {}const body = await request.json();- const { key, value, isPartialUpdate, reset } = body;+ const { key, value, isPartialUpdate, reset, namespace } = body;if (reset) {- if (key) {- await settingsManager.resetKey(key);+ if (namespace) {+ if (key) {+ await settingsManager.setCustomSetting(namespace, key, undefined);+ } else {+ await settingsManager.updateNamespaceSettings(namespace, {});+ }} else {- await settingsManager.reset();+ if (key) {+ await settingsManager.resetKey(key);+ } else {+ await settingsManager.reset();+ }}return NextResponse.json({ success: true });}- if (isPartialUpdate) {+ if (namespace) {+ if (isPartialUpdate) {+ const currentSettings =+ (await settingsManager.getNamespaceSettings(namespace)) || {};+ await settingsManager.updateNamespaceSettings(namespace, {+ ...currentSettings,+ ...value,+ });+ } else {+ await settingsManager.setCustomSetting(namespace, key, value);+ }+ } else if (isPartialUpdate) {const serializedSettings = JSON.parse(JSON.stringify(value));await settingsManager.update(serializedSettings);} else {diff --git a/pipes/data-table/src/app/globals.css b/pipes/data-table/src/app/globals.cssindex ff005b73a..e23e581f3 100644--- a/pipes/data-table/src/app/globals.css+++ b/pipes/data-table/src/app/globals.css@@ -70,3 +70,13 @@ body {@apply bg-background text-foreground !pointer-events-auto;}}++++[role="dialog"] {+ max-width: 896px !important;+ width: 90vw !important;+ margin: 0 auto;+ left: 50% !important;+ transform: translate(-50%, -50%) !important;+}diff --git a/pipes/data-table/src/components/page.tsx b/pipes/data-table/src/components/page.tsxindex 92493b5c5..cfd95d736 100644--- a/pipes/data-table/src/components/page.tsx+++ b/pipes/data-table/src/components/page.tsx@@ -7,6 +7,7 @@ import { VideoChunksTable } from "./video-chunks-table";import { AudioTranscriptionsTable } from "./audio-transcriptions-table";import { UiMonitoringTable } from "./ui-monitoring-table";import { pipe } from "@screenpipe/browser";+import { SearchCommand } from "./search-command";export default function DataPage() {const [currentTable, setCurrentTable] = useState("ocr_text");@@ -43,6 +44,9 @@ export default function DataPage() {/></div><div className="w-[80%] p-8">+ <div className="flex justify-end mb-4">+ <SearchCommand />+ </div><div className="w-full">{renderTable()}</div></div></div>diff --git a/pipes/data-table/src/components/search-command.tsx b/pipes/data-table/src/components/search-command.tsxnew file mode 100644index 000000000..d172a3deb--- /dev/null+++ b/pipes/data-table/src/components/search-command.tsx@@ -0,0 +1,273 @@+"use client";++import * as React from "react";+import { useState } from "react";+import { Search, Database } from "lucide-react";+import { Button } from "@/components/ui/button";+import { CommandDialog, CommandInput } from "@/components/ui/command";+import OpenAI from "openai";+import { toast } from "@/components/ui/use-toast";+import { useSettings } from "@/lib/hooks/use-settings";+import { DialogTitle } from "./ui/dialog";+import { SheetTitle } from "./ui/sheet";+import { Textarea } from "@/components/ui/textarea";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { cn } from "@/lib/utils";++export function SearchCommand() {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const [sqlQuery, setSqlQuery] = useState("");+ const [isLoading, setIsLoading] = useState(false);+ const [generatedSql, setGeneratedSql] = useState("");+ const { settings } = useSettings();+ const [results, setResults] = useState<any[]>([]);+ const [columns, setColumns] = useState<string[]>([]);+ const [error, setError] = useState<string | null>(null);+ const [isMac, setIsMac] = useState(false);++ // Add useEffect for OS detection+ React.useEffect(() => {+ setIsMac(navigator.userAgent.includes("Mac"));+ }, []);++ // Add useEffect for keyboard shortcut+ React.useEffect(() => {+ const down = (e: KeyboardEvent) => {+ if (e.key === "k" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ setOpen((open) => !open);+ }+ };+ document.addEventListener("keydown", down);+ return () => document.removeEventListener("keydown", down);+ }, []);++ const handleGenerateSql = async () => {+ if (!query.trim()) return;++ setIsLoading(true);++ try {+ const openai = new OpenAI({+ apiKey:+ settings.aiProviderType === "screenpipe-cloud"+ ? settings.user.token+ : settings.openaiApiKey,+ baseURL: settings.aiUrl,+ dangerouslyAllowBrowser: true,+ });++ const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [+ {+ role: "system",+ content: `You are an SQL expert. Generate SQLite queries based on natural language input.+ Important rules:+ - Only return the SQL query, no explanations+ - Use proper SQLite syntax+ - Use FTS tables when searching text: ocr_text_fts, audio_transcriptions_fts, ui_monitoring_fts+ - Common joins:+ - frames + ocr_text for screen content+ - audio_chunks + audio_transcriptions for voice+ - ui_monitoring for UI interactions+ - Always include proper timestamp filtering+ - Use proper escaping for text searches+ - Keep queries efficient by using indexes+ - Return results ordered by timestamp DESC+ Schema highlights:+ - Screen content: frames, ocr_text, ocr_text_fts+ - Audio: audio_chunks, audio_transcriptions, audio_transcriptions_fts+ - UI: ui_monitoring, ui_monitoring_fts+ - All tables have timestamp columns+ `,+ },+ {+ role: "user",+ content: query,+ },+ ];++ const completion = await openai.chat.completions.create({+ model: settings.aiModel,+ messages,+ temperature: 0.3, // Lower temperature for more precise SQL+ });++ const sql = completion.choices[0].message.content!;+ setGeneratedSql(sql);+ setSqlQuery(sql);++ // Here you would execute the SQL query+ // const results = await pipe.executeSql(sql);+ } catch (error: any) {+ console.error("Error generating SQL:", error);+ toast({+ title: "error",+ description: "failed to generate sql query. please try again.",+ variant: "destructive",+ });+ } finally {+ setIsLoading(false);+ }+ };++ const executeQuery = async () => {+ if (!sqlQuery.trim()) return;+ setIsLoading(true);+ setError(null); // Reset error state+ setResults([]); // Clear previous results++ try {+ const response = await fetch("http://localhost:3030/raw_sql", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ query: sqlQuery,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(+ errorData.message || `query failed: ${response.statusText}`+ );+ }++ const data = await response.json();+ setResults(data);+ if (data.length > 0) {+ setColumns(Object.keys(data[0]));+ } else {+ setColumns([]);+ }+ } catch (error: any) {+ console.error("error executing query:", error);+ setError(error.message || "failed to execute query");+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <>+ <Button+ variant="outline"+ className="w-64 justify-between text-sm text-muted-foreground"+ onClick={() => setOpen(true)}+ >+ <div className="flex items-center gap-2">+ <Database className="h-4 w-4" />+ <span>search with sql...</span>+ </div>+ <kbd className="pointer-events-none hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">+ <span className="text-xs">{isMac ? "⌘" : "ctrl"}</span>K+ </kbd>+ </Button>++ <CommandDialog open={open} onOpenChange={setOpen}>+ <SheetTitle></SheetTitle>+ <CommandInput+ placeholder="describe what data you want to query..."+ value={query}+ onValueChange={setQuery}+ onKeyDown={(e) => {+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ handleGenerateSql();+ }+ }}+ />+ <div className="px-4 pb-4">+ <div className="mt-4 space-y-4">+ <div className="flex justify-between items-center">+ <Button+ onClick={handleGenerateSql}+ disabled={isLoading}+ className="w-full"+ >+ {isLoading ? (+ <span>generating...</span>+ ) : (+ <span className="flex items-center gap-2">+ generate sql+ <kbd className="pointer-events-none hidden h-5 select-none items-center gap-1 rounded border px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">+ <span className="text-xs">{isMac ? "⌘" : "ctrl"}</span>+ enter+ </kbd>+ </span>+ )}+ </Button>+ </div>++ <div className="space-y-2">+ <label className="text-sm text-muted-foreground">sql query</label>+ <Textarea+ placeholder="write or edit sql query..."+ value={sqlQuery}+ onChange={(e) => setSqlQuery(e.target.value)}+ className={cn(+ "min-h-[100px] resize-none font-mono",+ error && "border-red-500"+ )}+ />+ {error && (+ <div className="text-sm text-red-500 font-mono">{error}</div>+ )}+ </div>++ <Button+ className="w-full"+ variant="secondary"+ onClick={executeQuery}+ disabled={isLoading}+ >+ {isLoading ? "executing..." : "execute sql"}+ </Button>++ {results.length === 0 && !error && !isLoading && sqlQuery && (+ <div className="text-center py-8 text-muted-foreground">+ no results found for this query+ </div>+ )}++ {results.length > 0 && (+ <div className="rounded-md border mt-4 max-h-[400px] overflow-auto">+ <Table>+ <TableHeader>+ <TableRow>+ {columns.map((column) => (+ <TableHead key={column}>{column}</TableHead>+ ))}+ </TableRow>+ </TableHeader>+ <TableBody>+ {results.map((row, i) => (+ <TableRow key={i}>+ {columns.map((column) => (+ <TableCell key={column}>+ <div className="max-w-[300px] truncate">+ {row[column]?.toString() || "N/A"}+ </div>+ </TableCell>+ ))}+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ )}+ </div>+ </div>+ </CommandDialog>+ </>+ );+}diff --git a/pipes/data-table/src/components/ui/resizable.tsx b/pipes/data-table/src/components/ui/resizable.tsxnew file mode 100644index 000000000..f4bc5586b--- /dev/null+++ b/pipes/data-table/src/components/ui/resizable.tsx@@ -0,0 +1,45 @@+"use client"++import { GripVertical } from "lucide-react"+import * as ResizablePrimitive from "react-resizable-panels"++import { cn } from "@/lib/utils"++const ResizablePanelGroup = ({+ className,+ ...props+}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (+ <ResizablePrimitive.PanelGroup+ className={cn(+ "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",+ className+ )}+ {...props}+ />+)++const ResizablePanel = ResizablePrimitive.Panel++const ResizableHandle = ({+ withHandle,+ className,+ ...props+}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {+ withHandle?: boolean+}) => (+ <ResizablePrimitive.PanelResizeHandle+ className={cn(+ "relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",+ className+ )}+ {...props}+ >+ {withHandle && (+ <div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">+ <GripVertical className="h-2.5 w-2.5" />+ </div>+ )}+ </ResizablePrimitive.PanelResizeHandle>+)++export { ResizablePanelGroup, ResizablePanel, ResizableHandle }diff --git a/pipes/data-table/src/components/ui/sheet.tsx b/pipes/data-table/src/components/ui/sheet.tsxnew file mode 100644index 000000000..a37f17ba0--- /dev/null+++ b/pipes/data-table/src/components/ui/sheet.tsx@@ -0,0 +1,140 @@+"use client"++import * as React from "react"+import * as SheetPrimitive from "@radix-ui/react-dialog"+import { cva, type VariantProps } from "class-variance-authority"+import { X } from "lucide-react"++import { cn } from "@/lib/utils"++const Sheet = SheetPrimitive.Root++const SheetTrigger = SheetPrimitive.Trigger++const SheetClose = SheetPrimitive.Close++const SheetPortal = SheetPrimitive.Portal++const SheetOverlay = React.forwardRef<+ React.ElementRef<typeof SheetPrimitive.Overlay>,+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>+>(({ className, ...props }, ref) => (+ <SheetPrimitive.Overlay+ className={cn(+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",+ className+ )}+ {...props}+ ref={ref}+ />+))+SheetOverlay.displayName = SheetPrimitive.Overlay.displayName++const sheetVariants = cva(+ "fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",+ {+ variants: {+ side: {+ top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",+ bottom:+ "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",+ left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",+ right:+ "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",+ },+ },+ defaultVariants: {+ side: "right",+ },+ }+)++interface SheetContentProps+ extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,+ VariantProps<typeof sheetVariants> {}++const SheetContent = React.forwardRef<+ React.ElementRef<typeof SheetPrimitive.Content>,+ SheetContentProps+>(({ side = "right", className, children, ...props }, ref) => (+ <SheetPortal>+ <SheetOverlay />+ <SheetPrimitive.Content+ ref={ref}+ className={cn(sheetVariants({ side }), className)}+ {...props}+ >+ {children}+ <SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">+ <X className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </SheetPrimitive.Close>+ </SheetPrimitive.Content>+ </SheetPortal>+))+SheetContent.displayName = SheetPrimitive.Content.displayName++const SheetHeader = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col space-y-2 text-center sm:text-left",+ className+ )}+ {...props}+ />+)+SheetHeader.displayName = "SheetHeader"++const SheetFooter = ({+ className,+ ...props+}: React.HTMLAttributes<HTMLDivElement>) => (+ <div+ className={cn(+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",+ className+ )}+ {...props}+ />+)+SheetFooter.displayName = "SheetFooter"++const SheetTitle = React.forwardRef<+ React.ElementRef<typeof SheetPrimitive.Title>,+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>+>(({ className, ...props }, ref) => (+ <SheetPrimitive.Title+ ref={ref}+ className={cn("text-lg font-semibold text-foreground", className)}+ {...props}+ />+))+SheetTitle.displayName = SheetPrimitive.Title.displayName++const SheetDescription = React.forwardRef<+ React.ElementRef<typeof SheetPrimitive.Description>,+ React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>+>(({ className, ...props }, ref) => (+ <SheetPrimitive.Description+ ref={ref}+ className={cn("text-sm text-muted-foreground", className)}+ {...props}+ />+))+SheetDescription.displayName = SheetPrimitive.Description.displayName++export {+ Sheet,+ SheetPortal,+ SheetOverlay,+ SheetTrigger,+ SheetClose,+ SheetContent,+ SheetHeader,+ SheetFooter,+ SheetTitle,+ SheetDescription,+}diff --git a/pipes/data-table/src/components/ui/textarea.tsx b/pipes/data-table/src/components/ui/textarea.tsxnew file mode 100644index 000000000..4d858bb6b--- /dev/null+++ b/pipes/data-table/src/components/ui/textarea.tsx@@ -0,0 +1,22 @@+import * as React from "react"++import { cn } from "@/lib/utils"++const Textarea = React.forwardRef<+ HTMLTextAreaElement,+ React.ComponentProps<"textarea">+>(({ className, ...props }, ref) => {+ return (+ <textarea+ className={cn(+ "flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",+ className+ )}+ ref={ref}+ {...props}+ />+ )+})+Textarea.displayName = "Textarea"++export { Textarea }diff --git a/pipes/data-table/src/lib/hooks/use-settings.tsx b/pipes/data-table/src/lib/hooks/use-settings.tsxindex 1e9a327b9..19937b456 100644--- a/pipes/data-table/src/lib/hooks/use-settings.tsx+++ b/pipes/data-table/src/lib/hooks/use-settings.tsx@@ -6,18 +6,51 @@ import { getDefaultSettings, type Settings } from "@screenpipe/browser";export function useSettings() {const defaultSettings = getDefaultSettings();- const [settings, setSettings] = useState<Settings>(defaultSettings);- const [loading, setLoading] = useState(false);+ defaultSettings.customSettings = {+ ...(defaultSettings.customSettings || {}),+ obsidian: {+ prompt: `yo, you're my personal data detective! 🕵️♂️++rules for the investigation:+- extract names of people i interact with and what we discussed, when i encounter a person, make sure to extract their name like this [[John Doe]] so it's linked in my notes+- identify recurring topics/themes in my convos, use tags or [[Link them]] to my notes+- spot any promises or commitments made (by me or others)+- catch interesting ideas or insights dropped in casual chat+- note emotional vibes and energy levels in conversations+- highlight potential opportunities or connections+- track project progress and blockers mentioned++style rules:+- always put people's names in double square brackets, eg: [[John Doe]] to link to their notes, same for companies, eg: [[Google]], or projects, eg: [[Project X]]+- keep it real and conversational+- use bullet points for clarity+- include relevant timestamps+- group related info together+- max 4 lines per insight+- no corporate speak, keep it human+- for tags use hyphen between words, no spaces, eg: #my-tag not #my tag nor #myTag nor #my_tag++remember: you're analyzing screen ocr text & audio, etc. from my computer, so focus on actual interactions and content!+you'll get chunks of 5 mins roughly of data screen & audio recordings and have to write logs.+this data will be used later for analysis, it must contains valuable insights on what i am doing.+if you do your job well, i'll give you a 🍺 and $1m`,+ },+ };++ const [settings, setSettings] = useState<Settings | null>(null);+ const [loading, setLoading] = useState(true);const [error, setError] = useState<Error | null>(null);useEffect(() => {const loadSettings = async () => {- setLoading(true);+ if (!loading) setLoading(true);try {const response = await fetch("/api/settings");const data = await response.json();setSettings({ ...defaultSettings, ...data });} catch (err) {+ console.error("failed to load settings:", err);+ setSettings(defaultSettings);setError(err as Error);} finally {setLoading(false);@@ -32,7 +65,7 @@ export function useSettings() {window.addEventListener("focus", onFocus);// Optional: periodic refresh every 30s- const interval = setInterval(loadSettings, 30000);+ const interval = setInterval(loadSettings, 2000);return () => {window.removeEventListener("focus", onFocus);@@ -42,44 +75,128 @@ export function useSettings() {const updateSetting = async <T extends keyof Settings>(key: T,- value: Settings[T]+ value: Settings[T],+ namespace?: string) => {+ if (!settings) return;try {await fetch("/api/settings", {method: "PUT",- body: JSON.stringify({ key, value }),+ body: JSON.stringify({ key, value, namespace }),});- setSettings((prev) => ({ ...prev, [key]: value }));++ if (namespace) {+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {+ ...(prev.customSettings?.[namespace] || {}),+ [key]: value,+ },+ },+ };+ });+ } else {+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return { ...prev, [key]: value };+ });+ }} catch (err) {setError(err as Error);}};- const updateSettings = async (newSettings: Partial<Settings>) => {+ const updateSettings = async (+ newSettings: Partial<Settings>,+ namespace?: string+ ) => {+ if (!settings) return;try {await fetch("/api/settings", {method: "PUT",- body: JSON.stringify({ value: newSettings, isPartialUpdate: true }),+ body: JSON.stringify({+ value: newSettings,+ isPartialUpdate: true,+ namespace,+ }),});- setSettings((prev) => ({ ...prev, ...newSettings }));++ if (namespace) {+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {+ ...(prev.customSettings?.[namespace] || {}),+ ...newSettings,+ },+ },+ };+ });+ } else {+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return { ...prev, ...newSettings };+ });+ }} catch (err) {setError(err as Error);}};- const resetSettings = async (settingKey?: keyof Settings) => {+ const resetSettings = async (+ settingKey?: keyof Settings,+ namespace?: string+ ) => {+ if (!settings) return;try {await fetch("/api/settings", {method: "PUT",- body: JSON.stringify({ reset: true, key: settingKey }),+ body: JSON.stringify({ reset: true, key: settingKey, namespace }),});- if (settingKey) {- setSettings((prev) => ({- ...prev,- [settingKey]: defaultSettings[settingKey],- }));++ if (namespace) {+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ if (settingKey) {+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {+ ...(prev.customSettings?.[namespace] || {}),+ [settingKey]: undefined,+ },+ },+ };+ } else {+ return {+ ...prev,+ customSettings: {+ ...prev.customSettings,+ [namespace]: {},+ },+ };+ }+ });} else {- setSettings(defaultSettings);+ if (settingKey) {+ setSettings((prev) => {+ if (!prev) return defaultSettings;+ return {+ ...prev,+ [settingKey]: defaultSettings[settingKey],+ };+ });+ } else {+ setSettings(defaultSettings);+ }}} catch (err) {setError(err as Error);@@ -87,7 +204,7 @@ export function useSettings() {};return {- settings,+ settings: settings || defaultSettings,loading,error,updateSetting,