Add pi web POC

This commit is contained in:
Federico Jaramillo Martinez
2026-05-07 11:12:23 +02:00
parent c9d82667df
commit adf9087e84
17 changed files with 6618 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Pi Web POC</title>
</head>
<body>
<pi-web-poc></pi-web-poc>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+55
View File
@@ -0,0 +1,55 @@
export interface Project {
id: string;
name: string;
path: string;
createdAt: string;
}
export interface Workspace {
id: string;
projectId: string;
path: string;
label: string;
branch?: string;
isMain: boolean;
isGitWorktree: boolean;
}
export interface SessionInfo {
id: string;
path: string;
cwd: string;
name?: string;
created: string;
modified: string;
messageCount: number;
firstMessage: string;
}
async function request<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, {
...init,
headers: { "content-type": "application/json", ...init?.headers },
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.error ?? response.statusText);
}
return response.json() as Promise<T>;
}
export const api = {
projects: () => request<Project[]>("/api/projects"),
addProject: (path: string, name?: string) => request<Project>("/api/projects", { method: "POST", body: JSON.stringify({ path, name }) }),
workspaces: (projectId: string) => request<Workspace[]>(`/api/projects/${projectId}/workspaces`),
sessions: (cwd: string) => request<SessionInfo[]>(`/api/sessions?cwd=${encodeURIComponent(cwd)}`),
startSession: (cwd: string) => request<SessionInfo>("/api/sessions", { method: "POST", body: JSON.stringify({ cwd }) }),
messages: (sessionId: string) => request<any[]>(`/api/sessions/${sessionId}/messages`),
prompt: (sessionId: string, text: string) => request<{ accepted: true }>(`/api/sessions/${sessionId}/prompt`, { method: "POST", body: JSON.stringify({ text }) }),
close: (sessionId: string) => request<{ closed: true }>(`/api/sessions/${sessionId}/close`, { method: "POST" }),
};
export function sessionEvents(sessionId: string): WebSocket {
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
return new WebSocket(`${protocol}//${location.host}/api/sessions/${sessionId}/events`);
}
+224
View File
@@ -0,0 +1,224 @@
import { LitElement, css, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { api, sessionEvents, type Project, type SessionInfo, type Workspace } from "./api";
interface ChatLine {
role: "user" | "assistant" | "tool" | "system";
text: string;
}
@customElement("pi-web-poc")
class PiWebPoc extends LitElement {
@state() private projects: Project[] = [];
@state() private workspaces: Workspace[] = [];
@state() private sessions: SessionInfo[] = [];
@state() private messages: ChatLine[] = [];
@state() private selectedProject?: Project;
@state() private selectedWorkspace?: Workspace;
@state() private selectedSession?: SessionInfo;
@state() private error = "";
@state() private draft = "";
private socket?: WebSocket;
connectedCallback(): void {
super.connectedCallback();
void this.loadProjects();
}
disconnectedCallback(): void {
this.socket?.close();
super.disconnectedCallback();
}
private async loadProjects() {
this.error = "";
try {
this.projects = await api.projects();
} catch (error) {
this.error = String(error);
}
}
private async addProject() {
const path = prompt("Project folder path");
if (!path) return;
try {
const project = await api.addProject(path);
this.projects = [...this.projects.filter((p) => p.id !== project.id), project];
await this.selectProject(project);
} catch (error) {
this.error = String(error);
}
}
private async selectProject(project: Project) {
this.selectedProject = project;
this.selectedWorkspace = undefined;
this.selectedSession = undefined;
this.sessions = [];
this.messages = [];
try {
this.workspaces = await api.workspaces(project.id);
if (this.workspaces[0]) await this.selectWorkspace(this.workspaces[0]);
} catch (error) {
this.error = String(error);
}
}
private async selectWorkspace(workspace: Workspace) {
this.selectedWorkspace = workspace;
this.selectedSession = undefined;
this.messages = [];
try {
this.sessions = await api.sessions(workspace.path);
} catch (error) {
this.error = String(error);
}
}
private async startSession() {
if (!this.selectedWorkspace) return;
try {
const session = await api.startSession(this.selectedWorkspace.path);
this.sessions = [session, ...this.sessions];
await this.selectSession(session);
} catch (error) {
this.error = String(error);
}
}
private async selectSession(session: SessionInfo) {
this.selectedSession = session;
this.socket?.close();
this.messages = normalizeMessages(await api.messages(session.id));
this.socket = sessionEvents(session.id);
this.socket.onmessage = (message) => this.applyEvent(JSON.parse(message.data));
}
private applyEvent(event: any) {
if (event.type === "assistant.delta") {
const lines = [...this.messages];
const last = lines.at(-1);
if (last?.role === "assistant") last.text += event.text;
else lines.push({ role: "assistant", text: event.text });
this.messages = lines;
} else if (event.type === "tool.start") {
this.messages = [...this.messages, { role: "tool", text: `${event.toolName}` }];
} else if (event.type === "tool.end") {
this.messages = [...this.messages, { role: "tool", text: `${event.isError ? "✖" : "✓"} ${event.toolName}` }];
} else if (event.type === "session.error") {
this.messages = [...this.messages, { role: "system", text: event.message }];
}
}
private async send() {
const text = this.draft.trim();
if (!text || !this.selectedSession) return;
this.draft = "";
this.messages = [...this.messages, { role: "user", text }];
try {
await api.prompt(this.selectedSession.id, text);
} catch (error) {
this.error = String(error);
}
}
private async closeSession() {
if (!this.selectedSession) return;
await api.close(this.selectedSession.id);
this.selectedSession = undefined;
this.socket?.close();
this.messages = [];
}
render() {
return html`
<div class="shell">
<aside>
<header>
<strong>Pi Web POC</strong>
<button @click=${this.addProject}>+ Project</button>
</header>
<section>
<h2>Projects</h2>
${this.projects.map((project) => html`
<button class=${this.selectedProject?.id === project.id ? "selected" : ""} @click=${() => this.selectProject(project)}>
<span>${project.name}</span><small>${project.path}</small>
</button>
`)}
</section>
<section>
<h2>Workspaces</h2>
${this.workspaces.map((workspace) => html`
<button class=${this.selectedWorkspace?.id === workspace.id ? "selected" : ""} @click=${() => this.selectWorkspace(workspace)}>
<span>${workspace.label}${workspace.isMain ? " · main" : ""}</span><small>${workspace.path}</small>
</button>
`)}
</section>
<section>
<h2>Sessions <button ?disabled=${!this.selectedWorkspace} @click=${this.startSession}>+</button></h2>
${this.sessions.map((session) => html`
<button class=${this.selectedSession?.id === session.id ? "selected" : ""} @click=${() => this.selectSession(session)}>
<span>${session.name || session.firstMessage || session.id.slice(0, 8)}</span><small>${session.messageCount} messages</small>
</button>
`)}
</section>
</aside>
<main>
${this.error ? html`<div class="error">${this.error}</div>` : null}
${this.selectedSession ? html`
<div class="chat">
${this.messages.map((message) => html`<div class="msg ${message.role}"><b>${message.role}</b><pre>${message.text}</pre></div>`)}
</div>
<footer>
<textarea .value=${this.draft} @input=${(e: Event) => (this.draft = (e.target as HTMLTextAreaElement).value)} @keydown=${(e: KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
void this.send();
}
}} placeholder="Message pi..."></textarea>
<button @click=${this.send}>Send</button>
<button @click=${this.closeSession}>Close</button>
</footer>
` : html`<div class="empty">Select or start a session.</div>`}
</main>
</div>
`;
}
static styles = css`
:host { display: block; height: 100vh; color: #e6edf3; background: #0d1117; font: 14px system-ui, sans-serif; }
.shell { display: grid; grid-template-columns: 340px 1fr; height: 100%; }
aside { border-right: 1px solid #30363d; overflow: auto; }
header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid #30363d; }
section { padding: 10px; border-bottom: 1px solid #21262d; }
h2 { display: flex; justify-content: space-between; align-items: center; margin: 0 0 8px; color: #8b949e; font-size: 12px; text-transform: uppercase; }
button { border: 1px solid #30363d; border-radius: 8px; background: #161b22; color: #e6edf3; padding: 7px 9px; cursor: pointer; }
section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
button.selected { border-color: #58a6ff; background: #0d2847; }
button:disabled { opacity: .5; cursor: not-allowed; }
small { display: block; color: #8b949e; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
main { display: flex; flex-direction: column; min-width: 0; }
.chat { flex: 1; overflow: auto; padding: 16px; }
.msg { margin: 0 0 14px; padding: 12px; border: 1px solid #30363d; border-radius: 10px; background: #161b22; }
.msg.user { border-color: #2f81f7; }
.msg.tool { color: #d29922; }
.msg.system, .error { color: #ff7b72; }
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
footer { display: grid; grid-template-columns: 1fr auto auto; gap: 8px; padding: 12px; border-top: 1px solid #30363d; }
textarea { min-height: 54px; resize: vertical; border-radius: 8px; border: 1px solid #30363d; background: #0d1117; color: #e6edf3; padding: 8px; }
.empty { margin: auto; color: #8b949e; }
.error { padding: 10px 16px; border-bottom: 1px solid #30363d; }
`;
}
function normalizeMessages(messages: any[]): ChatLine[] {
return messages.map((message) => ({
role: message.role === "assistant" ? "assistant" : message.role === "user" ? "user" : "system",
text: typeof message.content === "string" ? message.content : JSON.stringify(message.content, null, 2),
}));
}
+91
View File
@@ -0,0 +1,91 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import Fastify from "fastify";
import fastifyStatic from "@fastify/static";
import fastifyWebsocket from "@fastify/websocket";
import { ProjectStore } from "./storage/projectStore.js";
import { ProjectService } from "./projects/projectService.js";
import { WorkspaceService } from "./workspaces/workspaceService.js";
import { SessionEventHub } from "./realtime/sessionEventHub.js";
import { PiSessionService } from "./sessions/piSessionService.js";
const app = Fastify({ logger: true });
await app.register(fastifyWebsocket);
const projects = new ProjectService(new ProjectStore());
const workspaces = new WorkspaceService();
const eventHub = new SessionEventHub();
const sessions = new PiSessionService(eventHub);
app.get("/api/projects", async () => projects.list());
app.post<{ Body: { name?: string; path: string } }>("/api/projects", async (request, reply) => {
try {
return await projects.add(request.body);
} catch (error) {
return reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
}
});
app.get<{ Params: { projectId: string } }>("/api/projects/:projectId/workspaces", async (request, reply) => {
try {
const project = await projects.requireProject(request.params.projectId);
return await workspaces.list(project);
} catch (error) {
return reply.code(404).send({ error: error instanceof Error ? error.message : String(error) });
}
});
app.get<{ Querystring: { cwd?: string } }>("/api/sessions", async (request, reply) => {
if (!request.query.cwd) return reply.code(400).send({ error: "cwd query parameter is required" });
return sessions.list(request.query.cwd);
});
app.post<{ Body: { cwd: string } }>("/api/sessions", async (request, reply) => {
try {
return await sessions.start(request.body.cwd);
} catch (error) {
return reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
}
});
app.get<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/messages", async (request, reply) => {
try {
return await sessions.messages(request.params.sessionId);
} catch (error) {
return reply.code(404).send({ error: error instanceof Error ? error.message : String(error) });
}
});
app.post<{ Params: { sessionId: string }; Body: { text: string } }>("/api/sessions/:sessionId/prompt", async (request, reply) => {
try {
await sessions.prompt(request.params.sessionId, request.body.text);
return { accepted: true };
} catch (error) {
return reply.code(400).send({ error: error instanceof Error ? error.message : String(error) });
}
});
app.post<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/abort", async (request) => {
await sessions.abort(request.params.sessionId);
return { aborted: true };
});
app.post<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/close", async (request) => {
sessions.close(request.params.sessionId);
return { closed: true };
});
app.get<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/events", { websocket: true }, (socket, request) => {
eventHub.add(request.params.sessionId, socket);
});
const clientDist = join(process.cwd(), "dist", "client");
if (existsSync(clientDist)) {
await app.register(fastifyStatic, { root: clientDist });
app.setNotFoundHandler((_request, reply) => reply.sendFile("index.html"));
}
const port = Number(process.env.PI_WEB_PORT ?? process.env.PORT ?? 3000);
const host = process.env.PI_WEB_HOST ?? "127.0.0.1";
await app.listen({ port, host });
+24
View File
@@ -0,0 +1,24 @@
import { realpath, stat } from "node:fs/promises";
import type { ProjectStore } from "../storage/projectStore.js";
import type { Project } from "../types.js";
export class ProjectService {
constructor(private readonly store: ProjectStore) {}
list(): Promise<Project[]> {
return this.store.list();
}
async add(input: { name?: string; path: string }): Promise<Project> {
const resolved = await realpath(input.path);
const s = await stat(resolved);
if (!s.isDirectory()) throw new Error("Project path must be a directory");
return this.store.add({ name: input.name, path: resolved });
}
async requireProject(id: string): Promise<Project> {
const project = await this.store.get(id);
if (!project) throw new Error("Project not found");
return project;
}
}
+22
View File
@@ -0,0 +1,22 @@
import type { WebSocket } from "ws";
export class SessionEventHub {
private readonly socketsBySession = new Map<string, Set<WebSocket>>();
add(sessionId: string, socket: WebSocket): void {
let sockets = this.socketsBySession.get(sessionId);
if (!sockets) {
sockets = new Set();
this.socketsBySession.set(sessionId, sockets);
}
sockets.add(socket);
socket.on("close", () => sockets?.delete(socket));
}
publish(sessionId: string, event: unknown): void {
const payload = JSON.stringify(event);
for (const socket of this.socketsBySession.get(sessionId) ?? []) {
if (socket.readyState === socket.OPEN) socket.send(payload);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
import {
AuthStorage,
createAgentSession,
ModelRegistry,
SessionManager,
type AgentSession,
} from "@mariozechner/pi-coding-agent";
import type { ClientSession } from "../types.js";
import type { SessionEventHub } from "../realtime/sessionEventHub.js";
interface ActiveSession {
session: AgentSession;
unsubscribe: () => void;
}
export class PiSessionService {
private readonly active = new Map<string, ActiveSession>();
private readonly authStorage = AuthStorage.create();
private readonly modelRegistry = ModelRegistry.create(this.authStorage);
constructor(private readonly events: SessionEventHub) {}
async list(cwd: string): Promise<ClientSession[]> {
const sessions = await SessionManager.list(cwd);
return sessions.map((s) => ({
id: s.id,
path: s.path,
cwd: s.cwd,
name: s.name,
created: s.created.toISOString(),
modified: s.modified.toISOString(),
messageCount: s.messageCount,
firstMessage: s.firstMessage,
}));
}
async start(cwd: string): Promise<ClientSession> {
const { session } = await this.create(SessionManager.create(cwd), cwd);
return {
id: session.sessionId,
path: session.sessionFile ?? "",
cwd,
created: new Date().toISOString(),
modified: new Date().toISOString(),
messageCount: session.messages.length,
firstMessage: "",
};
}
async messages(sessionId: string): Promise<unknown[]> {
const session = await this.getOrOpen(sessionId);
return session.messages;
}
async prompt(sessionId: string, text: string): Promise<void> {
const session = await this.getOrOpen(sessionId);
void session.prompt(text).catch((error) => {
this.events.publish(sessionId, { type: "session.error", message: error instanceof Error ? error.message : String(error) });
});
}
async abort(sessionId: string): Promise<void> {
const active = this.active.get(sessionId);
if (active) await active.session.abort();
}
close(sessionId: string): void {
const active = this.active.get(sessionId);
if (!active) return;
active.unsubscribe();
active.session.dispose();
this.active.delete(sessionId);
}
private async getOrOpen(sessionId: string): Promise<AgentSession> {
const active = this.active.get(sessionId);
if (active) return active.session;
const match = (await SessionManager.listAll()).find((s) => s.id === sessionId || s.id.startsWith(sessionId));
if (!match) throw new Error("Session not found");
return (await this.create(SessionManager.open(match.path), match.cwd)).session;
}
private async create(sessionManager: SessionManager, cwd: string): Promise<ActiveSession> {
const { session } = await createAgentSession({
cwd,
sessionManager,
authStorage: this.authStorage,
modelRegistry: this.modelRegistry,
});
const unsubscribe = session.subscribe((event) => {
this.events.publish(session.sessionId, toClientEvent(event));
});
const active = { session, unsubscribe };
this.active.set(session.sessionId, active);
return active;
}
}
function toClientEvent(event: any): unknown {
if (event.type === "message_update" && event.assistantMessageEvent?.type === "text_delta") {
return { type: "assistant.delta", text: event.assistantMessageEvent.delta };
}
if (event.type === "tool_execution_start") {
return { type: "tool.start", toolName: event.toolName, toolCallId: event.toolCallId };
}
if (event.type === "tool_execution_end") {
return { type: "tool.end", toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError };
}
if (event.type === "agent_start") return { type: "agent.start" };
if (event.type === "agent_end") return { type: "agent.end" };
if (event.type === "message_end") return { type: "message.end" };
return { type: "pi.event", eventType: event.type };
}
+52
View File
@@ -0,0 +1,52 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { homedir } from "node:os";
import { randomUUID } from "node:crypto";
import type { Project } from "../types.js";
interface ProjectFile {
projects: Project[];
}
export class ProjectStore {
constructor(private readonly filePath = join(homedir(), ".pi-web", "projects.json")) {}
async list(): Promise<Project[]> {
return (await this.read()).projects;
}
async add(input: { name?: string; path: string }): Promise<Project> {
const data = await this.read();
const path = input.path;
const existing = data.projects.find((p) => p.path === path);
if (existing) return existing;
const project: Project = {
id: randomUUID(),
name: input.name?.trim() || path.split("/").filter(Boolean).at(-1) || path,
path,
createdAt: new Date().toISOString(),
};
data.projects.push(project);
await this.write(data);
return project;
}
async get(id: string): Promise<Project | undefined> {
return (await this.list()).find((p) => p.id === id);
}
private async read(): Promise<ProjectFile> {
try {
return JSON.parse(await readFile(this.filePath, "utf8")) as ProjectFile;
} catch (error: any) {
if (error?.code === "ENOENT") return { projects: [] };
throw error;
}
}
private async write(data: ProjectFile): Promise<void> {
await mkdir(dirname(this.filePath), { recursive: true });
await writeFile(this.filePath, `${JSON.stringify(data, null, 2)}\n`, "utf8");
}
}
+27
View File
@@ -0,0 +1,27 @@
export interface Project {
id: string;
name: string;
path: string;
createdAt: string;
}
export interface Workspace {
id: string;
projectId: string;
path: string;
label: string;
branch?: string;
isMain: boolean;
isGitWorktree: boolean;
}
export interface ClientSession {
id: string;
path: string;
cwd: string;
name?: string;
created: string;
modified: string;
messageCount: number;
firstMessage: string;
}
@@ -0,0 +1,38 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
export interface GitWorktreeInfo {
path: string;
branch?: string;
bare?: boolean;
detached?: boolean;
}
export async function isGitRepository(path: string): Promise<boolean> {
try {
const { stdout } = await execFileAsync("git", ["-C", path, "rev-parse", "--is-inside-work-tree"]);
return stdout.trim() === "true";
} catch {
return false;
}
}
export async function discoverGitWorktrees(path: string): Promise<GitWorktreeInfo[]> {
const { stdout } = await execFileAsync("git", ["-C", path, "worktree", "list", "--porcelain"]);
const chunks = stdout.trim().split(/\n\s*\n/).filter(Boolean);
return chunks.map((chunk) => {
const info: GitWorktreeInfo = { path: "" };
for (const line of chunk.split("\n")) {
const [key, ...rest] = line.split(" ");
const value = rest.join(" ");
if (key === "worktree") info.path = value;
if (key === "branch") info.branch = value.replace(/^refs\/heads\//, "");
if (key === "bare") info.bare = true;
if (key === "detached") info.detached = true;
}
return info;
}).filter((w) => w.path);
}
+38
View File
@@ -0,0 +1,38 @@
import { createHash } from "node:crypto";
import type { Project } from "../types.js";
import type { Workspace } from "../types.js";
import { discoverGitWorktrees, isGitRepository } from "./gitWorktreeDiscovery.js";
const idFor = (value: string) => createHash("sha1").update(value).digest("hex").slice(0, 12);
export class WorkspaceService {
async list(project: Project): Promise<Workspace[]> {
if (!(await isGitRepository(project.path))) {
return [this.single(project)];
}
const worktrees = await discoverGitWorktrees(project.path);
if (worktrees.length === 0) return [this.single(project)];
return worktrees.map((worktree) => ({
id: idFor(`${project.id}:${worktree.path}`),
projectId: project.id,
path: worktree.path,
label: worktree.branch || (worktree.detached ? "detached" : worktree.path.split("/").filter(Boolean).at(-1) || worktree.path),
branch: worktree.branch,
isMain: worktree.path === project.path,
isGitWorktree: true,
}));
}
private single(project: Project): Workspace {
return {
id: idFor(`${project.id}:${project.path}`),
projectId: project.id,
path: project.path,
label: project.name,
isMain: true,
isGitWorktree: false,
};
}
}