fix(remote-control): harden self-hosted session flows (#278)

Co-authored-by: chengzifeng <chengzifeng@meituan.com>
This commit is contained in:
Cheng Zi Feng
2026-04-16 10:46:31 +08:00
committed by claude-code-best
parent 920a7ffd9d
commit 962ed75f4b
24 changed files with 1252 additions and 162 deletions

View File

@@ -138,13 +138,19 @@ bun run dist/cli.js
/remote-control
```
CLI 会向 RCS 注册环境,注册成功后在终端显示连接 URL
环境型 Remote Control例如 `claude remote-control` 子命令)会向 RCS 注册环境,注册成功后在终端显示连接 URL
```
https://rcs.example.com/code?bridge=<environmentId>
```
同时支持 QR 码扫码打开。该 URL 即 Web UI 控制面板入口,在浏览器中打开即可远程操控当前会话。
交互式 REPL 方式(`--remote-control``/remote-control`)在某些桥接模式下也可能直接给出会话 URL
```
https://rcs.example.com/code/session_<id>
```
两种 URL 都可以直接在浏览器打开并远程操控当前会话;只有 environment 模式才会出现在 Web UI 的环境列表中。
若已连接,再次执行 `/remote-control` 会显示对话框,包含以下选项:
- **Disconnect this session** — 断开远程连接
@@ -165,7 +171,7 @@ claude bridge
通过 `/remote-control` 命令获取 URL 后,在浏览器打开即可使用。功能:
- 查看已注册的运行环境
- 查看已注册的运行环境environment 模式)
- 创建和管理会话
- 实时查看对话消息和工具调用
- 审批 Claude Code 的工具权限请求
@@ -275,4 +281,3 @@ curl https://rcs.example.com/health
| 依赖 | claude.ai 订阅 + OAuth | 仅需 API Key |
自托管模式的核心优势是:设置 `CLAUDE_BRIDGE_BASE_URL` 后,代码自动调用 `isSelfHostedBridge()` 返回 `true`,跳过所有 GrowthBook 和订阅检查,无需 claude.ai 账户即可使用。

View File

@@ -25,17 +25,18 @@ import {
storeUpdateSession,
storeGetEnvironment,
storeGetSession,
storeListActiveEnvironments,
} from "../store";
import { getEventBus, getAllEventBuses, removeEventBus } from "../transport/event-bus";
import { runDisconnectMonitorSweep } from "../services/disconnect-monitor";
describe("Disconnect Monitor Logic", () => {
beforeEach(() => {
storeReset();
for (const [key] of getAllEventBuses()) {
removeEventBus(key);
}
});
// Test the logic directly rather than the interval-based monitor
// to avoid long-running tests with timers
test("environment times out when lastPollAt is too old", () => {
const env = storeCreateEnvironment({ secret: "s" });
const timeoutMs = 300 * 1000; // 5 minutes
@@ -44,14 +45,7 @@ describe("Disconnect Monitor Logic", () => {
const oldDate = new Date(Date.now() - timeoutMs - 60000);
storeUpdateEnvironment(env.id, { lastPollAt: oldDate });
// Check the timeout logic (same as in disconnect-monitor.ts)
const now = Date.now();
const envs = storeListActiveEnvironments();
for (const e of envs) {
if (e.lastPollAt && now - e.lastPollAt.getTime() > timeoutMs) {
storeUpdateEnvironment(e.id, { status: "disconnected" });
}
}
runDisconnectMonitorSweep();
const updated = storeGetEnvironment(env.id);
expect(updated?.status).toBe("disconnected");
@@ -59,16 +53,7 @@ describe("Disconnect Monitor Logic", () => {
test("environment stays active when lastPollAt is recent", () => {
const env = storeCreateEnvironment({ secret: "s" });
const timeoutMs = 300 * 1000;
// lastPollAt is recent (just created)
const now = Date.now();
const envs = storeListActiveEnvironments();
for (const e of envs) {
if (e.lastPollAt && now - e.lastPollAt.getTime() > timeoutMs) {
storeUpdateEnvironment(e.id, { status: "disconnected" });
}
}
runDisconnectMonitorSweep();
const updated = storeGetEnvironment(env.id);
expect(updated?.status).toBe("active");
@@ -77,25 +62,47 @@ describe("Disconnect Monitor Logic", () => {
test("session becomes inactive when updatedAt is too old", () => {
const session = storeCreateSession({});
storeUpdateSession(session.id, { status: "running" });
const timeoutMs = 300 * 1000 * 2; // 2x disconnect timeout
// Simulate updatedAt being older than 2x timeout
// We can't directly set updatedAt, but we can verify the logic
// by checking that recently updated sessions are not marked inactive
const now = Date.now();
const rec = storeGetSession(session.id);
// Session was just updated, should not be inactive
expect(rec?.status).toBe("running");
expect(now - rec!.updatedAt.getTime()).toBeLessThan(timeoutMs);
expect(rec).toBeTruthy();
if (!rec) return;
rec.updatedAt = new Date(Date.now() - 300 * 1000 * 2 - 60000);
runDisconnectMonitorSweep();
const updated = storeGetSession(session.id);
expect(updated?.status).toBe("inactive");
});
test("session stays running when recently updated", () => {
const session = storeCreateSession({});
storeUpdateSession(session.id, { status: "running" });
const timeoutMs = 300 * 1000 * 2;
runDisconnectMonitorSweep();
const updated = storeGetSession(session.id);
expect(updated?.status).toBe("running");
});
test("session timeout publishes an inactive session_status event", () => {
const session = storeCreateSession({});
storeUpdateSession(session.id, { status: "idle" });
const rec = storeGetSession(session.id);
expect(rec?.status).toBe("running");
expect(Date.now() - rec!.updatedAt.getTime()).toBeLessThan(timeoutMs);
expect(rec).toBeTruthy();
if (!rec) return;
rec.updatedAt = new Date(Date.now() - 300 * 1000 * 2 - 60000);
const bus = getEventBus(session.id);
const events: Array<{ type: string; payload: { status?: string } }> = [];
bus.subscribe((event) => {
events.push({ type: event.type, payload: event.payload as { status?: string } });
});
runDisconnectMonitorSweep();
expect(events).toContainEqual({
type: "session_status",
payload: { status: "inactive" },
});
});
});

View File

@@ -19,16 +19,18 @@ mock.module("../config", () => ({
import { Hono } from "hono";
import { storeReset, storeCreateSession, storeCreateEnvironment, storeBindSession } from "../store";
import { removeEventBus, getAllEventBuses } from "../transport/event-bus";
import { removeEventBus, getAllEventBuses, getEventBus } from "../transport/event-bus";
import { issueToken } from "../auth/token";
import { publishSessionEvent } from "../services/transport";
// Import route modules
import v1Sessions from "../routes/v1/sessions";
import v1Environments from "../routes/v1/environments";
import v1EnvironmentsWork from "../routes/v1/environments.work";
import v1SessionIngress from "../routes/v1/session-ingress";
import v1SessionIngress, { websocket as sessionIngressWebsocket } from "../routes/v1/session-ingress";
import v2CodeSessions from "../routes/v2/code-sessions";
import v2Worker from "../routes/v2/worker";
import v2WorkerEventsStream from "../routes/v2/worker-events-stream";
import v2WorkerEvents from "../routes/v2/worker-events";
import webAuth from "../routes/web/auth";
import webSessions from "../routes/web/sessions";
@@ -43,6 +45,7 @@ function createApp() {
app.route("/v2/session_ingress", v1SessionIngress);
app.route("/v1/code/sessions", v2CodeSessions);
app.route("/v1/code/sessions", v2Worker);
app.route("/v1/code/sessions", v2WorkerEventsStream);
app.route("/v1/code/sessions", v2WorkerEvents);
app.route("/web", webAuth);
app.route("/web", webSessions);
@@ -53,6 +56,11 @@ function createApp() {
const AUTH_HEADERS = { Authorization: "Bearer test-api-key", "X-Username": "testuser" };
function toWebSessionId(sessionId: string): string {
if (!sessionId.startsWith("cse_")) return sessionId;
return `session_${sessionId.slice("cse_".length)}`;
}
describe("V1 Session Routes", () => {
let app: Hono;
@@ -109,6 +117,24 @@ describe("V1 Session Routes", () => {
expect(res.status).toBe(404);
});
test("GET /v1/sessions/:id — resolves compat code session IDs", async () => {
const createRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const {
session: { id },
} = await createRes.json();
const getRes = await app.request(`/v1/sessions/${toWebSessionId(id)}`, {
headers: AUTH_HEADERS,
});
expect(getRes.status).toBe(200);
const body = await getRes.json();
expect(body.id).toBe(id);
});
test("PATCH /v1/sessions/:id — updates title", async () => {
const createRes = await app.request("/v1/sessions", {
method: "POST",
@@ -142,6 +168,32 @@ describe("V1 Session Routes", () => {
expect(archiveRes.status).toBe(200);
});
test("POST /v1/sessions/:id/archive — archives compat code session IDs", async () => {
const createRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const {
session: { id },
} = await createRes.json();
const compatId = toWebSessionId(id);
const archiveRes = await app.request(`/v1/sessions/${compatId}/archive`, {
method: "POST",
headers: AUTH_HEADERS,
});
expect(archiveRes.status).toBe(200);
const getRes = await app.request(`/v1/sessions/${compatId}`, {
headers: AUTH_HEADERS,
});
expect(getRes.status).toBe(200);
const body = await getRes.json();
expect(body.id).toBe(id);
expect(body.status).toBe("archived");
});
test("POST /v1/sessions/:id/events — publishes events", async () => {
const createRes = await app.request("/v1/sessions", {
method: "POST",
@@ -160,6 +212,30 @@ describe("V1 Session Routes", () => {
expect(body.events).toBe(1);
});
test("POST /v1/sessions/:id/events — resolves compat code session IDs", async () => {
const createRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const {
session: { id },
} = await createRes.json();
const compatId = toWebSessionId(id);
const eventsRes = await app.request(`/v1/sessions/${compatId}/events`, {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({ events: [{ type: "user", content: "hello from compat" }] }),
});
expect(eventsRes.status).toBe(200);
const events = getEventBus(id).getEventsSince(0);
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("user");
expect((events[0]?.payload as { content?: string }).content).toBe("hello from compat");
});
test("POST /v1/sessions with environment_id creates work item", async () => {
// First register an environment
const envRes = await app.request("/v1/environments/bridge", {
@@ -443,6 +519,26 @@ describe("Web Auth Routes", () => {
expect(body.ok).toBe(true);
});
test("POST /web/bind — binds compat code session ID to UUID", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const body = await sessRes.json();
const compatId = toWebSessionId(body.session.id);
const bindRes = await app.request("/web/bind?uuid=test-uuid", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionId: compatId }),
});
expect(bindRes.status).toBe(200);
const bindBody = await bindRes.json();
expect(bindBody.ok).toBe(true);
expect(bindBody.sessionId).toBe(compatId);
});
test("POST /web/bind — 404 for unknown session", async () => {
const res = await app.request("/web/bind?uuid=test-uuid", {
method: "POST",
@@ -501,6 +597,24 @@ describe("Web Session Routes", () => {
expect(sessions[0].id).toBe(id);
});
test("GET /web/sessions and /all — serialize owned code sessions as compat IDs", async () => {
const codeSession = storeCreateSession({ idPrefix: "cse_" });
storeBindSession(codeSession.id, "user-1");
const compatId = toWebSessionId(codeSession.id);
const listRes = await app.request("/web/sessions?uuid=user-1");
expect(listRes.status).toBe(200);
const sessions = await listRes.json();
expect(sessions).toHaveLength(1);
expect(sessions[0].id).toBe(compatId);
const allRes = await app.request("/web/sessions/all?uuid=user-1");
expect(allRes.status).toBe(200);
const summaries = await allRes.json();
expect(summaries).toHaveLength(1);
expect(summaries[0].id).toBe(compatId);
});
test("GET /web/sessions — requires UUID", async () => {
const res = await app.request("/web/sessions");
expect(res.status).toBe(401);
@@ -525,6 +639,33 @@ describe("Web Session Routes", () => {
expect(sessions).toHaveLength(1); // only user-1's session, not user-2's
});
test("GET /web/sessions and /all — hides archived and inactive sessions", async () => {
const archived = storeCreateSession({});
const inactive = storeCreateSession({});
const open = storeCreateSession({});
storeBindSession(archived.id, "user-1");
storeBindSession(inactive.id, "user-1");
storeBindSession(open.id, "user-1");
await app.request(`/v1/sessions/${archived.id}/archive`, {
method: "POST",
headers: AUTH_HEADERS,
});
const { storeUpdateSession } = await import("../store");
storeUpdateSession(inactive.id, { status: "inactive" });
const listRes = await app.request("/web/sessions?uuid=user-1");
expect(listRes.status).toBe(200);
const sessions = await listRes.json();
expect(sessions.map((session: { id: string }) => session.id)).toEqual([open.id]);
const allRes = await app.request("/web/sessions/all?uuid=user-1");
expect(allRes.status).toBe(200);
const summaries = await allRes.json();
expect(summaries.map((session: { id: string }) => session.id)).toEqual([open.id]);
});
test("GET /web/sessions/:id — returns owned session", async () => {
const createRes = await app.request("/web/sessions?uuid=user-1", {
method: "POST",
@@ -563,6 +704,22 @@ describe("Web Session Routes", () => {
expect(body.events).toEqual([]);
});
test("GET /web/sessions/:id and history — supports compat code session IDs", async () => {
const codeSession = storeCreateSession({ idPrefix: "cse_" });
storeBindSession(codeSession.id, "user-1");
const compatId = toWebSessionId(codeSession.id);
const getRes = await app.request(`/web/sessions/${compatId}?uuid=user-1`);
expect(getRes.status).toBe(200);
const session = await getRes.json();
expect(session.id).toBe(compatId);
const histRes = await app.request(`/web/sessions/${compatId}/history?uuid=user-1`);
expect(histRes.status).toBe(200);
const history = await histRes.json();
expect(history.events).toEqual([]);
});
test("GET /web/sessions/:id/history — 403 for non-owner", async () => {
const createRes = await app.request("/web/sessions?uuid=user-1", {
method: "POST",
@@ -647,6 +804,24 @@ describe("Web Session Routes", () => {
}
});
test("GET /web/sessions/:id/events — supports compat code session IDs", async () => {
const codeSession = storeCreateSession({ idPrefix: "cse_" });
storeBindSession(codeSession.id, "user-1");
const compatId = toWebSessionId(codeSession.id);
const eventsRes = await app.request(`/web/sessions/${compatId}/events?uuid=user-1`);
expect(eventsRes.status).toBe(200);
expect(eventsRes.headers.get("Content-Type")).toBe("text/event-stream");
const reader = eventsRes.body?.getReader();
if (reader) {
const { value } = await reader.read();
const text = new TextDecoder().decode(value!);
expect(text).toContain(": keepalive");
reader.cancel();
}
});
test("GET /web/sessions/:id/events — 403 for non-owner", async () => {
const createRes = await app.request("/web/sessions?uuid=user-1", {
method: "POST",
@@ -658,6 +833,25 @@ describe("Web Session Routes", () => {
const eventsRes = await app.request(`/web/sessions/${id}/events?uuid=user-2`);
expect(eventsRes.status).toBe(403);
});
test("GET /web/sessions/:id/events — 409 for archived session", async () => {
const createRes = await app.request("/web/sessions?uuid=user-1", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { id } = await createRes.json();
await app.request(`/v1/sessions/${id}/archive`, {
method: "POST",
headers: AUTH_HEADERS,
});
const res = await app.request(`/web/sessions/${id}/events?uuid=user-1`);
expect(res.status).toBe(409);
const body = await res.json();
expect(body.error.type).toBe("session_closed");
});
});
describe("Web Control Routes", () => {
@@ -692,6 +886,32 @@ describe("Web Control Routes", () => {
expect(body.event).toBeTruthy();
});
test("POST /web/sessions/:id/events/control/interrupt — supports compat code session IDs", async () => {
const rawSessionId = storeCreateSession({ idPrefix: "cse_" }).id;
storeBindSession(rawSessionId, "user-1");
const compatId = toWebSessionId(rawSessionId);
const eventsRes = await app.request(`/web/sessions/${compatId}/events?uuid=user-1`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "user", content: "hello" }),
});
expect(eventsRes.status).toBe(200);
const controlRes = await app.request(`/web/sessions/${compatId}/control?uuid=user-1`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "permission_response", approved: true, request_id: "r1" }),
});
expect(controlRes.status).toBe(200);
const interruptRes = await app.request(`/web/sessions/${compatId}/interrupt?uuid=user-1`, {
method: "POST",
headers: { "Content-Type": "application/json" },
});
expect(interruptRes.status).toBe(200);
});
test("POST /web/sessions/:id/events — 403 for non-owner", async () => {
const res = await app.request(`/web/sessions/${sessionId}/events?uuid=user-2`, {
method: "POST",
@@ -743,6 +963,33 @@ describe("Web Control Routes", () => {
});
expect(res.status).toBe(403);
});
test("POST /web/sessions/:id/events/control/interrupt — 409 for archived session", async () => {
await app.request(`/v1/sessions/${sessionId}/archive`, {
method: "POST",
headers: AUTH_HEADERS,
});
const eventsRes = await app.request(`/web/sessions/${sessionId}/events?uuid=user-1`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "user", content: "hello" }),
});
expect(eventsRes.status).toBe(409);
const controlRes = await app.request(`/web/sessions/${sessionId}/control?uuid=user-1`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type: "permission_response", approved: true, request_id: "r1" }),
});
expect(controlRes.status).toBe(409);
const interruptRes = await app.request(`/web/sessions/${sessionId}/interrupt?uuid=user-1`, {
method: "POST",
headers: { "Content-Type": "application/json" },
});
expect(interruptRes.status).toBe(409);
});
});
describe("Web Environment Routes", () => {
@@ -822,6 +1069,81 @@ describe("V1 Session Ingress Routes (HTTP)", () => {
});
expect(res.status).toBe(404);
});
test("POST /v2/session_ingress/session/:sessionId/events — resolves compat code session IDs", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const {
session: { id },
} = await sessRes.json();
const compatId = toWebSessionId(id);
const res = await app.request(`/v2/session_ingress/session/${compatId}/events`, {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({ events: [{ type: "assistant", message: { role: "assistant", content: "compat ok" } }] }),
});
expect(res.status).toBe(200);
const events = getEventBus(id).getEventsSince(0);
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("assistant");
});
test("GET /v2/session_ingress/ws/:sessionId — resolves compat code session IDs", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const {
session: { id },
} = await sessRes.json();
const compatId = toWebSessionId(id);
publishSessionEvent(id, "user", { content: "compat ws replay" }, "outbound");
const server = Bun.serve({
port: 0,
fetch: app.fetch,
websocket: {
...sessionIngressWebsocket,
idleTimeout: 30,
},
});
try {
const message = await new Promise<string>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/v2/session_ingress/ws/${compatId}?token=test-api-key`);
const timeout = setTimeout(() => {
ws.close();
reject(new Error("Timed out waiting for compat WebSocket replay"));
}, 2000);
ws.onmessage = (event) => {
const data = typeof event.data === "string" ? event.data : String(event.data);
if (data.includes("\"type\":\"user\"")) {
clearTimeout(timeout);
ws.close();
resolve(data);
}
};
ws.onerror = () => {
clearTimeout(timeout);
reject(new Error("Compat WebSocket connection failed"));
};
});
expect(message).toContain("\"type\":\"user\"");
expect(message).toContain(`\"session_id\":\"${id}\"`);
expect(message).toContain("compat ws replay");
} finally {
await server.stop(true);
}
});
});
describe("V2 Worker Events Routes", () => {
@@ -856,6 +1178,112 @@ describe("V2 Worker Events Routes", () => {
expect(body.count).toBe(1);
});
test("POST /v1/code/sessions/:id/worker/events — unwraps CCR batch payloads", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { session: { id } } = await sessRes.json();
const res = await app.request(`/v1/code/sessions/${id}/worker/events`, {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({
worker_epoch: 1,
events: [{ payload: { type: "assistant", content: "response" } }],
}),
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.count).toBe(1);
const events = getEventBus(id).getEventsSince(0);
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("assistant");
expect((events[0]?.payload as { content?: string }).content).toBe("response");
});
test("GET/PUT /v1/code/sessions/:id/worker — stores worker state", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { session: { id } } = await sessRes.json();
const putRes = await app.request(`/v1/code/sessions/${id}/worker`, {
method: "PUT",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({
worker_epoch: 1,
worker_status: "running",
external_metadata: { permission_mode: "default" },
}),
});
expect(putRes.status).toBe(200);
const getRes = await app.request(`/v1/code/sessions/${id}/worker`, {
headers: AUTH_HEADERS,
});
expect(getRes.status).toBe(200);
const body = await getRes.json();
expect(body.worker.worker_status).toBe("running");
expect(body.worker.external_metadata.permission_mode).toBe("default");
});
test("POST /v1/code/sessions/:id/worker/heartbeat — updates heartbeat", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { session: { id } } = await sessRes.json();
const heartbeatRes = await app.request(`/v1/code/sessions/${id}/worker/heartbeat`, {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({ worker_epoch: 1 }),
});
expect(heartbeatRes.status).toBe(200);
const getRes = await app.request(`/v1/code/sessions/${id}/worker`, {
headers: AUTH_HEADERS,
});
const body = await getRes.json();
expect(body.worker.last_heartbeat_at).toBeTruthy();
});
test("GET /v1/code/sessions/:id/worker/events/stream — emits CCR client_event frames", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { session: { id } } = await sessRes.json();
const streamRes = await app.request(`/v1/code/sessions/${id}/worker/events/stream`, {
headers: AUTH_HEADERS,
});
expect(streamRes.status).toBe(200);
const reader = streamRes.body?.getReader();
expect(reader).toBeTruthy();
if (!reader) return;
const firstChunk = await reader.read();
const keepalive = new TextDecoder().decode(firstChunk.value!);
expect(keepalive).toContain(": keepalive");
publishSessionEvent(id, "user", { type: "user", content: "hello" }, "outbound");
const secondChunk = await reader.read();
const frame = new TextDecoder().decode(secondChunk.value!);
expect(frame).toContain("event: client_event");
expect(frame).toContain("\"payload\":{\"type\":\"user\",\"content\":\"hello\",\"message\":{\"content\":\"hello\"}}");
reader.cancel();
});
test("PUT /v1/code/sessions/:id/worker/state — updates session status", async () => {
const sessRes = await app.request("/v1/sessions", {
method: "POST",
@@ -903,4 +1331,20 @@ describe("V2 Worker Events Routes", () => {
});
expect(res.status).toBe(200);
});
test("POST /v1/code/sessions/:id/worker/events/delivery — batch no-op", async () => {
const sessRes = await app.request("/v1/code/sessions", {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const { session: { id } } = await sessRes.json();
const res = await app.request(`/v1/code/sessions/${id}/worker/events/delivery`, {
method: "POST",
headers: { ...AUTH_HEADERS, "Content-Type": "application/json" },
body: JSON.stringify({ worker_epoch: 1, updates: [{ event_id: "evt123", status: "received" }] }),
});
expect(res.status).toBe(200);
});
});

View File

@@ -345,6 +345,14 @@ describe("Transport Service", () => {
expect(result.message).toEqual(msg);
});
test("preserves uuid field", () => {
const result = normalizePayload("user", {
uuid: "msg_123",
content: "hi",
});
expect(result.uuid).toBe("msg_123");
});
test("uses name as tool_name fallback", () => {
const result = normalizePayload("tool", { name: "Read" });
expect(result.tool_name).toBe("Read");

View File

@@ -336,6 +336,26 @@ describe("ws-handler", () => {
expect(lastMsg.message.content).toBe("hello world");
});
test("preserves payload uuid for outbound user events", () => {
const bus = getEventBus("um2");
const ws = createMockWs();
handleWebSocketOpen(ws, "um2");
bus.publish({
id: "internal-event-id",
sessionId: "um2",
type: "user",
payload: { uuid: "web-message-uuid", content: "hello from web" },
direction: "outbound",
});
const sent = ws.getSentData();
const lastMsg = JSON.parse(sent[sent.length - 1]);
expect(lastMsg.type).toBe("user");
expect(lastMsg.uuid).toBe("web-message-uuid");
expect(lastMsg.message.content).toBe("hello from web");
});
test("converts generic event type", () => {
const bus = getEventBus("gen1");
const ws = createMockWs();

View File

@@ -8,7 +8,7 @@ import {
handleWebSocketClose,
ingestBridgeMessage,
} from "../../transport/ws-handler";
import { getSession } from "../../services/session";
import { getSession, resolveExistingSessionId } from "../../services/session";
const { upgradeWebSocket, websocket } = createBunWebSocket();
@@ -43,7 +43,8 @@ function authenticateRequest(c: any, label: string, expectedSessionId?: string):
/** POST /v2/session_ingress/session/:sessionId/events — HTTP POST (HybridTransport writes) */
app.post("/session/:sessionId/events", async (c) => {
const sessionId = c.req.param("sessionId")!;
const requestedSessionId = c.req.param("sessionId")!;
const sessionId = resolveExistingSessionId(requestedSessionId) ?? requestedSessionId;
if (!authenticateRequest(c, `POST session/${sessionId}`, sessionId)) {
return c.json({ error: { type: "unauthorized", message: "Invalid auth" } }, 401);
@@ -71,7 +72,8 @@ app.post("/session/:sessionId/events", async (c) => {
app.get(
"/ws/:sessionId",
upgradeWebSocket(async (c) => {
const sessionId = c.req.param("sessionId")!;
const requestedSessionId = c.req.param("sessionId")!;
const sessionId = resolveExistingSessionId(requestedSessionId) ?? requestedSessionId;
if (!authenticateRequest(c, `WS ${sessionId}`, sessionId)) {
return {

View File

@@ -4,6 +4,7 @@ import {
getSession,
updateSessionTitle,
archiveSession,
resolveExistingSessionId,
} from "../../services/session";
import { createWorkItem } from "../../services/work-dispatch";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
@@ -38,7 +39,8 @@ app.post("/", acceptCliHeaders, apiKeyAuth, async (c) => {
/** GET /v1/sessions/:id — Get session */
app.get("/:id", acceptCliHeaders, apiKeyAuth, async (c) => {
const session = getSession(c.req.param("id")!);
const sessionId = resolveExistingSessionId(c.req.param("id")!) ?? c.req.param("id")!;
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
@@ -47,27 +49,43 @@ app.get("/:id", acceptCliHeaders, apiKeyAuth, async (c) => {
/** PATCH /v1/sessions/:id — Update session title */
app.patch("/:id", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = resolveExistingSessionId(c.req.param("id")!) ?? c.req.param("id")!;
const existing = getSession(sessionId);
if (!existing) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const body = await c.req.json();
if (body.title) {
updateSessionTitle(c.req.param("id")!, body.title);
updateSessionTitle(sessionId, body.title);
}
const session = getSession(c.req.param("id")!);
const session = getSession(sessionId);
return c.json(session, 200);
});
/** POST /v1/sessions/:id/archive — Archive session */
app.post("/:id/archive", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = resolveExistingSessionId(c.req.param("id")!) ?? c.req.param("id")!;
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
try {
archiveSession(c.req.param("id")!);
archiveSession(sessionId);
} catch {
return c.json({ status: "ok" }, 409);
}
return c.json({ status: "ok" }, 200);
});
/** POST /v1/sessions/:id/events — Send event to session */
app.post("/:id/events", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = c.req.param("id")!;
const sessionId = resolveExistingSessionId(c.req.param("id")!) ?? c.req.param("id")!;
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const body = await c.req.json();
const events = body.events

View File

@@ -1,6 +1,6 @@
import { Hono } from "hono";
import { sessionIngressAuth, acceptCliHeaders } from "../../auth/middleware";
import { createSSEStream } from "../../transport/sse-writer";
import { createWorkerEventStream } from "../../transport/sse-writer";
import { getSession } from "../../services/session";
const app = new Hono();
@@ -18,7 +18,7 @@ app.get("/:id/worker/events/stream", acceptCliHeaders, sessionIngressAuth, async
const fromSeq = c.req.query("from_sequence_num");
const fromSeqNum = fromSeq ? parseInt(fromSeq) : lastEventId ? parseInt(lastEventId) : 0;
return createSSEStream(c, sessionId, fromSeqNum);
return createWorkerEventStream(c, sessionId, fromSeqNum);
});
export default app;

View File

@@ -1,32 +1,66 @@
import { Hono } from "hono";
import { sessionIngressAuth, acceptCliHeaders } from "../../auth/middleware";
import { publishSessionEvent } from "../../services/transport";
import { getSession, updateSessionStatus } from "../../services/session";
import { getSession, touchSession, updateSessionStatus } from "../../services/session";
const app = new Hono();
function extractWorkerEvents(body: unknown): Array<Record<string, unknown>> {
if (!body || typeof body !== "object") {
return [];
}
const payload = body as Record<string, unknown>;
const rawEvents = Array.isArray(payload.events)
? payload.events
: Array.isArray(body)
? body
: [body];
return rawEvents
.filter((evt): evt is Record<string, unknown> => !!evt && typeof evt === "object")
.map((evt) => {
const wrappedPayload = evt.payload;
if (wrappedPayload && typeof wrappedPayload === "object" && !Array.isArray(wrappedPayload)) {
return wrappedPayload as Record<string, unknown>;
}
return evt;
});
}
/** POST /v1/code/sessions/:id/worker/events — Write events */
app.post("/:id/worker/events", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
if (!getSession(sessionId)) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const body = await c.req.json();
const events = Array.isArray(body) ? body : [body];
const events = extractWorkerEvents(body);
const published = [];
for (const evt of events) {
const result = publishSessionEvent(sessionId, evt.type || "message", evt, "inbound");
const eventType = typeof evt.type === "string" ? evt.type : "message";
const result = publishSessionEvent(sessionId, eventType, evt, "inbound");
published.push(result);
}
touchSession(sessionId);
return c.json({ status: "ok", count: published.length }, 200);
});
/** PUT /v1/code/sessions/:id/worker/state — Report worker state */
app.put("/:id/worker/state", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
if (!getSession(sessionId)) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const body = await c.req.json();
if (body.status) {
updateSessionStatus(sessionId, body.status);
} else {
touchSession(sessionId);
}
return c.json({ status: "ok" }, 200);
@@ -34,12 +68,29 @@ app.put("/:id/worker/state", acceptCliHeaders, sessionIngressAuth, async (c) =>
/** PUT /v1/code/sessions/:id/worker/external_metadata — Report worker metadata (no-op) */
app.put("/:id/worker/external_metadata", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
if (!getSession(sessionId)) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
// TUI's CCRClient calls this for metadata reporting. Accept and discard.
return c.json({ status: "ok" }, 200);
});
/** POST /v1/code/sessions/:id/worker/events/delivery — Batch delivery tracking (no-op) */
app.post("/:id/worker/events/delivery", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
if (!getSession(sessionId)) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
return c.json({ status: "ok" }, 200);
});
/** POST /v1/code/sessions/:id/worker/events/:eventId/delivery — Delivery tracking (no-op) */
app.post("/:id/worker/events/:eventId/delivery", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
if (!getSession(sessionId)) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
// TUI's CCRClient reports event delivery status (received/processing/processed).
// Accept and discard — event bus doesn't track per-event delivery.
return c.json({ status: "ok" }, 200);

View File

@@ -1,9 +1,75 @@
import { Hono } from "hono";
import { getSession, incrementEpoch } from "../../services/session";
import { apiKeyAuth, acceptCliHeaders } from "../../auth/middleware";
import { getSession, incrementEpoch, touchSession, updateSessionStatus } from "../../services/session";
import { apiKeyAuth, acceptCliHeaders, sessionIngressAuth } from "../../auth/middleware";
import { storeGetSessionWorker, storeUpsertSessionWorker } from "../../store";
const app = new Hono();
/** GET /v1/code/sessions/:id/worker — Read worker state */
app.get("/:id/worker", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const worker = storeGetSessionWorker(sessionId);
return c.json({
worker: {
worker_status: worker?.workerStatus ?? session.status,
external_metadata: worker?.externalMetadata ?? null,
requires_action_details: worker?.requiresActionDetails ?? null,
last_heartbeat_at: worker?.lastHeartbeatAt?.toISOString() ?? null,
},
}, 200);
});
/** PUT /v1/code/sessions/:id/worker — Update worker state */
app.put("/:id/worker", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const body = await c.req.json();
if (body.worker_status) {
updateSessionStatus(sessionId, body.worker_status);
} else {
touchSession(sessionId);
}
const worker = storeUpsertSessionWorker(sessionId, {
workerStatus: body.worker_status,
externalMetadata: body.external_metadata,
requiresActionDetails: body.requires_action_details,
});
return c.json({
status: "ok",
worker: {
worker_status: worker.workerStatus ?? session.status,
external_metadata: worker.externalMetadata,
requires_action_details: worker.requiresActionDetails,
last_heartbeat_at: worker.lastHeartbeatAt?.toISOString() ?? null,
},
}, 200);
});
/** POST /v1/code/sessions/:id/worker/heartbeat — Keep worker alive */
app.post("/:id/worker/heartbeat", acceptCliHeaders, sessionIngressAuth, async (c) => {
const sessionId = c.req.param("id")!;
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
const now = new Date();
storeUpsertSessionWorker(sessionId, { lastHeartbeatAt: now });
touchSession(sessionId);
return c.json({ status: "ok", last_heartbeat_at: now.toISOString() }, 200);
});
/** POST /v1/code/sessions/:id/worker/register — Register worker */
app.post("/:id/worker/register", acceptCliHeaders, apiKeyAuth, async (c) => {
const sessionId = c.req.param("id")!;

View File

@@ -1,5 +1,6 @@
import { Hono } from "hono";
import { storeGetSession, storeBindSession } from "../../store";
import { storeBindSession } from "../../store";
import { resolveExistingWebSessionId, toWebSessionId } from "../../services/session";
const app = new Hono();
@@ -14,13 +15,13 @@ app.post("/bind", async (c) => {
return c.json({ error: "sessionId and uuid are required" }, 400);
}
const session = storeGetSession(sessionId);
if (!session) {
const resolvedSessionId = resolveExistingWebSessionId(sessionId);
if (!resolvedSessionId) {
return c.json({ error: "Session not found" }, 404);
}
storeBindSession(sessionId, uuid);
return c.json({ ok: true, sessionId });
storeBindSession(resolvedSessionId, uuid);
return c.json({ ok: true, sessionId: toWebSessionId(resolvedSessionId) });
});
export default app;

View File

@@ -1,31 +1,46 @@
import { Hono } from "hono";
import { uuidAuth } from "../../auth/middleware";
import { getSession, updateSessionStatus } from "../../services/session";
import { getSession, isSessionClosedStatus, resolveOwnedWebSessionId, updateSessionStatus } from "../../services/session";
import { publishSessionEvent } from "../../services/transport";
import { getEventBus } from "../../transport/event-bus";
import { storeIsSessionOwner } from "../../store";
const app = new Hono();
function checkOwnership(c: { get: (key: string) => string | undefined }, sessionId: string) {
type OwnershipCheckResult =
| { error: true }
| { error: true; reason: string }
| { error: false; session: NonNullable<ReturnType<typeof getSession>>; sessionId: string };
function checkOwnership(c: { get: (key: string) => string | undefined }, sessionId: string): OwnershipCheckResult {
const uuid = c.get("uuid")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
return { error: true, session: null };
const resolvedSessionId = resolveOwnedWebSessionId(sessionId, uuid);
if (!resolvedSessionId) {
return { error: true };
}
const session = getSession(sessionId);
const session = getSession(resolvedSessionId);
if (!session) {
return { error: true, session: null };
return { error: true };
}
return { error: false, session };
if (isSessionClosedStatus(session.status)) {
return { error: true, reason: `Session is ${session.status}` };
}
return { error: false, session, sessionId: resolvedSessionId };
}
function closedSessionResponse(message: string) {
return { error: { type: "session_closed", message } };
}
/** POST /web/sessions/:id/events — Send user message to session */
app.post("/sessions/:id/events", uuidAuth, async (c) => {
const sessionId = c.req.param("id")!;
const { error } = checkOwnership(c, sessionId);
if (error) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
const requestedSessionId = c.req.param("id")!;
const ownership = checkOwnership(c, requestedSessionId);
if (ownership.error) {
const message = "reason" in ownership ? ownership.reason : "Not your session";
const status = "reason" in ownership ? 409 : 403;
return c.json("reason" in ownership ? closedSessionResponse(message) : { error: { type: "forbidden", message } }, status);
}
const { sessionId } = ownership;
const body = await c.req.json();
const eventType = body.type || "user";
@@ -37,11 +52,14 @@ app.post("/sessions/:id/events", uuidAuth, async (c) => {
/** POST /web/sessions/:id/control — Send control request (permission approval etc) */
app.post("/sessions/:id/control", uuidAuth, async (c) => {
const sessionId = c.req.param("id")!;
const { error } = checkOwnership(c, sessionId);
if (error) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
const requestedSessionId = c.req.param("id")!;
const ownership = checkOwnership(c, requestedSessionId);
if (ownership.error) {
const message = "reason" in ownership ? ownership.reason : "Not your session";
const status = "reason" in ownership ? 409 : 403;
return c.json("reason" in ownership ? closedSessionResponse(message) : { error: { type: "forbidden", message } }, status);
}
const { sessionId } = ownership;
const body = await c.req.json();
const event = publishSessionEvent(sessionId, body.type || "control_request", body, "outbound");
@@ -50,11 +68,14 @@ app.post("/sessions/:id/control", uuidAuth, async (c) => {
/** POST /web/sessions/:id/interrupt — Interrupt session */
app.post("/sessions/:id/interrupt", uuidAuth, async (c) => {
const sessionId = c.req.param("id")!;
const { error } = checkOwnership(c, sessionId);
if (error) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
const requestedSessionId = c.req.param("id")!;
const ownership = checkOwnership(c, requestedSessionId);
if (ownership.error) {
const message = "reason" in ownership ? ownership.reason : "Not your session";
const status = "reason" in ownership ? 409 : 403;
return c.json("reason" in ownership ? closedSessionResponse(message) : { error: { type: "forbidden", message } }, status);
}
const { sessionId } = ownership;
publishSessionEvent(sessionId, "interrupt", { action: "interrupt" }, "outbound");
updateSessionStatus(sessionId, "idle");

View File

@@ -1,9 +1,16 @@
import { Hono } from "hono";
import { uuidAuth } from "../../auth/middleware";
import { getSession, createSession } from "../../services/session";
import { storeListSessionsByOwnerUuid, storeIsSessionOwner, storeBindSession } from "../../store";
import {
createSession,
getSession,
isSessionClosedStatus,
listWebSessionSummariesByOwnerUuid,
listWebSessionsByOwnerUuid,
resolveOwnedWebSessionId,
toWebSessionResponse,
} from "../../services/session";
import { storeBindSession } from "../../store";
import { createWorkItem } from "../../services/work-dispatch";
import { listSessionSummariesByOwnerUuid } from "../../services/session";
import { createSSEStream } from "../../transport/sse-writer";
import { getEventBus } from "../../transport/event-bus";
@@ -38,36 +45,36 @@ app.post("/sessions", uuidAuth, async (c) => {
/** GET /web/sessions — List sessions owned by the requesting UUID */
app.get("/sessions", uuidAuth, async (c) => {
const uuid = c.get("uuid")!;
const sessions = storeListSessionsByOwnerUuid(uuid);
const sessions = listWebSessionsByOwnerUuid(uuid);
return c.json(sessions, 200);
});
/** GET /web/sessions/all — List sessions owned by the requesting UUID (unowned sessions excluded) */
app.get("/sessions/all", uuidAuth, async (c) => {
const uuid = c.get("uuid")!;
const sessions = listSessionSummariesByOwnerUuid(uuid);
const sessions = listWebSessionSummariesByOwnerUuid(uuid);
return c.json(sessions, 200);
});
/** GET /web/sessions/:id — Session detail */
app.get("/sessions/:id", uuidAuth, async (c) => {
const uuid = c.get("uuid")!;
const sessionId = c.req.param("id")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
const sessionId = resolveOwnedWebSessionId(c.req.param("id")!, uuid);
if (!sessionId) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
return c.json(session, 200);
return c.json(toWebSessionResponse(session), 200);
});
/** GET /web/sessions/:id/history — Historical events for session */
app.get("/sessions/:id/history", uuidAuth, async (c) => {
const uuid = c.get("uuid")!;
const sessionId = c.req.param("id")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
const sessionId = resolveOwnedWebSessionId(c.req.param("id")!, uuid);
if (!sessionId) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const session = getSession(sessionId);
@@ -83,14 +90,17 @@ app.get("/sessions/:id/history", uuidAuth, async (c) => {
/** SSE /web/sessions/:id/events — Real-time event stream */
app.get("/sessions/:id/events", uuidAuth, async (c) => {
const uuid = c.get("uuid")!;
const sessionId = c.req.param("id")!;
if (!storeIsSessionOwner(sessionId, uuid)) {
const sessionId = resolveOwnedWebSessionId(c.req.param("id")!, uuid);
if (!sessionId) {
return c.json({ error: { type: "forbidden", message: "Not your session" } }, 403);
}
const session = getSession(sessionId);
if (!session) {
return c.json({ error: { type: "not_found", message: "Session not found" } }, 404);
}
if (isSessionClosedStatus(session.status)) {
return c.json({ error: { type: "session_closed", message: `Session is ${session.status}` } }, 409);
}
const lastEventId = c.req.header("Last-Event-ID");
const fromSeqNum = lastEventId ? parseInt(lastEventId) : 0;

View File

@@ -1,32 +1,35 @@
import { storeListActiveEnvironments, storeUpdateEnvironment } from "../store";
import { storeListSessions, storeUpdateSession } from "../store";
import { storeListSessions } from "../store";
import { config } from "../config";
import { updateSessionStatus } from "./session";
export function startDisconnectMonitor() {
export function runDisconnectMonitorSweep(now = Date.now()) {
const timeoutMs = config.disconnectTimeout * 1000;
// Check environment heartbeat timeout
const envs = storeListActiveEnvironments();
for (const env of envs) {
if (env.lastPollAt && now - env.lastPollAt.getTime() > timeoutMs) {
console.log(`[RCS] Environment ${env.id} timed out (no poll for ${Math.round((now - env.lastPollAt.getTime()) / 1000)}s)`);
storeUpdateEnvironment(env.id, { status: "disconnected" });
}
}
// Check session timeout (2x disconnect timeout with no update)
const sessions = storeListSessions();
for (const session of sessions) {
if (session.status === "running" || session.status === "idle") {
const elapsed = now - session.updatedAt.getTime();
if (elapsed > timeoutMs * 2) {
console.log(`[RCS] Session ${session.id} marked inactive (no update for ${Math.round(elapsed / 1000)}s)`);
updateSessionStatus(session.id, "inactive");
}
}
}
}
export function startDisconnectMonitor() {
setInterval(() => {
const now = Date.now();
// Check environment heartbeat timeout
const envs = storeListActiveEnvironments();
for (const env of envs) {
if (env.lastPollAt && now - env.lastPollAt.getTime() > timeoutMs) {
console.log(`[RCS] Environment ${env.id} timed out (no poll for ${Math.round((now - env.lastPollAt.getTime()) / 1000)}s)`);
storeUpdateEnvironment(env.id, { status: "disconnected" });
}
}
// Check session timeout (2x disconnect timeout with no update)
const sessions = storeListSessions();
for (const session of sessions) {
if (session.status === "running" || session.status === "idle") {
const elapsed = now - session.updatedAt.getTime();
if (elapsed > timeoutMs * 2) {
console.log(`[RCS] Session ${session.id} marked inactive (no update for ${Math.round(elapsed / 1000)}s)`);
storeUpdateSession(session.id, { status: "inactive" });
}
}
}
runDisconnectMonitorSweep();
}, 60_000); // Check every minute
}

View File

@@ -1,14 +1,20 @@
import {
storeCreateSession,
storeGetSession,
storeIsSessionOwner,
storeUpdateSession,
storeListSessions,
storeListSessionsByUsername,
storeListSessionsByEnvironment,
storeListSessionsByOwnerUuid,
} from "../store";
import { removeEventBus } from "../transport/event-bus";
import { getAllEventBuses, removeEventBus } from "../transport/event-bus";
import type { CreateSessionRequest, CreateCodeSessionRequest, SessionResponse, SessionSummaryResponse } from "../types/api";
import { v4 as uuid } from "uuid";
const CODE_SESSION_PREFIX = "cse_";
const WEB_SESSION_PREFIX = "session_";
const CLOSED_SESSION_STATUSES = new Set(["archived", "inactive"]);
function toResponse(row: { id: string; environmentId: string | null; title: string | null; status: string; source: string; permissionMode: string | null; workerEpoch: number; username: string | null; createdAt: Date; updatedAt: Date }): SessionResponse {
return {
@@ -25,6 +31,24 @@ function toResponse(row: { id: string; environmentId: string | null; title: stri
};
}
export function toWebSessionId(sessionId: string): string {
if (!sessionId.startsWith(CODE_SESSION_PREFIX)) return sessionId;
return `${WEB_SESSION_PREFIX}${sessionId.slice(CODE_SESSION_PREFIX.length)}`;
}
function toCompatibleCodeSessionId(sessionId: string): string | null {
if (!sessionId.startsWith(WEB_SESSION_PREFIX)) return null;
return `${CODE_SESSION_PREFIX}${sessionId.slice(WEB_SESSION_PREFIX.length)}`;
}
export function toWebSessionResponse(session: SessionResponse): SessionResponse {
return { ...session, id: toWebSessionId(session.id) };
}
function toWebSessionSummaryResponse(session: SessionSummaryResponse): SessionSummaryResponse {
return { ...session, id: toWebSessionId(session.id) };
}
export function createSession(req: CreateSessionRequest & { username?: string }): SessionResponse {
const record = storeCreateSession({
environmentId: req.environment_id,
@@ -51,16 +75,78 @@ export function getSession(sessionId: string): SessionResponse | null {
return record ? toResponse(record) : null;
}
export function isSessionClosedStatus(status: string | null | undefined): boolean {
return !!status && CLOSED_SESSION_STATUSES.has(status);
}
export function resolveExistingSessionId(sessionId: string): string | null {
if (storeGetSession(sessionId)) {
return sessionId;
}
const compatibleCodeSessionId = toCompatibleCodeSessionId(sessionId);
if (compatibleCodeSessionId && storeGetSession(compatibleCodeSessionId)) {
return compatibleCodeSessionId;
}
return null;
}
export function resolveExistingWebSessionId(sessionId: string): string | null {
return resolveExistingSessionId(sessionId);
}
export function resolveOwnedWebSessionId(sessionId: string, uuid: string): string | null {
if (storeIsSessionOwner(sessionId, uuid)) {
return sessionId;
}
const compatibleCodeSessionId = toCompatibleCodeSessionId(sessionId);
if (compatibleCodeSessionId && storeIsSessionOwner(compatibleCodeSessionId, uuid)) {
return compatibleCodeSessionId;
}
return null;
}
export function listWebSessionsByOwnerUuid(uuid: string): SessionResponse[] {
return storeListSessionsByOwnerUuid(uuid)
.filter((session) => !isSessionClosedStatus(session.status))
.map(toResponse)
.map(toWebSessionResponse);
}
export function listWebSessionSummariesByOwnerUuid(uuid: string): SessionSummaryResponse[] {
return storeListSessionsByOwnerUuid(uuid)
.filter((session) => !isSessionClosedStatus(session.status))
.map(toSummaryResponse)
.map(toWebSessionSummaryResponse);
}
export function updateSessionTitle(sessionId: string, title: string) {
storeUpdateSession(sessionId, { title });
}
export function updateSessionStatus(sessionId: string, status: string) {
storeUpdateSession(sessionId, { status });
const bus = getAllEventBuses().get(sessionId);
if (!bus) return;
bus.publish({
id: uuid(),
sessionId,
type: "session_status",
payload: { status },
direction: "inbound",
});
}
export function touchSession(sessionId: string) {
storeUpdateSession(sessionId, {});
}
export function archiveSession(sessionId: string) {
storeUpdateSession(sessionId, { status: "archived" });
updateSessionStatus(sessionId, "archived");
removeEventBus(sessionId);
}

View File

@@ -51,6 +51,8 @@ export function normalizePayload(type: string, payload: unknown): Record<string,
raw: payload,
};
if (typeof p.uuid === "string" && p.uuid) normalized.uuid = p.uuid;
// Preserve tool fields
if (p.tool_name) normalized.tool_name = p.tool_name;
if (p.name) normalized.tool_name = p.name;

View File

@@ -47,6 +47,16 @@ export interface WorkItemRecord {
updatedAt: Date;
}
export interface SessionWorkerRecord {
sessionId: string;
workerStatus: string | null;
externalMetadata: Record<string, unknown> | null;
requiresActionDetails: Record<string, unknown> | null;
lastHeartbeatAt: Date | null;
createdAt: Date;
updatedAt: Date;
}
// ---------- Stores (in-memory Maps) ----------
const users = new Map<string, UserRecord>();
@@ -54,6 +64,7 @@ const tokenToUser = new Map<string, { username: string; createdAt: Date }>();
const environments = new Map<string, EnvironmentRecord>();
const sessions = new Map<string, SessionRecord>();
const workItems = new Map<string, WorkItemRecord>();
const sessionWorkers = new Map<string, SessionWorkerRecord>();
// UUID → session ownership: sessionId → Set of UUIDs
const sessionOwners = new Map<string, Set<string>>();
@@ -190,9 +201,59 @@ export function storeListSessionsByEnvironment(envId: string): SessionRecord[] {
}
export function storeDeleteSession(id: string): boolean {
sessionWorkers.delete(id);
return sessions.delete(id);
}
// ---------- Session Worker ----------
export function storeGetSessionWorker(sessionId: string): SessionWorkerRecord | undefined {
return sessionWorkers.get(sessionId);
}
export function storeUpsertSessionWorker(sessionId: string, patch: {
workerStatus?: string | null;
externalMetadata?: Record<string, unknown> | null;
requiresActionDetails?: Record<string, unknown> | null;
lastHeartbeatAt?: Date | null;
}): SessionWorkerRecord {
const now = new Date();
const existing = sessionWorkers.get(sessionId);
const record: SessionWorkerRecord = existing ?? {
sessionId,
workerStatus: null,
externalMetadata: null,
requiresActionDetails: null,
lastHeartbeatAt: null,
createdAt: now,
updatedAt: now,
};
if (patch.workerStatus !== undefined) {
record.workerStatus = patch.workerStatus;
}
if (patch.externalMetadata !== undefined) {
if (patch.externalMetadata === null) {
record.externalMetadata = null;
} else {
record.externalMetadata = {
...(record.externalMetadata ?? {}),
...patch.externalMetadata,
};
}
}
if (patch.requiresActionDetails !== undefined) {
record.requiresActionDetails = patch.requiresActionDetails;
}
if (patch.lastHeartbeatAt !== undefined) {
record.lastHeartbeatAt = patch.lastHeartbeatAt;
}
record.updatedAt = now;
sessionWorkers.set(sessionId, record);
return record;
}
// ---------- Work Items ----------
// ---------- Session Ownership (UUID-based) ----------
@@ -272,5 +333,6 @@ export function storeReset() {
environments.clear();
sessions.clear();
workItems.clear();
sessionWorkers.clear();
sessionOwners.clear();
}

View File

@@ -115,3 +115,109 @@ export function createSSEStream(c: Context, sessionId: string, fromSeqNum = 0) {
},
});
}
function toWorkerClientPayload(event: SessionEvent): Record<string, unknown> {
const normalized =
event.payload && typeof event.payload === "object"
? (event.payload as Record<string, unknown>)
: undefined;
const raw =
normalized?.raw && typeof normalized.raw === "object" && !Array.isArray(normalized.raw)
? (normalized.raw as Record<string, unknown>)
: undefined;
const payload: Record<string, unknown> = {
...(raw ?? normalized ?? {}),
type: event.type,
};
if (event.type === "user") {
const message = payload.message;
if (!message || typeof message !== "object" || !("content" in message)) {
const content =
typeof normalized?.content === "string"
? normalized.content
: typeof payload.content === "string"
? payload.content
: typeof event.payload === "string"
? event.payload
: "";
payload.content = content;
payload.message = { content };
}
}
return payload;
}
function toWorkerClientFrame(event: SessionEvent): string {
const data = JSON.stringify({
event_id: event.id,
sequence_num: event.seqNum,
event_type: event.type,
source: "client",
payload: toWorkerClientPayload(event),
created_at: new Date(event.createdAt).toISOString(),
});
return `id: ${event.seqNum}\nevent: client_event\ndata: ${data}\n\n`;
}
/** Create CCR worker SSE stream (client_event frames, outbound events only). */
export function createWorkerEventStream(c: Context, sessionId: string, fromSeqNum = 0) {
const bus = getEventBus(sessionId);
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
if (fromSeqNum > 0) {
const missed = bus
.getEventsSince(fromSeqNum)
.filter((event) => event.direction === "outbound");
for (const event of missed) {
controller.enqueue(encoder.encode(toWorkerClientFrame(event)));
}
}
controller.enqueue(encoder.encode(": keepalive\n\n"));
const unsub = bus.subscribe((event) => {
if (event.direction !== "outbound") {
return;
}
try {
controller.enqueue(encoder.encode(toWorkerClientFrame(event)));
} catch {
unsub();
}
});
const keepalive = setInterval(() => {
try {
controller.enqueue(encoder.encode(": keepalive\n\n"));
} catch {
clearInterval(keepalive);
unsub();
}
}, 15000);
c.req.raw.signal.addEventListener("abort", () => {
unsub();
clearInterval(keepalive);
try {
controller.close();
} catch {
// already closed
}
});
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
},
});
}

View File

@@ -24,13 +24,14 @@ const SERVER_KEEPALIVE_INTERVAL_MS = 60_000;
*/
function toSDKMessage(event: SessionEvent): string {
const payload = event.payload as Record<string, unknown> | null;
const messageUuid = typeof payload?.uuid === "string" && payload.uuid ? payload.uuid : event.id;
let msg: Record<string, unknown>;
if (event.type === "user" || event.type === "user_message") {
msg = {
type: "user",
uuid: event.id,
uuid: messageUuid,
session_id: event.sessionId,
message: {
role: "user",
@@ -82,7 +83,7 @@ function toSDKMessage(event: SessionEvent): string {
} else {
msg = {
type: event.type,
uuid: event.id,
uuid: messageUuid,
session_id: event.sessionId,
message: payload,
};

View File

@@ -4,18 +4,26 @@
*/
import { getUuid, setUuid, apiBind, apiFetchSessions, apiFetchAllSessions, apiFetchEnvironments, apiFetchSession, apiFetchSessionHistory, apiSendEvent, apiSendControl, apiInterrupt, apiCreateSession } from "./api.js";
import { connectSSE, disconnectSSE } from "./sse.js";
import { appendEvent, renderPermissionRequest, showLoading, isLoading, resetReplayState, renderReplayPendingRequests } from "./render.js";
import { appendEvent, showLoading, isLoading, removeLoading, resetReplayState, renderReplayPendingRequests } from "./render.js";
import { initTaskPanel, toggleTaskPanel, resetTaskState } from "./task-panel.js";
import { esc, formatTime, statusClass } from "./utils.js";
import { esc, formatTime, statusClass, isClosedSessionStatus } from "./utils.js";
// ============================================================
// State
// ============================================================
let currentSessionId = null;
let currentSessionStatus = null;
let dashboardInterval = null;
let cachedEnvs = [];
function generateMessageUuid() {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return `msg_${Date.now()}_${Math.random().toString(16).slice(2)}`;
}
// ============================================================
// Router
// ============================================================
@@ -43,6 +51,69 @@ function navigate(path) {
}
window.navigate = navigate;
function applySessionStatus(status) {
currentSessionStatus = status || null;
const badge = document.getElementById("session-status");
if (badge) {
badge.textContent = status || "";
badge.className = `status-badge status-${statusClass(status)}`;
}
const closed = isClosedSessionStatus(status);
const input = document.getElementById("msg-input");
if (input) {
input.disabled = closed;
input.placeholder = closed ? "Session is closed" : "Type a message...";
}
const actionBtn = document.getElementById("action-btn");
if (actionBtn) {
actionBtn.disabled = closed;
actionBtn.title = closed ? "Session is closed" : "";
}
if (closed) {
removeLoading();
window.__updateActionBtn?.(false);
}
}
function handleSessionEvent(event) {
if (event?.type === "session_status" && typeof event.payload?.status === "string") {
applySessionStatus(event.payload.status);
if (isClosedSessionStatus(event.payload.status)) {
disconnectSSE();
}
}
appendEvent(event);
}
async function syncClosedSessionState(err, actionLabel) {
if (!(err instanceof Error)) {
alert(`${actionLabel}: unknown error`);
return;
}
if (!currentSessionId || !/session is /i.test(err.message)) {
alert(`${actionLabel}: ${err.message}`);
return;
}
try {
const session = await apiFetchSession(currentSessionId);
applySessionStatus(session.status);
if (isClosedSessionStatus(session.status)) {
appendEvent({ type: "session_status", payload: { status: session.status } });
return;
}
} catch {
// Fall back to the original error if the refresh also fails.
}
alert(`${actionLabel}: ${err.message}`);
}
async function handleRoute() {
// Ensure we have a UUID
getUuid();
@@ -86,6 +157,8 @@ async function handleRoute() {
}
// Default: /code → dashboard
currentSessionId = null;
currentSessionStatus = null;
showPage("dashboard");
disconnectSSE();
renderDashboard();
@@ -172,9 +245,7 @@ async function renderSessionDetail(id) {
document.getElementById("session-id").textContent = session.id;
document.getElementById("session-env").textContent = session.environment_id || "";
document.getElementById("session-time").textContent = formatTime(session.created_at);
const badge = document.getElementById("session-status");
badge.textContent = session.status;
badge.className = `status-badge status-${statusClass(session.status)}`;
applySessionStatus(session.status);
} catch (err) {
alert("Failed to load session: " + err.message);
navigate("/code/");
@@ -201,7 +272,13 @@ async function renderSessionDetail(id) {
// Re-render any still-unresolved permission prompts from history
renderReplayPendingRequests();
connectSSE(id, appendEvent, lastSeqNum);
if (isClosedSessionStatus(currentSessionStatus)) {
appendEvent({ type: "session_status", payload: { status: currentSessionStatus } });
disconnectSSE();
return;
}
connectSSE(id, handleSessionEvent, lastSeqNum);
}
// ============================================================
@@ -237,28 +314,35 @@ function setupControlBar() {
}
async function doInterrupt() {
if (!currentSessionId) return;
if (!currentSessionId || isClosedSessionStatus(currentSessionStatus)) return;
const btn = document.getElementById("action-btn");
btn.disabled = true;
try {
await apiInterrupt(currentSessionId);
appendEvent({ type: "interrupt", payload: { message: "Session interrupted" } });
} catch (err) {
alert("Interrupt failed: " + err.message);
await syncClosedSessionState(err, "Interrupt failed");
} finally {
btn.disabled = false;
btn.disabled = isClosedSessionStatus(currentSessionStatus);
}
}
async function sendMessage() {
const input = document.getElementById("msg-input");
const text = input.value.trim();
if (!text || !currentSessionId) return;
if (!text || !currentSessionId || isClosedSessionStatus(currentSessionStatus)) return;
input.value = "";
const uuid = generateMessageUuid();
try {
await apiSendEvent(currentSessionId, { type: "user", content: text });
await apiSendEvent(currentSessionId, {
type: "user",
uuid,
content: text,
message: { content: text },
});
} catch (err) {
alert("Failed to send: " + err.message);
input.value = text;
await syncClosedSessionState(err, "Failed to send");
}
}

View File

@@ -150,6 +150,7 @@ nav {
.status-active, .status-running { background: var(--green-bg); color: var(--green); }
.status-idle { background: var(--yellow-bg); color: var(--yellow); }
.status-inactive { background: #F0ECE7; color: var(--text-secondary); }
.status-requires_action { background: var(--orange-bg); color: var(--orange); }
.status-archived { background: #F0ECE7; color: var(--text-secondary); }
.status-error { background: var(--red-bg); color: var(--red); }

View File

@@ -7,7 +7,7 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,400;12..96,500;12..96,600;12..96,700&family=Figtree:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap" />
<link rel="stylesheet" href="./style.css" />
<link rel="stylesheet" href="/code/style.css" />
</head>
<body>
<!-- Nav Bar -->
@@ -146,6 +146,6 @@
<!-- QR Libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
<script type="module" src="./app.js"></script>
<script type="module" src="/code/app.js"></script>
</body>
</html>

View File

@@ -13,11 +13,13 @@ import { processAssistantEvent } from "./task-panel.js";
const replayPendingRequests = new Map(); // request_id → event data (unresolved)
const replayRespondedRequests = new Set(); // request_ids that have a response
const renderedUserUuids = new Set();
/** Clear replay tracking state (call before each history load) */
export function resetReplayState() {
replayPendingRequests.clear();
replayRespondedRequests.clear();
renderedUserUuids.clear();
}
/** After replay finishes, render any still-unresolved permission prompts */
@@ -84,6 +86,59 @@ function formatAssistantContent(content) {
return html;
}
function getUserUuid(payload) {
if (!payload || typeof payload !== "object") return null;
if (typeof payload.uuid === "string" && payload.uuid) return payload.uuid;
if (payload.raw && typeof payload.raw === "object" && typeof payload.raw.uuid === "string" && payload.raw.uuid) {
return payload.raw.uuid;
}
return null;
}
function shouldRenderUserEvent(payload, direction, replay) {
const uuid = getUserUuid(payload);
if (uuid) {
if (renderedUserUuids.has(uuid)) return false;
renderedUserUuids.add(uuid);
return true;
}
// Legacy fallback with no uuid: keep the previous no-duplicate behavior.
// Live inbound user events without a uuid are most likely echoes of a web-
// sent message; replay keeps the prior "outbound only" rule as well.
return direction === "outbound";
}
function getMessageContentBlocks(payload) {
if (!payload || typeof payload !== "object") return [];
const msg = payload.message;
if (!msg || typeof msg !== "object" || !Array.isArray(msg.content)) return [];
return msg.content.filter((block) => block && typeof block === "object");
}
function renderEmbeddedToolUseBlocks(payload) {
return getMessageContentBlocks(payload)
.filter((block) => block.type === "tool_use")
.map((block) =>
renderToolUse({
tool_name: block.name || "tool",
tool_input: block.input || {},
}),
);
}
function renderEmbeddedToolResultBlocks(payload) {
return getMessageContentBlocks(payload)
.filter((block) => block.type === "tool_result")
.map((block) =>
renderToolResult({
content: block.content || "",
output: block.content || "",
is_error: !!block.is_error,
}),
);
}
// ============================================================
// Event Router
// ============================================================
@@ -103,26 +158,42 @@ export function appendEvent(data, { replay = false } = {}) {
// During history replay, only render messages & tools — skip interactive/stateful events
// Exception: unresolved permission/control requests are re-shown as pending prompts.
if (replay) {
let histEl;
const histEls = [];
switch (type) {
case "user":
if (direction === "outbound") histEl = renderUserMessage(payload, direction);
{
const toolResultEls = renderEmbeddedToolResultBlocks(payload);
if (toolResultEls.length > 0) {
histEls.push(...toolResultEls);
break;
}
if (shouldRenderUserEvent(payload, direction, true)) {
histEls.push(renderUserMessage(payload, direction));
}
}
break;
case "assistant":
{
const toolUseEls = renderEmbeddedToolUseBlocks(payload);
const text = extractText(payload);
if (text && text.trim()) histEl = renderAssistantMessage(payload);
if (text && text.trim()) histEls.push(renderAssistantMessage(payload));
if (toolUseEls.length > 0) histEls.push(...toolUseEls);
processAssistantEvent(payload);
}
break;
case "tool_use":
histEl = renderToolUse(payload);
histEls.push(renderToolUse(payload));
break;
case "tool_result":
histEl = renderToolResult(payload);
histEls.push(renderToolResult(payload));
break;
case "error":
histEl = renderSystemMessage(`Error: ${payload.message || payload.content || "Unknown error"}`);
histEls.push(renderSystemMessage(`Error: ${payload.message || payload.content || "Unknown error"}`));
break;
case "session_status":
if (payload.status === "archived" || payload.status === "inactive") {
histEls.push(renderSystemMessage(`Session ${payload.status}`));
}
break;
case "control_request":
case "permission_request":
@@ -149,32 +220,42 @@ export function appendEvent(data, { replay = false } = {}) {
default:
return;
}
if (histEl) {
for (const histEl of histEls) {
stream.appendChild(histEl);
stream.scrollTop = stream.scrollHeight;
}
return;
}
let el;
const els = [];
let needLoading = false;
switch (type) {
case "user":
// Skip inbound user messages — they're echoes of what we already sent
if (direction === "inbound") return;
el = renderUserMessage(payload, direction);
needLoading = true;
{
const toolResultEls = renderEmbeddedToolResultBlocks(payload);
if (toolResultEls.length > 0) {
els.push(...toolResultEls);
break;
}
if (!shouldRenderUserEvent(payload, direction, false)) return;
els.push(renderUserMessage(payload, direction));
needLoading = true;
}
break;
case "partial_assistant":
// Skip partial assistant — wait for the final "assistant" event
// to avoid blank/duplicate messages during streaming
return;
case "assistant":
removeLoading();
{
const toolUseEls = renderEmbeddedToolUseBlocks(payload);
const text = extractText(payload);
if (text && text.trim()) el = renderAssistantMessage(payload);
if (text && text.trim()) {
removeLoading();
els.push(renderAssistantMessage(payload));
}
if (toolUseEls.length > 0) els.push(...toolUseEls);
processAssistantEvent(payload);
}
break;
@@ -184,10 +265,10 @@ export function appendEvent(data, { replay = false } = {}) {
// Skip result — it just repeats the assistant message content
return;
case "tool_use":
el = renderToolUse(payload);
els.push(renderToolUse(payload));
break;
case "tool_result":
el = renderToolResult(payload);
els.push(renderToolResult(payload));
break;
case "control_request":
case "permission_request":
@@ -195,27 +276,27 @@ export function appendEvent(data, { replay = false } = {}) {
const toolName = payload.request.tool_name || "unknown";
const toolInput = payload.request.input || payload.request.tool_input || {};
if (toolName === "AskUserQuestion") {
el = renderAskUserQuestion({
els.push(renderAskUserQuestion({
request_id: payload.request_id || data.id,
tool_input: toolInput,
description: payload.request.description || "",
});
}));
} else if (toolName === "ExitPlanMode") {
el = renderExitPlanMode({
els.push(renderExitPlanMode({
request_id: payload.request_id || data.id,
tool_input: toolInput,
description: payload.request.description || "",
});
}));
} else {
el = renderPermissionRequest({
els.push(renderPermissionRequest({
request_id: payload.request_id || data.id,
tool_name: toolName,
tool_input: toolInput,
description: payload.request.description || "",
});
}));
}
} else {
el = renderSystemMessage(`Control: ${payload.request?.subtype || "unknown"}`);
els.push(renderSystemMessage(`Control: ${payload.request?.subtype || "unknown"}`));
}
break;
case "control_response":
@@ -229,16 +310,22 @@ export function appendEvent(data, { replay = false } = {}) {
const fullText = typeof payload === "string" ? payload : JSON.stringify(payload);
if (/connecting|waiting|initializing|Remote Control/i.test(msg + " " + fullText)) return;
if (!msg.trim()) return;
el = renderSystemMessage(msg);
els.push(renderSystemMessage(msg));
}
break;
case "error":
removeLoading();
el = renderSystemMessage(`Error: ${payload.message || payload.content || "Unknown error"}`);
els.push(renderSystemMessage(`Error: ${payload.message || payload.content || "Unknown error"}`));
break;
case "session_status":
if (payload.status === "archived" || payload.status === "inactive") {
removeLoading();
els.push(renderSystemMessage(`Session ${payload.status}`));
}
break;
case "interrupt":
removeLoading();
el = renderSystemMessage("Session interrupted");
els.push(renderSystemMessage("Session interrupted"));
break;
case "system":
// Skip raw system/init messages — they're noise
@@ -247,11 +334,11 @@ export function appendEvent(data, { replay = false } = {}) {
// Skip noise from bridge init
const raw = JSON.stringify(payload);
if (/Remote Control connecting/i.test(raw)) return;
el = renderSystemMessage(`${type}: ${truncate(raw, 200)}`);
els.push(renderSystemMessage(`${type}: ${truncate(raw, 200)}`));
}
}
if (el) {
for (const el of els) {
stream.appendChild(el);
stream.scrollTop = stream.scrollHeight;
}

View File

@@ -19,9 +19,14 @@ export function statusClass(status) {
active: "active",
running: "running",
idle: "idle",
inactive: "inactive",
requires_action: "requires_action",
archived: "archived",
error: "error",
};
return map[status] || "default";
}
export function isClosedSessionStatus(status) {
return status === "archived" || status === "inactive";
}