Improve session reconnect behavior

This commit is contained in:
Federico Jaramillo Martinez
2026-05-07 13:00:10 +02:00
parent fd28af3c93
commit ad05497319
10 changed files with 114 additions and 15 deletions
+4
View File
@@ -113,6 +113,10 @@ app.get<{ Params: { sessionId: string } }>("/api/sessions/:sessionId/events", {
eventHub.add(request.params.sessionId, socket);
});
app.get("/api/sessions/events", { websocket: true }, (socket) => {
eventHub.addGlobal(socket);
});
app.get<{ Querystring: { cwd?: string; q?: string; kind?: "tracked" | "untracked" | "other" } }>("/api/files", async (request, reply) => {
if (!request.query.cwd) return reply.code(400).send({ error: "cwd query parameter is required" });
try {
+13
View File
@@ -2,6 +2,7 @@ import type { WebSocket } from "ws";
export class SessionEventHub {
private readonly socketsBySession = new Map<string, Set<WebSocket>>();
private readonly globalSockets = new Set<WebSocket>();
add(sessionId: string, socket: WebSocket): void {
let sockets = this.socketsBySession.get(sessionId);
@@ -13,10 +14,22 @@ export class SessionEventHub {
socket.on("close", () => sockets?.delete(socket));
}
addGlobal(socket: WebSocket): void {
this.globalSockets.add(socket);
socket.on("close", () => this.globalSockets.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);
}
}
publishGlobal(event: unknown): void {
const payload = JSON.stringify(event);
for (const socket of this.globalSockets) {
if (socket.readyState === socket.OPEN) socket.send(payload);
}
}
}
+8 -2
View File
@@ -135,7 +135,7 @@ export class PiSessionService {
this.bindRuntime(active);
runtime.setRebindSession(async () => this.bindRuntime(active));
this.active.set(runtime.session.sessionId, active);
this.events.publish(runtime.session.sessionId, { type: "status.update", status: this.statusFromSession(runtime.session) });
this.publishStatus(runtime.session);
return active;
}
@@ -147,11 +147,17 @@ export class PiSessionService {
const { session } = active.runtime;
active.unsubscribe = session.subscribe((event) => {
this.events.publish(session.sessionId, toClientEvent(event));
this.events.publish(session.sessionId, { type: "status.update", status: this.statusFromSession(session) });
this.publishStatus(session);
});
this.active.set(session.sessionId, active);
}
private publishStatus(session: AgentSession): void {
const status = this.statusFromSession(session);
this.events.publish(session.sessionId, { type: "status.update", status });
this.events.publishGlobal({ type: "status.update", status });
}
private statusFromSession(session: AgentSession): ClientSessionStatus {
const stats = session.getSessionStats();
return {