mirror of
https://github.com/earendil-works/pi.git
synced 2026-06-18 15:54:04 +08:00
bbbc232c7c
- Replace fragmented storage backends with single IndexedDBStorageBackend - Create multi-store StorageBackend interface (storeName parameter) - Remove old backends: IndexedDBBackend, LocalStorageBackend, SessionIndexedDBBackend, WebExtensionStorageBackend - Remove old repositories: ProviderKeysRepository, SessionRepository, SettingsRepository - Simplify AppStorage to directly expose storage methods (getSetting/setSetting, getProviderKey/setProviderKey) - Create SessionsRepository for session-specific operations - Update all consumers to use new simplified API - Update example app to use new storage architecture - Benefits: 10GB+ quota (vs 10MB chrome.storage), single database, consistent API
389 lines
11 KiB
TypeScript
389 lines
11 KiB
TypeScript
import { Button, icon, Input } from "@mariozechner/mini-lit";
|
|
import "@mariozechner/mini-lit/dist/ThemeToggle.js";
|
|
import { getModel } from "@mariozechner/pi-ai";
|
|
import {
|
|
Agent,
|
|
type AgentState,
|
|
ApiKeyPromptDialog,
|
|
ApiKeysTab,
|
|
type AppMessage,
|
|
AppStorage,
|
|
ChatPanel,
|
|
IndexedDBStorageBackend,
|
|
// PersistentStorageDialog, // TODO: Fix - currently broken
|
|
ProviderTransport,
|
|
ProxyTab,
|
|
SessionListDialog,
|
|
setAppStorage,
|
|
SettingsDialog,
|
|
} from "@mariozechner/pi-web-ui";
|
|
import { html, render } from "lit";
|
|
import { Bell, History, Plus, Settings } from "lucide";
|
|
import "./app.css";
|
|
import { createSystemNotification, customMessageTransformer, registerCustomMessageRenderers } from "./custom-messages.js";
|
|
|
|
// Register custom message renderers
|
|
registerCustomMessageRenderers();
|
|
|
|
const backend = new IndexedDBStorageBackend({
|
|
dbName: "pi-web-ui-example",
|
|
version: 1,
|
|
stores: [
|
|
{ name: "sessions-metadata", keyPath: "id", indices: [{ name: "lastModified", keyPath: "lastModified" }] },
|
|
{ name: "sessions-data", keyPath: "id" },
|
|
{ name: "settings" },
|
|
{ name: "provider-keys" },
|
|
],
|
|
});
|
|
const storage = new AppStorage(backend);
|
|
setAppStorage(storage);
|
|
|
|
let currentSessionId: string | undefined;
|
|
let currentTitle = "";
|
|
let isEditingTitle = false;
|
|
let agent: Agent;
|
|
let chatPanel: ChatPanel;
|
|
let agentUnsubscribe: (() => void) | undefined;
|
|
|
|
const generateTitle = (messages: AppMessage[]): string => {
|
|
const firstUserMsg = messages.find((m) => m.role === "user");
|
|
if (!firstUserMsg || firstUserMsg.role !== "user") return "";
|
|
|
|
let text = "";
|
|
const content = firstUserMsg.content;
|
|
|
|
if (typeof content === "string") {
|
|
text = content;
|
|
} else {
|
|
const textBlocks = content.filter((c: any) => c.type === "text");
|
|
text = textBlocks.map((c: any) => c.text || "").join(" ");
|
|
}
|
|
|
|
text = text.trim();
|
|
if (!text) return "";
|
|
|
|
const sentenceEnd = text.search(/[.!?]/);
|
|
if (sentenceEnd > 0 && sentenceEnd <= 50) {
|
|
return text.substring(0, sentenceEnd + 1);
|
|
}
|
|
return text.length <= 50 ? text : text.substring(0, 47) + "...";
|
|
};
|
|
|
|
const shouldSaveSession = (messages: AppMessage[]): boolean => {
|
|
const hasUserMsg = messages.some((m: any) => m.role === "user");
|
|
const hasAssistantMsg = messages.some((m: any) => m.role === "assistant");
|
|
return hasUserMsg && hasAssistantMsg;
|
|
};
|
|
|
|
const saveSession = async () => {
|
|
if (!storage.sessions || !currentSessionId || !agent || !currentTitle) return;
|
|
|
|
const state = agent.state;
|
|
if (!shouldSaveSession(state.messages)) return;
|
|
|
|
try {
|
|
// Create session data
|
|
const sessionData = {
|
|
id: currentSessionId,
|
|
title: currentTitle,
|
|
model: state.model!,
|
|
thinkingLevel: state.thinkingLevel,
|
|
messages: state.messages,
|
|
createdAt: new Date().toISOString(),
|
|
lastModified: new Date().toISOString(),
|
|
};
|
|
|
|
// Create session metadata
|
|
const metadata = {
|
|
id: currentSessionId,
|
|
title: currentTitle,
|
|
createdAt: sessionData.createdAt,
|
|
lastModified: sessionData.lastModified,
|
|
messageCount: state.messages.length,
|
|
usage: {
|
|
input: 0,
|
|
output: 0,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
cost: {
|
|
input: 0,
|
|
output: 0,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
total: 0,
|
|
},
|
|
},
|
|
modelId: state.model?.id || null,
|
|
thinkingLevel: state.thinkingLevel,
|
|
preview: generateTitle(state.messages),
|
|
};
|
|
|
|
await storage.sessions.saveSession(sessionData, metadata);
|
|
} catch (err) {
|
|
console.error("Failed to save session:", err);
|
|
}
|
|
};
|
|
|
|
const updateUrl = (sessionId: string) => {
|
|
const url = new URL(window.location.href);
|
|
url.searchParams.set("session", sessionId);
|
|
window.history.replaceState({}, "", url);
|
|
};
|
|
|
|
const createAgent = async (initialState?: Partial<AgentState>) => {
|
|
if (agentUnsubscribe) {
|
|
agentUnsubscribe();
|
|
}
|
|
|
|
const transport = new ProviderTransport();
|
|
|
|
agent = new Agent({
|
|
initialState: initialState || {
|
|
systemPrompt: `You are a helpful AI assistant with access to various tools.
|
|
|
|
Available tools:
|
|
- JavaScript REPL: Execute JavaScript code in a sandboxed browser environment (can do calculations, get time, process data, create visualizations, etc.)
|
|
- Artifacts: Create interactive HTML, SVG, Markdown, and text artifacts
|
|
|
|
Feel free to use these tools when needed to provide accurate and helpful responses.`,
|
|
model: getModel("anthropic", "claude-sonnet-4-5-20250929"),
|
|
thinkingLevel: "off",
|
|
messages: [],
|
|
tools: [],
|
|
},
|
|
transport,
|
|
// Custom transformer: convert system notifications to user messages with <system> tags
|
|
messageTransformer: customMessageTransformer,
|
|
});
|
|
|
|
agentUnsubscribe = agent.subscribe((event: any) => {
|
|
if (event.type === "state-update") {
|
|
const messages = event.state.messages;
|
|
|
|
// Generate title after first successful response
|
|
if (!currentTitle && shouldSaveSession(messages)) {
|
|
currentTitle = generateTitle(messages);
|
|
}
|
|
|
|
// Create session ID on first successful save
|
|
if (!currentSessionId && shouldSaveSession(messages)) {
|
|
currentSessionId = crypto.randomUUID();
|
|
updateUrl(currentSessionId);
|
|
}
|
|
|
|
// Auto-save
|
|
if (currentSessionId) {
|
|
saveSession();
|
|
}
|
|
|
|
renderApp();
|
|
}
|
|
});
|
|
|
|
await chatPanel.setAgent(agent);
|
|
};
|
|
|
|
const loadSession = async (sessionId: string): Promise<boolean> => {
|
|
if (!storage.sessions) return false;
|
|
|
|
const sessionData = await storage.sessions.getSession(sessionId);
|
|
if (!sessionData) {
|
|
console.error("Session not found:", sessionId);
|
|
return false;
|
|
}
|
|
|
|
currentSessionId = sessionId;
|
|
const metadata = await storage.sessions.getMetadata(sessionId);
|
|
currentTitle = metadata?.title || "";
|
|
|
|
await createAgent({
|
|
model: sessionData.model,
|
|
thinkingLevel: sessionData.thinkingLevel,
|
|
messages: sessionData.messages,
|
|
tools: [],
|
|
});
|
|
|
|
updateUrl(sessionId);
|
|
renderApp();
|
|
return true;
|
|
};
|
|
|
|
const newSession = () => {
|
|
const url = new URL(window.location.href);
|
|
url.search = "";
|
|
window.location.href = url.toString();
|
|
};
|
|
|
|
// ============================================================================
|
|
// RENDER
|
|
// ============================================================================
|
|
const renderApp = () => {
|
|
const app = document.getElementById("app");
|
|
if (!app) return;
|
|
|
|
const appHtml = html`
|
|
<div class="w-full h-screen flex flex-col bg-background text-foreground overflow-hidden">
|
|
<!-- Header -->
|
|
<div class="flex items-center justify-between border-b border-border shrink-0">
|
|
<div class="flex items-center gap-2 px-4 py-">
|
|
${Button({
|
|
variant: "ghost",
|
|
size: "sm",
|
|
children: icon(History, "sm"),
|
|
onClick: () => {
|
|
SessionListDialog.open(
|
|
async (sessionId) => {
|
|
await loadSession(sessionId);
|
|
},
|
|
(deletedSessionId) => {
|
|
// Only reload if the current session was deleted
|
|
if (deletedSessionId === currentSessionId) {
|
|
newSession();
|
|
}
|
|
},
|
|
);
|
|
},
|
|
title: "Sessions",
|
|
})}
|
|
${Button({
|
|
variant: "ghost",
|
|
size: "sm",
|
|
children: icon(Plus, "sm"),
|
|
onClick: newSession,
|
|
title: "New Session",
|
|
})}
|
|
|
|
${currentTitle
|
|
? isEditingTitle
|
|
? html`<div class="flex items-center gap-2">
|
|
${Input({
|
|
type: "text",
|
|
value: currentTitle,
|
|
className: "text-sm w-64",
|
|
onChange: async (e: Event) => {
|
|
const newTitle = (e.target as HTMLInputElement).value.trim();
|
|
if (newTitle && newTitle !== currentTitle && storage.sessions && currentSessionId) {
|
|
await storage.sessions.updateTitle(currentSessionId, newTitle);
|
|
currentTitle = newTitle;
|
|
}
|
|
isEditingTitle = false;
|
|
renderApp();
|
|
},
|
|
onKeyDown: async (e: KeyboardEvent) => {
|
|
if (e.key === "Enter") {
|
|
const newTitle = (e.target as HTMLInputElement).value.trim();
|
|
if (newTitle && newTitle !== currentTitle && storage.sessions && currentSessionId) {
|
|
await storage.sessions.updateTitle(currentSessionId, newTitle);
|
|
currentTitle = newTitle;
|
|
}
|
|
isEditingTitle = false;
|
|
renderApp();
|
|
} else if (e.key === "Escape") {
|
|
isEditingTitle = false;
|
|
renderApp();
|
|
}
|
|
},
|
|
})}
|
|
</div>`
|
|
: html`<button
|
|
class="px-2 py-1 text-sm text-foreground hover:bg-secondary rounded transition-colors"
|
|
@click=${() => {
|
|
isEditingTitle = true;
|
|
renderApp();
|
|
requestAnimationFrame(() => {
|
|
const input = app?.querySelector('input[type="text"]') as HTMLInputElement;
|
|
if (input) {
|
|
input.focus();
|
|
input.select();
|
|
}
|
|
});
|
|
}}
|
|
title="Click to edit title"
|
|
>
|
|
${currentTitle}
|
|
</button>`
|
|
: html`<span class="text-base font-semibold text-foreground">Pi Web UI Example</span>`}
|
|
</div>
|
|
<div class="flex items-center gap-1 px-2">
|
|
${Button({
|
|
variant: "ghost",
|
|
size: "sm",
|
|
children: icon(Bell, "sm"),
|
|
onClick: () => {
|
|
// Demo: Inject custom message
|
|
if (agent) {
|
|
agent.appendMessage(
|
|
createSystemNotification("This is a custom message! It appears in the UI but is never sent to the LLM."),
|
|
);
|
|
}
|
|
},
|
|
title: "Demo: Add Custom Notification",
|
|
})}
|
|
<theme-toggle></theme-toggle>
|
|
${Button({
|
|
variant: "ghost",
|
|
size: "sm",
|
|
children: icon(Settings, "sm"),
|
|
onClick: () => SettingsDialog.open([new ApiKeysTab(), new ProxyTab()]),
|
|
title: "Settings",
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Chat Panel -->
|
|
${chatPanel}
|
|
</div>
|
|
`;
|
|
|
|
render(appHtml, app);
|
|
};
|
|
|
|
// ============================================================================
|
|
// INIT
|
|
// ============================================================================
|
|
async function initApp() {
|
|
const app = document.getElementById("app");
|
|
if (!app) throw new Error("App container not found");
|
|
|
|
// Show loading
|
|
render(
|
|
html`
|
|
<div class="w-full h-screen flex items-center justify-center bg-background text-foreground">
|
|
<div class="text-muted-foreground">Loading...</div>
|
|
</div>
|
|
`,
|
|
app,
|
|
);
|
|
|
|
// TODO: Fix PersistentStorageDialog - currently broken
|
|
// Request persistent storage
|
|
// if (storage.sessions) {
|
|
// await PersistentStorageDialog.request();
|
|
// }
|
|
|
|
// Create ChatPanel
|
|
chatPanel = new ChatPanel();
|
|
chatPanel.onApiKeyRequired = async (provider: string) => {
|
|
return await ApiKeyPromptDialog.prompt(provider);
|
|
};
|
|
|
|
// Check for session in URL
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const sessionIdFromUrl = urlParams.get("session");
|
|
|
|
if (sessionIdFromUrl) {
|
|
const loaded = await loadSession(sessionIdFromUrl);
|
|
if (!loaded) {
|
|
// Session doesn't exist, redirect to new session
|
|
newSession();
|
|
return;
|
|
}
|
|
} else {
|
|
await createAgent();
|
|
}
|
|
|
|
renderApp();
|
|
}
|
|
|
|
initApp();
|