init: arcadia-admin — admin webapp for arcadia-core, cloned from vibespace
Initial commit. Spun up via the docs/STARTER.md recipe: cp from vibespace, reset git, rename package, set brand to "Arcadia Admin" with Shield icon in app/lib/identity.ts. Inherits the full Crema sibling-lib wiring including @crema/arcadia-client (typed HTTP + Phoenix Channels realtime against arcadia-core) and @crema/arcadia-auth-ui (login/signup/password-reset/2FA forms). The /login route already renders <LoginForm>; <ArcadiaProvider> in app/root.tsx reads VITE_ARCADIA_URL (default localhost:4000) and VITE_ARCADIA_TENANT (default "default"). CLAUDE.md and README rewritten to frame this as the admin app for arcadia-core. docs/STARTER.md removed — arcadia-admin is a leaf consumer, not a downstream starter. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
153
app/lib/agents.ts
Normal file
153
app/lib/agents.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
// Agent personas — named, role-scoped sub-system prompts.
|
||||
// Each persona stacks on top of the main systemPrompt to specialize the
|
||||
// assistant for a task. Persisted in localStorage; reactive across tabs.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type Agent = {
|
||||
id: string
|
||||
name: string
|
||||
role: string
|
||||
prompt: string
|
||||
}
|
||||
|
||||
export const DEFAULT_AGENTS: Agent[] = [
|
||||
{
|
||||
id: "generalist",
|
||||
name: "Atlas",
|
||||
role: "Generalist",
|
||||
prompt:
|
||||
"You handle anything: chat, planning, summaries, casual questions. Match the user's tone. Keep replies as long as the task deserves — terse for quick questions, detailed when explaining.",
|
||||
},
|
||||
{
|
||||
id: "coder",
|
||||
name: "Forge",
|
||||
role: "Software engineer",
|
||||
prompt:
|
||||
"You are a senior software engineer. Write idiomatic, well-typed code. Prefer concrete examples over abstract advice. When asked to fix a bug, identify root cause before patching. Use markdown code blocks with language tags. Mention edge cases briefly when relevant.",
|
||||
},
|
||||
{
|
||||
id: "writer",
|
||||
name: "Inkwell",
|
||||
role: "Writer",
|
||||
prompt:
|
||||
"You are a prose writer. Produce vivid, well-paced text — short stories, copy, emails, essays. Vary sentence length. Show, don't tell. When the user asks for a draft, deliver the draft, not a description of it.",
|
||||
},
|
||||
{
|
||||
id: "researcher",
|
||||
name: "Pilot",
|
||||
role: "Researcher",
|
||||
prompt:
|
||||
"You are a careful researcher. Structure answers as: claim → evidence → caveat. Distinguish what is well-established from what is uncertain. Refuse to fabricate citations — if you don't know, say so.",
|
||||
},
|
||||
{
|
||||
id: "ui-driver",
|
||||
name: "Cursor",
|
||||
role: "UI Operator",
|
||||
prompt:
|
||||
"You specialize in driving this app's UI on the user's behalf. Prefer doing over explaining. When the user asks for an action, emit an action block immediately. When they ask a question about the app, answer concisely and offer to do it.",
|
||||
},
|
||||
]
|
||||
|
||||
const STORAGE_KEY = "crema.agents"
|
||||
const ACTIVE_KEY = "crema.assistant.activeAgent"
|
||||
const CHANGE_EVENT = "crema:agents-change"
|
||||
|
||||
function isAgent(v: unknown): v is Agent {
|
||||
return (
|
||||
!!v &&
|
||||
typeof v === "object" &&
|
||||
typeof (v as Agent).id === "string" &&
|
||||
typeof (v as Agent).name === "string" &&
|
||||
typeof (v as Agent).role === "string" &&
|
||||
typeof (v as Agent).prompt === "string"
|
||||
)
|
||||
}
|
||||
|
||||
function readFromStorage(): Agent[] {
|
||||
if (typeof window === "undefined") return DEFAULT_AGENTS
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return DEFAULT_AGENTS
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return DEFAULT_AGENTS
|
||||
const cleaned = parsed.filter(isAgent)
|
||||
return cleaned.length > 0 ? cleaned : DEFAULT_AGENTS
|
||||
} catch {
|
||||
return DEFAULT_AGENTS
|
||||
}
|
||||
}
|
||||
|
||||
export function loadAgents(): Agent[] {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function saveAgents(next: Agent[]) {
|
||||
if (typeof window === "undefined") return
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
|
||||
export function resetAgents() {
|
||||
saveAgents(DEFAULT_AGENTS)
|
||||
}
|
||||
|
||||
let cached: Agent[] | null = null
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY || e.key === ACTIVE_KEY) onChange()
|
||||
})
|
||||
return () => {
|
||||
window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
}
|
||||
|
||||
function getSnapshot(): Agent[] {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
|
||||
function getServerSnapshot(): Agent[] {
|
||||
return DEFAULT_AGENTS
|
||||
}
|
||||
|
||||
export function useAgents(): Agent[] {
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
|
||||
export function loadActiveAgentId(): string {
|
||||
if (typeof window === "undefined") return DEFAULT_AGENTS[0].id
|
||||
try {
|
||||
return localStorage.getItem(ACTIVE_KEY) ?? DEFAULT_AGENTS[0].id
|
||||
} catch {
|
||||
return DEFAULT_AGENTS[0].id
|
||||
}
|
||||
}
|
||||
|
||||
export function saveActiveAgentId(id: string) {
|
||||
if (typeof window === "undefined") return
|
||||
localStorage.setItem(ACTIVE_KEY, id)
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
|
||||
export function composeSystemPrompt(
|
||||
base: string,
|
||||
agent: Agent | undefined,
|
||||
): string {
|
||||
if (!agent) return base
|
||||
return `${base}\n\nActive persona: ${agent.name} — ${agent.role}\n${agent.prompt}`
|
||||
}
|
||||
|
||||
export function newAgentId(): string {
|
||||
return `agent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
||||
}
|
||||
83
app/lib/api.ts
Normal file
83
app/lib/api.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
// API — typed fetch wrapper. Auto-injects the session token, throws on
|
||||
// non-2xx with a parsed error, and supports AbortSignal for cancellation.
|
||||
//
|
||||
// Replace `apiBaseURL` with your backend root. The Resources route shows the
|
||||
// typical usage pattern.
|
||||
|
||||
import { loadSession, signOut } from "~/lib/session"
|
||||
|
||||
export const apiBaseURL = "/api"
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number
|
||||
body: unknown
|
||||
constructor(message: string, status: number, body: unknown) {
|
||||
super(message)
|
||||
this.name = "ApiError"
|
||||
this.status = status
|
||||
this.body = body
|
||||
}
|
||||
}
|
||||
|
||||
export type ApiInit = Omit<RequestInit, "body" | "method"> & {
|
||||
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
|
||||
body?: unknown
|
||||
}
|
||||
|
||||
export async function apiFetch<T = unknown>(
|
||||
path: string,
|
||||
init: ApiInit = {},
|
||||
): Promise<T> {
|
||||
const session = loadSession()
|
||||
const headers = new Headers(init.headers)
|
||||
if (session?.token) headers.set("Authorization", `Bearer ${session.token}`)
|
||||
if (init.body !== undefined && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
const url = path.startsWith("http") ? path : `${apiBaseURL}${path}`
|
||||
const res = await fetch(url, {
|
||||
...init,
|
||||
method: init.method ?? "GET",
|
||||
headers,
|
||||
body:
|
||||
init.body === undefined
|
||||
? undefined
|
||||
: typeof init.body === "string"
|
||||
? init.body
|
||||
: JSON.stringify(init.body),
|
||||
})
|
||||
|
||||
if (res.status === 401) {
|
||||
// Token rejected — clear session so the shell bounces to /login.
|
||||
signOut()
|
||||
}
|
||||
|
||||
const ct = res.headers.get("Content-Type") ?? ""
|
||||
const parsed = ct.includes("application/json")
|
||||
? await res.json().catch(() => null)
|
||||
: await res.text().catch(() => null)
|
||||
|
||||
if (!res.ok) {
|
||||
const message =
|
||||
(parsed && typeof parsed === "object" && "message" in parsed
|
||||
? String((parsed as { message: unknown }).message)
|
||||
: null) ?? `${res.status} ${res.statusText}`
|
||||
throw new ApiError(message, res.status, parsed)
|
||||
}
|
||||
return parsed as T
|
||||
}
|
||||
|
||||
/** Convenience helpers. */
|
||||
export const api = {
|
||||
get: <T = unknown>(path: string, init?: ApiInit) =>
|
||||
apiFetch<T>(path, { ...init, method: "GET" }),
|
||||
post: <T = unknown>(path: string, body?: unknown, init?: ApiInit) =>
|
||||
apiFetch<T>(path, { ...init, method: "POST", body }),
|
||||
put: <T = unknown>(path: string, body?: unknown, init?: ApiInit) =>
|
||||
apiFetch<T>(path, { ...init, method: "PUT", body }),
|
||||
patch: <T = unknown>(path: string, body?: unknown, init?: ApiInit) =>
|
||||
apiFetch<T>(path, { ...init, method: "PATCH", body }),
|
||||
del: <T = unknown>(path: string, init?: ApiInit) =>
|
||||
apiFetch<T>(path, { ...init, method: "DELETE" }),
|
||||
}
|
||||
40
app/lib/identity.ts
Normal file
40
app/lib/identity.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// Project identity — brand and user. Hooks return module-singleton defaults
|
||||
// so routes don't have to thread props. Swap the constants below for your
|
||||
// project's brand; swap useUser() for a real session hook when you wire auth.
|
||||
|
||||
import { Shield, type LucideIcon } from "lucide-react"
|
||||
|
||||
export type Brand = {
|
||||
name: string
|
||||
icon: LucideIcon
|
||||
}
|
||||
|
||||
export type User = {
|
||||
name: string
|
||||
email: string
|
||||
initials: string
|
||||
}
|
||||
|
||||
const brand: Brand = {
|
||||
name: "Arcadia Admin",
|
||||
icon: Shield,
|
||||
}
|
||||
|
||||
const currentUser: User = {
|
||||
name: "Signed-in user",
|
||||
email: "user@example.com",
|
||||
initials: "U",
|
||||
}
|
||||
|
||||
export function useBrand(): Brand {
|
||||
return brand
|
||||
}
|
||||
|
||||
export function useUser(): User {
|
||||
return currentUser
|
||||
}
|
||||
|
||||
/** Convenience for non-React modules (page meta, scripts, etc). */
|
||||
export function getBrand(): Brand {
|
||||
return brand
|
||||
}
|
||||
125
app/lib/library.ts
Normal file
125
app/lib/library.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
// Library — saved artifacts. Today: conversation snapshots.
|
||||
// Tomorrow: snippets, prompts, generated documents.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type LibraryItem = {
|
||||
id: string
|
||||
kind: "conversation" | "snippet"
|
||||
title: string
|
||||
// Free-form body. For "conversation": markdown transcript. For "snippet": text.
|
||||
content: string
|
||||
tags: string[]
|
||||
// Optional metadata.
|
||||
agentName?: string
|
||||
agentRole?: string
|
||||
threadId?: string
|
||||
messageCount?: number
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.library"
|
||||
const CHANGE_EVENT = "crema:library-change"
|
||||
const MAX_BYTES = 1_500_000
|
||||
|
||||
export function newLibraryId(): string {
|
||||
return `lib-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
||||
}
|
||||
|
||||
function isLibraryItem(v: unknown): v is LibraryItem {
|
||||
if (!v || typeof v !== "object") return false
|
||||
const x = v as LibraryItem
|
||||
return (
|
||||
typeof x.id === "string" &&
|
||||
(x.kind === "conversation" || x.kind === "snippet") &&
|
||||
typeof x.title === "string" &&
|
||||
typeof x.content === "string" &&
|
||||
Array.isArray(x.tags) &&
|
||||
typeof x.createdAt === "number"
|
||||
)
|
||||
}
|
||||
|
||||
function readFromStorage(): LibraryItem[] {
|
||||
if (typeof window === "undefined") return []
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.filter(isLibraryItem)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeToStorage(items: LibraryItem[]) {
|
||||
if (typeof window === "undefined") return
|
||||
let trimmed = items
|
||||
let serialized = JSON.stringify(trimmed)
|
||||
while (serialized.length > MAX_BYTES && trimmed.length > 1) {
|
||||
trimmed = trimmed.slice(0, -1)
|
||||
serialized = JSON.stringify(trimmed)
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, serialized)
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
} catch {
|
||||
/* quota — bail */
|
||||
}
|
||||
}
|
||||
|
||||
export function loadLibrary(): LibraryItem[] {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function addLibraryItem(item: Omit<LibraryItem, "id" | "createdAt">): LibraryItem {
|
||||
const next: LibraryItem = {
|
||||
...item,
|
||||
id: newLibraryId(),
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
const items = readFromStorage()
|
||||
writeToStorage([next, ...items])
|
||||
return next
|
||||
}
|
||||
|
||||
export function deleteLibraryItem(id: string) {
|
||||
const items = readFromStorage().filter((x) => x.id !== id)
|
||||
writeToStorage(items)
|
||||
}
|
||||
|
||||
export function updateLibraryItem(id: string, patch: Partial<LibraryItem>) {
|
||||
const items = readFromStorage().map((x) =>
|
||||
x.id === id ? { ...x, ...patch } : x,
|
||||
)
|
||||
writeToStorage(items)
|
||||
}
|
||||
|
||||
let cached: LibraryItem[] | null = null
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY) onChange()
|
||||
})
|
||||
return () => window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
function getSnapshot(): LibraryItem[] {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
function getServerSnapshot(): LibraryItem[] {
|
||||
return []
|
||||
}
|
||||
|
||||
export function useLibrary(): LibraryItem[] {
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
99
app/lib/llm-settings.ts
Normal file
99
app/lib/llm-settings.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Persisted LLM settings — base URL, context budget, response cap.
|
||||
// Reactive across tabs (storage event) and within the same tab (custom event).
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type LLMSettings = {
|
||||
baseURL: string
|
||||
contextTokens: number
|
||||
responseBudget: number
|
||||
systemPrompt: string
|
||||
}
|
||||
|
||||
export const DEFAULT_SYSTEM_PROMPT =
|
||||
"You are a helpful general-purpose assistant embedded in an app. Handle any request the user makes — writing, brainstorming, code, analysis, casual chat — at the length the task deserves. Use markdown when it helps. You can also drive the UI when the user toggles UI Control on."
|
||||
|
||||
export const DEFAULT_SETTINGS: LLMSettings = {
|
||||
baseURL: "http://localhost:1234/v1",
|
||||
contextTokens: 9000,
|
||||
responseBudget: 512,
|
||||
systemPrompt: DEFAULT_SYSTEM_PROMPT,
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.llm.settings"
|
||||
const CHANGE_EVENT = "comfy:llm-settings-change"
|
||||
|
||||
function readFromStorage(): LLMSettings {
|
||||
if (typeof window === "undefined") return DEFAULT_SETTINGS
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return DEFAULT_SETTINGS
|
||||
const parsed = JSON.parse(raw) as Partial<LLMSettings>
|
||||
return {
|
||||
baseURL: typeof parsed.baseURL === "string" ? parsed.baseURL : DEFAULT_SETTINGS.baseURL,
|
||||
contextTokens:
|
||||
Number.isFinite(parsed.contextTokens) && (parsed.contextTokens as number) > 0
|
||||
? (parsed.contextTokens as number)
|
||||
: DEFAULT_SETTINGS.contextTokens,
|
||||
responseBudget:
|
||||
Number.isFinite(parsed.responseBudget) && (parsed.responseBudget as number) > 0
|
||||
? (parsed.responseBudget as number)
|
||||
: DEFAULT_SETTINGS.responseBudget,
|
||||
systemPrompt:
|
||||
typeof parsed.systemPrompt === "string" && parsed.systemPrompt.trim().length > 0
|
||||
? parsed.systemPrompt
|
||||
: DEFAULT_SETTINGS.systemPrompt,
|
||||
}
|
||||
} catch {
|
||||
return DEFAULT_SETTINGS
|
||||
}
|
||||
}
|
||||
|
||||
export function loadLLMSettings(): LLMSettings {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function saveLLMSettings(next: LLMSettings) {
|
||||
if (typeof window === "undefined") return
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
|
||||
export function resetLLMSettings() {
|
||||
saveLLMSettings(DEFAULT_SETTINGS)
|
||||
}
|
||||
|
||||
let cached: LLMSettings | null = null
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY) onChange()
|
||||
})
|
||||
return () => {
|
||||
window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
}
|
||||
|
||||
function getSnapshot(): LLMSettings {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
|
||||
function getServerSnapshot(): LLMSettings {
|
||||
return DEFAULT_SETTINGS
|
||||
}
|
||||
|
||||
export function useLLMSettings(): LLMSettings {
|
||||
// useSyncExternalStore avoids hydration flicker and stays reactive.
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
// Re-read after mount to pick up localStorage on first client render.
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
155
app/lib/notifications.ts
Normal file
155
app/lib/notifications.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
// Notifications — small reactive store for in-app toasts/inbox items.
|
||||
// Pair with @crema/notification-ui's <ToastProvider /> for transient toasts;
|
||||
// this store is for the appbar bell's persistent inbox.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type NotificationKind = "info" | "success" | "warning" | "error"
|
||||
|
||||
export type AppNotification = {
|
||||
id: string
|
||||
kind: NotificationKind
|
||||
title: string
|
||||
body?: string
|
||||
// Optional href to open when the row is clicked.
|
||||
href?: string
|
||||
createdAt: number
|
||||
readAt?: number
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.notifications"
|
||||
const CHANGE_EVENT = "crema:notifications-change"
|
||||
const MAX_ITEMS = 200
|
||||
|
||||
function newId(): string {
|
||||
return `n-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
||||
}
|
||||
|
||||
function readFromStorage(): AppNotification[] {
|
||||
if (typeof window === "undefined") return []
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.filter(
|
||||
(n): n is AppNotification =>
|
||||
n &&
|
||||
typeof n.id === "string" &&
|
||||
typeof n.title === "string" &&
|
||||
typeof n.createdAt === "number" &&
|
||||
["info", "success", "warning", "error"].includes(n.kind),
|
||||
)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeToStorage(items: AppNotification[]) {
|
||||
if (typeof window === "undefined") return
|
||||
const trimmed = items.slice(0, MAX_ITEMS)
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmed))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
} catch {
|
||||
/* quota — drop silently */
|
||||
}
|
||||
}
|
||||
|
||||
export function loadNotifications(): AppNotification[] {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function addNotification(
|
||||
n: Omit<AppNotification, "id" | "createdAt">,
|
||||
): AppNotification {
|
||||
const next: AppNotification = {
|
||||
...n,
|
||||
id: newId(),
|
||||
createdAt: Date.now(),
|
||||
}
|
||||
writeToStorage([next, ...readFromStorage()])
|
||||
return next
|
||||
}
|
||||
|
||||
export function markRead(id: string) {
|
||||
const items = readFromStorage().map((n) =>
|
||||
n.id === id ? { ...n, readAt: Date.now() } : n,
|
||||
)
|
||||
writeToStorage(items)
|
||||
}
|
||||
|
||||
export function markAllRead() {
|
||||
const now = Date.now()
|
||||
const items = readFromStorage().map((n) =>
|
||||
n.readAt ? n : { ...n, readAt: now },
|
||||
)
|
||||
writeToStorage(items)
|
||||
}
|
||||
|
||||
export function dismiss(id: string) {
|
||||
writeToStorage(readFromStorage().filter((n) => n.id !== id))
|
||||
}
|
||||
|
||||
export function dismissAll() {
|
||||
writeToStorage([])
|
||||
}
|
||||
|
||||
let cached: AppNotification[] | null = null
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY) onChange()
|
||||
})
|
||||
return () => window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
function getSnapshot(): AppNotification[] {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
function getServerSnapshot(): AppNotification[] {
|
||||
return []
|
||||
}
|
||||
|
||||
export function useNotifications(): AppNotification[] {
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
|
||||
export function unreadCount(items: AppNotification[]): number {
|
||||
return items.filter((n) => !n.readAt).length
|
||||
}
|
||||
|
||||
/** Seed a few demo notifications on first load so the bell isn't empty. */
|
||||
export function seedIfEmpty() {
|
||||
if (typeof window === "undefined") return
|
||||
if (localStorage.getItem(STORAGE_KEY)) return
|
||||
const now = Date.now()
|
||||
const seed: AppNotification[] = [
|
||||
{
|
||||
id: newId(),
|
||||
kind: "info",
|
||||
title: "Welcome",
|
||||
body: "Tag elements with data-action and the assistant can drive them.",
|
||||
href: "/assistant",
|
||||
createdAt: now - 60_000,
|
||||
},
|
||||
{
|
||||
id: newId(),
|
||||
kind: "success",
|
||||
title: "Profile saved",
|
||||
body: "Your display name and avatar are live across the app.",
|
||||
href: "/profile",
|
||||
createdAt: now - 5 * 60_000,
|
||||
},
|
||||
]
|
||||
writeToStorage(seed)
|
||||
}
|
||||
6
app/lib/page-meta.ts
Normal file
6
app/lib/page-meta.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { getBrand } from "./identity"
|
||||
|
||||
/** Build a route's <title> as `${brand.name} · ${suffix}`. */
|
||||
export function pageTitle(suffix: string): { title: string }[] {
|
||||
return [{ title: `${getBrand().name} · ${suffix}` }]
|
||||
}
|
||||
115
app/lib/profile.ts
Normal file
115
app/lib/profile.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
// User profile — name, email, title, bio, signature, default agent.
|
||||
// Persisted in localStorage; reactive across tabs.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type Profile = {
|
||||
name: string
|
||||
email: string
|
||||
title: string
|
||||
bio: string
|
||||
signature: string
|
||||
avatarUrl: string
|
||||
defaultAgentId: string
|
||||
}
|
||||
|
||||
export const DEFAULT_PROFILE: Profile = {
|
||||
name: "Signed-in user",
|
||||
email: "user@example.com",
|
||||
title: "",
|
||||
bio: "",
|
||||
signature: "",
|
||||
avatarUrl: "",
|
||||
defaultAgentId: "",
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.profile"
|
||||
const CHANGE_EVENT = "crema:profile-change"
|
||||
|
||||
function readFromStorage(): Profile {
|
||||
if (typeof window === "undefined") return DEFAULT_PROFILE
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return DEFAULT_PROFILE
|
||||
const parsed = JSON.parse(raw) as Partial<Profile>
|
||||
return {
|
||||
name:
|
||||
typeof parsed.name === "string" && parsed.name.trim().length > 0
|
||||
? parsed.name
|
||||
: DEFAULT_PROFILE.name,
|
||||
email:
|
||||
typeof parsed.email === "string" ? parsed.email : DEFAULT_PROFILE.email,
|
||||
title:
|
||||
typeof parsed.title === "string" ? parsed.title : DEFAULT_PROFILE.title,
|
||||
bio: typeof parsed.bio === "string" ? parsed.bio : DEFAULT_PROFILE.bio,
|
||||
signature:
|
||||
typeof parsed.signature === "string"
|
||||
? parsed.signature
|
||||
: DEFAULT_PROFILE.signature,
|
||||
avatarUrl:
|
||||
typeof parsed.avatarUrl === "string"
|
||||
? parsed.avatarUrl
|
||||
: DEFAULT_PROFILE.avatarUrl,
|
||||
defaultAgentId:
|
||||
typeof parsed.defaultAgentId === "string"
|
||||
? parsed.defaultAgentId
|
||||
: DEFAULT_PROFILE.defaultAgentId,
|
||||
}
|
||||
} catch {
|
||||
return DEFAULT_PROFILE
|
||||
}
|
||||
}
|
||||
|
||||
export function loadProfile(): Profile {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function saveProfile(next: Profile) {
|
||||
if (typeof window === "undefined") return
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
|
||||
export function resetProfile() {
|
||||
saveProfile(DEFAULT_PROFILE)
|
||||
}
|
||||
|
||||
export function profileInitials(name: string): string {
|
||||
const words = name.trim().split(/\s+/).filter(Boolean)
|
||||
if (words.length === 0) return "?"
|
||||
if (words.length === 1) return words[0].slice(0, 2).toUpperCase()
|
||||
return (words[0][0] + words[words.length - 1][0]).toUpperCase()
|
||||
}
|
||||
|
||||
let cached: Profile | null = null
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY) onChange()
|
||||
})
|
||||
return () => {
|
||||
window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
}
|
||||
|
||||
function getSnapshot(): Profile {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
|
||||
function getServerSnapshot(): Profile {
|
||||
return DEFAULT_PROFILE
|
||||
}
|
||||
|
||||
export function useProfile(): Profile {
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
32
app/lib/resources.test.ts
Normal file
32
app/lib/resources.test.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it, beforeEach } from "vitest"
|
||||
|
||||
import {
|
||||
createResource,
|
||||
deleteResource,
|
||||
listResources,
|
||||
updateResource,
|
||||
} from "./resources"
|
||||
|
||||
describe("resources", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
it("creates, updates, and deletes", () => {
|
||||
expect(listResources()).toEqual([])
|
||||
const r = createResource({ name: "Test", owner: "Atlas" })
|
||||
expect(r.status).toBe("active")
|
||||
expect(listResources()).toHaveLength(1)
|
||||
|
||||
const updated = updateResource(r.id, { status: "paused" })
|
||||
expect(updated?.status).toBe("paused")
|
||||
expect(updated?.updatedAt).toBeGreaterThanOrEqual(r.updatedAt)
|
||||
|
||||
deleteResource(r.id)
|
||||
expect(listResources()).toEqual([])
|
||||
})
|
||||
|
||||
it("ignores updates for unknown ids", () => {
|
||||
expect(updateResource("missing", { name: "x" })).toBeNull()
|
||||
})
|
||||
})
|
||||
157
app/lib/resources.ts
Normal file
157
app/lib/resources.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
// Resource store — example domain entity.
|
||||
// Backed by localStorage today, but written so each call is a single function
|
||||
// you can swap with `api.get/post/put/del` once you have a real backend.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type Resource = {
|
||||
id: string
|
||||
name: string
|
||||
status: "active" | "paused" | "archived"
|
||||
owner: string
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.resources"
|
||||
const CHANGE_EVENT = "crema:resources-change"
|
||||
|
||||
function newId() {
|
||||
return `r-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
||||
}
|
||||
|
||||
function readFromStorage(): Resource[] {
|
||||
if (typeof window === "undefined") return []
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.filter(
|
||||
(r): r is Resource =>
|
||||
r &&
|
||||
typeof r.id === "string" &&
|
||||
typeof r.name === "string" &&
|
||||
["active", "paused", "archived"].includes(r.status) &&
|
||||
typeof r.owner === "string" &&
|
||||
typeof r.createdAt === "number" &&
|
||||
typeof r.updatedAt === "number",
|
||||
)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function write(items: Resource[]) {
|
||||
if (typeof window === "undefined") return
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
} catch {
|
||||
/* quota */
|
||||
}
|
||||
}
|
||||
|
||||
// CRUD — these mirror what `api.get/post/put/del` would look like.
|
||||
export function listResources(): Resource[] {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function createResource(input: {
|
||||
name: string
|
||||
owner: string
|
||||
status?: Resource["status"]
|
||||
}): Resource {
|
||||
const now = Date.now()
|
||||
const r: Resource = {
|
||||
id: newId(),
|
||||
name: input.name,
|
||||
owner: input.owner,
|
||||
status: input.status ?? "active",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
write([r, ...readFromStorage()])
|
||||
return r
|
||||
}
|
||||
|
||||
export function updateResource(
|
||||
id: string,
|
||||
patch: Partial<Omit<Resource, "id" | "createdAt">>,
|
||||
): Resource | null {
|
||||
const items = readFromStorage()
|
||||
let updated: Resource | null = null
|
||||
const next = items.map((r) => {
|
||||
if (r.id !== id) return r
|
||||
updated = { ...r, ...patch, updatedAt: Date.now() }
|
||||
return updated
|
||||
})
|
||||
if (updated) write(next)
|
||||
return updated
|
||||
}
|
||||
|
||||
export function deleteResource(id: string) {
|
||||
write(readFromStorage().filter((r) => r.id !== id))
|
||||
}
|
||||
|
||||
let cached: Resource[] | null = null
|
||||
function subscribe(cb: () => void) {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY) onChange()
|
||||
})
|
||||
return () => window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
function getSnapshot(): Resource[] {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
function getServerSnapshot(): Resource[] {
|
||||
return []
|
||||
}
|
||||
|
||||
export function useResources(): Resource[] {
|
||||
const v = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return v
|
||||
}
|
||||
|
||||
/** Seed a few rows on first load so the table isn't empty. */
|
||||
export function seedResourcesIfEmpty() {
|
||||
if (typeof window === "undefined") return
|
||||
if (localStorage.getItem(STORAGE_KEY)) return
|
||||
const now = Date.now()
|
||||
const seed: Resource[] = [
|
||||
{
|
||||
id: newId(),
|
||||
name: "Acme dashboard",
|
||||
status: "active",
|
||||
owner: "Atlas",
|
||||
createdAt: now - 86_400_000 * 3,
|
||||
updatedAt: now - 3600_000,
|
||||
},
|
||||
{
|
||||
id: newId(),
|
||||
name: "Onboarding pipeline",
|
||||
status: "paused",
|
||||
owner: "Forge",
|
||||
createdAt: now - 86_400_000 * 7,
|
||||
updatedAt: now - 86_400_000,
|
||||
},
|
||||
{
|
||||
id: newId(),
|
||||
name: "Q1 report draft",
|
||||
status: "archived",
|
||||
owner: "Inkwell",
|
||||
createdAt: now - 86_400_000 * 30,
|
||||
updatedAt: now - 86_400_000 * 14,
|
||||
},
|
||||
]
|
||||
write(seed)
|
||||
}
|
||||
31
app/lib/session.test.ts
Normal file
31
app/lib/session.test.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it, beforeEach } from "vitest"
|
||||
|
||||
import { hasSession, loadSession, signIn, signOut } from "./session"
|
||||
|
||||
describe("session", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
it("starts unauthenticated", () => {
|
||||
expect(loadSession()).toBeNull()
|
||||
expect(hasSession()).toBe(false)
|
||||
})
|
||||
|
||||
it("rejects empty credentials", async () => {
|
||||
await expect(signIn("", "")).rejects.toThrow(/required/i)
|
||||
await expect(signIn("not-an-email", "pw")).rejects.toThrow(/valid email/i)
|
||||
expect(hasSession()).toBe(false)
|
||||
})
|
||||
|
||||
it("creates a session on sign-in and clears on sign-out", async () => {
|
||||
const session = await signIn("alice@example.com", "hunter2")
|
||||
expect(session.email).toBe("alice@example.com")
|
||||
expect(session.token).toMatch(/^dev-/)
|
||||
expect(hasSession()).toBe(true)
|
||||
|
||||
signOut()
|
||||
expect(loadSession()).toBeNull()
|
||||
expect(hasSession()).toBe(false)
|
||||
})
|
||||
})
|
||||
160
app/lib/session.ts
Normal file
160
app/lib/session.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
// Session — minimal auth scaffold backed by localStorage.
|
||||
// Swap loadSession/signIn/signOut for real calls (cookies + server) when you
|
||||
// wire a backend. The shape here matches what AppShell + useUser expect.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
import { profileInitials } from "~/lib/profile"
|
||||
|
||||
export type Session = {
|
||||
userId: string
|
||||
name: string
|
||||
email: string
|
||||
token: string
|
||||
// Issued at, ms since epoch.
|
||||
issuedAt: number
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.session"
|
||||
const CHANGE_EVENT = "crema:session-change"
|
||||
|
||||
function readFromStorage(): Session | null {
|
||||
if (typeof window === "undefined") return null
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return null
|
||||
const parsed = JSON.parse(raw) as Partial<Session>
|
||||
if (
|
||||
typeof parsed.userId !== "string" ||
|
||||
typeof parsed.email !== "string" ||
|
||||
typeof parsed.token !== "string"
|
||||
)
|
||||
return null
|
||||
return {
|
||||
userId: parsed.userId,
|
||||
name:
|
||||
typeof parsed.name === "string" && parsed.name.trim()
|
||||
? parsed.name
|
||||
: parsed.email,
|
||||
email: parsed.email,
|
||||
token: parsed.token,
|
||||
issuedAt:
|
||||
typeof parsed.issuedAt === "number" ? parsed.issuedAt : Date.now(),
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function loadSession(): Session | null {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock sign-in. Validates only that email + password are non-empty; returns
|
||||
* a fake session. Replace with a real fetch to your auth endpoint.
|
||||
*/
|
||||
export async function signIn(
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<Session> {
|
||||
await new Promise((r) => setTimeout(r, 250))
|
||||
if (!email.trim() || !password.trim()) {
|
||||
throw new Error("Email and password are required.")
|
||||
}
|
||||
if (!email.includes("@")) {
|
||||
throw new Error("Enter a valid email address.")
|
||||
}
|
||||
const session: Session = {
|
||||
userId: `u-${Date.now().toString(36)}`,
|
||||
name: email.split("@")[0].replace(/\W/g, " ").trim() || email,
|
||||
email,
|
||||
token: `dev-${Math.random().toString(36).slice(2, 14)}`,
|
||||
issuedAt: Date.now(),
|
||||
}
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(session))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
export function signOut() {
|
||||
if (typeof window === "undefined") return
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
sessionStorage.removeItem("arcadia_access_token")
|
||||
sessionStorage.removeItem("arcadia_refresh_token")
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
|
||||
/** Bridge: persist a Session record from a successful arcadia login.
|
||||
* Stores the JWT in sessionStorage (where ArcadiaProvider's getToken reads
|
||||
* it) and writes the user-shaped Session into localStorage so the existing
|
||||
* AppShell / useUser machinery keeps working unchanged. */
|
||||
export function persistFromArcadiaLogin(
|
||||
tokens: { access_token: string; refresh_token?: string },
|
||||
user?: { id: string; email: string; full_name?: string; first_name?: string; last_name?: string } | null,
|
||||
): Session {
|
||||
const name =
|
||||
user?.full_name ||
|
||||
[user?.first_name, user?.last_name].filter(Boolean).join(" ") ||
|
||||
user?.email ||
|
||||
"Signed-in user"
|
||||
const session: Session = {
|
||||
userId: user?.id ?? `arcadia-${Date.now().toString(36)}`,
|
||||
name,
|
||||
email: user?.email ?? "",
|
||||
token: tokens.access_token,
|
||||
issuedAt: Date.now(),
|
||||
}
|
||||
if (typeof window !== "undefined") {
|
||||
sessionStorage.setItem("arcadia_access_token", tokens.access_token)
|
||||
if (tokens.refresh_token) sessionStorage.setItem("arcadia_refresh_token", tokens.refresh_token)
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(session))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
/** True if a non-expired session is in storage. */
|
||||
export function hasSession(): boolean {
|
||||
return !!readFromStorage()
|
||||
}
|
||||
|
||||
let cached: Session | null = null
|
||||
let cacheValid = false
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cacheValid = false
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === STORAGE_KEY) onChange()
|
||||
})
|
||||
return () => window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
function getSnapshot(): Session | null {
|
||||
if (!cacheValid) {
|
||||
cached = readFromStorage()
|
||||
cacheValid = true
|
||||
}
|
||||
return cached
|
||||
}
|
||||
function getServerSnapshot(): Session | null {
|
||||
return null
|
||||
}
|
||||
|
||||
export function useSession(): Session | null {
|
||||
const s = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cacheValid = false
|
||||
}, [])
|
||||
return s
|
||||
}
|
||||
|
||||
export function sessionInitials(session: Session | null): string {
|
||||
if (!session) return "?"
|
||||
return profileInitials(session.name || session.email)
|
||||
}
|
||||
222
app/lib/threads.ts
Normal file
222
app/lib/threads.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
// Conversation threads — multiple named chats, each with its own history,
|
||||
// active agent, and pinned message indices. Persisted in localStorage.
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react"
|
||||
|
||||
export type ThreadMessage = {
|
||||
role: "user" | "assistant"
|
||||
content: string
|
||||
/** Persona that authored this assistant message (omitted for user msgs). */
|
||||
agentId?: string
|
||||
}
|
||||
|
||||
export type Thread = {
|
||||
id: string
|
||||
title: string
|
||||
agentId: string
|
||||
messages: ThreadMessage[]
|
||||
pinned: number[] // indices into messages[]
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
const THREADS_KEY = "crema.assistant.threads"
|
||||
const ACTIVE_KEY = "crema.assistant.activeThreadId"
|
||||
const SNAPSHOT_KEY_PREFIX = "crema.assistant.thread.snapshot."
|
||||
const CHANGE_EVENT = "crema:threads-change"
|
||||
const MAX_BYTES = 800_000
|
||||
|
||||
export function newThreadId(): string {
|
||||
return `t-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
||||
}
|
||||
|
||||
function isThread(v: unknown): v is Thread {
|
||||
if (!v || typeof v !== "object") return false
|
||||
const t = v as Thread
|
||||
return (
|
||||
typeof t.id === "string" &&
|
||||
typeof t.title === "string" &&
|
||||
typeof t.agentId === "string" &&
|
||||
Array.isArray(t.messages) &&
|
||||
Array.isArray(t.pinned) &&
|
||||
typeof t.createdAt === "number" &&
|
||||
typeof t.updatedAt === "number"
|
||||
)
|
||||
}
|
||||
|
||||
function readFromStorage(): Thread[] {
|
||||
if (typeof window === "undefined") return []
|
||||
try {
|
||||
const raw = localStorage.getItem(THREADS_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.filter(isThread)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeToStorage(threads: Thread[]) {
|
||||
if (typeof window === "undefined") return
|
||||
let serialized = JSON.stringify(threads)
|
||||
// Trim oldest threads if quota gets tight.
|
||||
let trimmed = threads
|
||||
while (serialized.length > MAX_BYTES && trimmed.length > 1) {
|
||||
trimmed = trimmed.slice(0, -1)
|
||||
serialized = JSON.stringify(trimmed)
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(THREADS_KEY, serialized)
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
} catch {
|
||||
/* quota — bail */
|
||||
}
|
||||
}
|
||||
|
||||
export function loadThreads(): Thread[] {
|
||||
return readFromStorage()
|
||||
}
|
||||
|
||||
export function saveThreads(threads: Thread[]) {
|
||||
writeToStorage(threads)
|
||||
}
|
||||
|
||||
export function loadActiveThreadId(): string | null {
|
||||
if (typeof window === "undefined") return null
|
||||
return localStorage.getItem(ACTIVE_KEY)
|
||||
}
|
||||
|
||||
export function saveActiveThreadId(id: string | null) {
|
||||
if (typeof window === "undefined") return
|
||||
if (id) localStorage.setItem(ACTIVE_KEY, id)
|
||||
else localStorage.removeItem(ACTIVE_KEY)
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
}
|
||||
|
||||
let cached: Thread[] | null = null
|
||||
|
||||
function subscribe(cb: () => void): () => void {
|
||||
const onChange = () => {
|
||||
cached = null
|
||||
cb()
|
||||
}
|
||||
window.addEventListener(CHANGE_EVENT, onChange)
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === THREADS_KEY || e.key === ACTIVE_KEY) onChange()
|
||||
})
|
||||
return () => {
|
||||
window.removeEventListener(CHANGE_EVENT, onChange)
|
||||
}
|
||||
}
|
||||
|
||||
function getSnapshot(): Thread[] {
|
||||
if (!cached) cached = readFromStorage()
|
||||
return cached
|
||||
}
|
||||
function getServerSnapshot(): Thread[] {
|
||||
return []
|
||||
}
|
||||
|
||||
export function useThreads(): Thread[] {
|
||||
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
||||
useEffect(() => {
|
||||
cached = null
|
||||
}, [])
|
||||
return value
|
||||
}
|
||||
|
||||
export function ensureThread(
|
||||
threads: Thread[],
|
||||
fallbackAgentId: string,
|
||||
): { threads: Thread[]; activeId: string } {
|
||||
const stored = loadActiveThreadId()
|
||||
if (stored && threads.some((t) => t.id === stored))
|
||||
return { threads, activeId: stored }
|
||||
if (threads.length > 0) {
|
||||
saveActiveThreadId(threads[0].id)
|
||||
return { threads, activeId: threads[0].id }
|
||||
}
|
||||
const id = newThreadId()
|
||||
const now = Date.now()
|
||||
const fresh: Thread = {
|
||||
id,
|
||||
title: "New conversation",
|
||||
agentId: fallbackAgentId,
|
||||
messages: [],
|
||||
pinned: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
saveActiveThreadId(id)
|
||||
saveThreads([fresh, ...threads])
|
||||
return { threads: [fresh, ...threads], activeId: id }
|
||||
}
|
||||
|
||||
export function updateThread(id: string, patch: Partial<Thread>) {
|
||||
const threads = readFromStorage()
|
||||
const next = threads.map((t) =>
|
||||
t.id === id ? { ...t, ...patch, updatedAt: Date.now() } : t,
|
||||
)
|
||||
writeToStorage(next)
|
||||
}
|
||||
|
||||
export function createThread(agentId: string, title = "New conversation"): Thread {
|
||||
const threads = readFromStorage()
|
||||
const id = newThreadId()
|
||||
const now = Date.now()
|
||||
const fresh: Thread = {
|
||||
id,
|
||||
title,
|
||||
agentId,
|
||||
messages: [],
|
||||
pinned: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
writeToStorage([fresh, ...threads])
|
||||
saveActiveThreadId(id)
|
||||
return fresh
|
||||
}
|
||||
|
||||
export function deleteThread(id: string) {
|
||||
const threads = readFromStorage()
|
||||
const next = threads.filter((t) => t.id !== id)
|
||||
writeToStorage(next)
|
||||
if (loadActiveThreadId() === id) {
|
||||
saveActiveThreadId(next[0]?.id ?? null)
|
||||
}
|
||||
}
|
||||
|
||||
export function snapshotThread(id: string) {
|
||||
const threads = readFromStorage()
|
||||
const t = threads.find((x) => x.id === id)
|
||||
if (!t) return
|
||||
try {
|
||||
localStorage.setItem(SNAPSHOT_KEY_PREFIX + id, JSON.stringify(t))
|
||||
} catch {
|
||||
/* quota */
|
||||
}
|
||||
}
|
||||
|
||||
export function loadThreadSnapshot(id: string): Thread | null {
|
||||
if (typeof window === "undefined") return null
|
||||
try {
|
||||
const raw = localStorage.getItem(SNAPSHOT_KEY_PREFIX + id)
|
||||
if (!raw) return null
|
||||
const parsed = JSON.parse(raw)
|
||||
return isThread(parsed) ? parsed : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function clearThreadSnapshot(id: string) {
|
||||
if (typeof window === "undefined") return
|
||||
localStorage.removeItem(SNAPSHOT_KEY_PREFIX + id)
|
||||
}
|
||||
|
||||
export function deriveTitleFromFirstMessage(text: string): string {
|
||||
const trimmed = text.trim().split(/\s+/).slice(0, 8).join(" ")
|
||||
return trimmed.length > 60 ? trimmed.slice(0, 57) + "…" : trimmed || "New conversation"
|
||||
}
|
||||
6
app/lib/utils.ts
Normal file
6
app/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
Reference in New Issue
Block a user