Archived
Add pi web POC
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
.DS_Store
|
||||
*.log
|
||||
@@ -0,0 +1,46 @@
|
||||
# Pi Web POC
|
||||
|
||||
Small web wrapper around `@mariozechner/pi-coding-agent`.
|
||||
|
||||
## What it does
|
||||
|
||||
- Add/list projects.
|
||||
- Discover workspaces from `git worktree list --porcelain`.
|
||||
- For non-git projects, show the project folder as the only workspace.
|
||||
- List Pi sessions for a workspace using Pi's default session storage.
|
||||
- Start Pi sessions, chat over WebSocket events, and close active runtimes.
|
||||
|
||||
## State
|
||||
|
||||
This POC intentionally keeps state minimal:
|
||||
|
||||
- Projects: `~/.pi-web/projects.json`
|
||||
- Workspaces: discovered from git, not stored
|
||||
- Sessions/chat history: Pi default JSONL session storage
|
||||
- Active sessions/WebSockets: memory only
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Open the Vite URL, usually <http://localhost:5173>.
|
||||
|
||||
For a single-process/proxied deployment:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
PI_WEB_PORT=3000 npm start
|
||||
```
|
||||
|
||||
Then proxy Traefik to `http://127.0.0.1:3000`.
|
||||
|
||||
The server defaults to `127.0.0.1:3000`. Use `PI_WEB_HOST=0.0.0.0` only if you want to bind directly on all interfaces.
|
||||
|
||||
## Notes
|
||||
|
||||
- The backend uses your normal Pi auth/model settings from `~/.pi/agent`.
|
||||
- Slash commands that belong to Pi's interactive TUI, such as `/model`, are not implemented in this POC UI yet. Plain prompts and extension/prompt-template handling go through the SDK path.
|
||||
- `Close` currently only disposes the in-memory runtime. It does not hide or delete sessions.
|
||||
Generated
+5811
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "pi-web-poc",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "sh -c 'npm run dev:server & npm run dev:client & wait'",
|
||||
"dev:server": "tsx watch src/server/index.ts",
|
||||
"dev:client": "vite --host 0.0.0.0",
|
||||
"build": "tsc && vite build",
|
||||
"start": "tsx src/server/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/static": "^8.3.0",
|
||||
"@fastify/websocket": "^11.2.0",
|
||||
"@mariozechner/pi-coding-agent": "^0.73.0",
|
||||
"fastify": "^5.6.1",
|
||||
"lit": "^3.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/ws": "^8.18.1",
|
||||
"tsx": "^4.20.6",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.2.4"
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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`);
|
||||
}
|
||||
@@ -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),
|
||||
}));
|
||||
}
|
||||
@@ -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 });
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig({
|
||||
root: "src/client",
|
||||
build: {
|
||||
outDir: "../../dist/client",
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
"/api": "http://localhost:3000",
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user