Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(api): add PATCH endpoint to rename threads
Abdurrahman Fakhrul1447f98cae90
diff --git a/app/api/threads/route.test.ts b/app/api/threads/route.test.tsnew file mode 100644index 00000000..65c117fe--- /dev/null+++ b/app/api/threads/route.test.ts@@ -0,0 +1,130 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import os from "node:os";+import path from "node:path";++let mockSessionAuthorized = true;++const stableContext = {+ session: { device_id: "test-device", issued_at: 1, expires_at: 2, cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" },+ device: { label: "test owner", approvedAt: 1, role: "owner" as const },+ role: "owner" as const,+};++vi.mock("@/lib/auth/require-session", () => ({+ getSessionContext: vi.fn(async () => (mockSessionAuthorized ? stableContext : null)),+ requireSession: vi.fn(async () => mockSessionAuthorized),+}));++process.env.OS_THREADS_DIR = path.join(os.tmpdir(), `mso-threads-route-test-${process.pid}`);++const { GET, POST, PATCH } = await import("./route");+const { getThread, saveThread } = await import("@/lib/ai/threads");++function patchRequest(body: unknown) {+ return new NextRequest("http://localhost/api/threads", {+ method: "PATCH",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });+}++describe("/api/threads route", () => {+ beforeEach(() => {+ mockSessionAuthorized = true;+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("enforces owner session on PATCH", async () => {+ mockSessionAuthorized = false;+ const res = await PATCH(patchRequest({ id: "any", title: "any" }));+ expect(res.status).toBe(401);+ const data = await res.json();+ expect(data.error).toBe("Unauthorized");+ });++ it("renames only the title and preserves messages and history", async () => {+ const threadId = "thread_patch_ok";+ await saveThread({+ id: threadId,+ title: "Original Title",+ createdAt: 5000,+ updatedAt: 5000,+ messages: [{ role: "user", text: "hello world" }],+ history: [{ role: "user", text: "hello" }],+ });++ const res = await PATCH(patchRequest({ id: threadId, title: "Updated Title" }));+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.ok).toBe(true);+ expect(body.thread.title).toBe("Updated Title");+ expect(body.thread.id).toBe(threadId);++ const reloaded = await getThread(threadId);+ expect(reloaded?.title).toBe("Updated Title");+ expect(reloaded?.messages).toEqual([{ role: "user", text: "hello world" }]);+ expect(reloaded?.history).toEqual([{ role: "user", text: "hello" }]);+ expect(reloaded?.createdAt).toBe(5000);+ });++ it("rejects invalid id including path traversal and symbols", async () => {+ const invalidIds = ["../escaped", "has space", "bad@id", "", "id/slash"];+ for (const id of invalidIds) {+ const res = await PATCH(patchRequest({ id, title: "Valid Title" }));+ expect(res.status).toBe(400);+ const data = await res.json();+ expect(data.error).toBe("invalid id");+ }+ });++ it("rejects over-long id exceeding 64 characters", async () => {+ const longId = "a".repeat(65);+ const res = await PATCH(patchRequest({ id: longId, title: "Valid Title" }));+ expect(res.status).toBe(400);+ const data = await res.json();+ expect(data.error).toBe("invalid id");+ });++ it("rejects invalid or empty title", async () => {+ const invalidTitles = ["", " ", null, 123, undefined];+ for (const title of invalidTitles) {+ const res = await PATCH(patchRequest({ id: "valid_id", title }));+ expect(res.status).toBe(400);+ const data = await res.json();+ expect(data.error).toBe("invalid title");+ }+ });++ it("clamps over-long title to 120 characters", async () => {+ const threadId = "thread_clamp_title";+ await saveThread({+ id: threadId,+ title: "Before Clamp",+ createdAt: 1000,+ updatedAt: 1000,+ messages: [{ role: "user", text: "clamp test" }],+ history: [],+ });++ const overLongTitle = "T".repeat(200);+ const res = await PATCH(patchRequest({ id: threadId, title: overLongTitle }));+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.thread.title).toBe("T".repeat(120));+ expect(body.thread.title.length).toBe(120);++ const reloaded = await getThread(threadId);+ expect(reloaded?.title).toBe("T".repeat(120));+ });++ it("returns 404 when renaming non-existent thread", async () => {+ const res = await PATCH(patchRequest({ id: "thread_missing", title: "New Name" }));+ expect(res.status).toBe(404);+ const data = await res.json();+ expect(data.error).toBe("not_found");+ });+});diff --git a/app/api/threads/route.ts b/app/api/threads/route.tsindex 962111d7..2ba909b3 100644--- a/app/api/threads/route.ts+++ b/app/api/threads/route.ts@@ -1,15 +1,18 @@import { NextRequest, NextResponse } from "next/server";import { requireSession } from "@/lib/auth/require-session";-import { listThreads, getThread, saveThread, deleteThread, type ChatThread } from "@/lib/ai/threads";+import { listThreads, getThread, saveThread, deleteThread, renameThread, type ChatThread } from "@/lib/ai/threads";export const runtime = "nodejs";export const dynamic = "force-dynamic";+const THREAD_ID = /^[A-Za-z0-9_-]{1,64}$/;+// Persistent Alfa chat threads (YAML files in ~/.mso/threads/). Session-gated.// GET → list summaries// GET ?id=<id> → one full thread// POST { id, title?, createdAt?, messages[], history[] } → save (create/update)// DELETE ?id=<id> → remove+// PATCH { id, title } → rename threadexport async function GET(req: NextRequest) {if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });const id = req.nextUrl.searchParams.get("id");@@ -52,3 +55,31 @@ export async function DELETE(req: NextRequest) {await deleteThread(id);return NextResponse.json({ ok: true });}++export async function PATCH(req: NextRequest) {+ if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ let body: { id?: unknown; title?: unknown };+ try {+ body = await req.json();+ } catch {+ return NextResponse.json({ error: "bad_request" }, { status: 400 });+ }+ if (!body || typeof body !== "object") {+ return NextResponse.json({ error: "bad_request" }, { status: 400 });+ }+ const id = typeof body.id === "string" ? body.id : "";+ if (!id || !THREAD_ID.test(id)) {+ return NextResponse.json({ error: "invalid id" }, { status: 400 });+ }+ if (typeof body.title !== "string" || !body.title.trim()) {+ return NextResponse.json({ error: "invalid title" }, { status: 400 });+ }+ const title = body.title.trim().slice(0, 120);+ try {+ const thread = await renameThread(id, title);+ if (!thread) return NextResponse.json({ error: "not_found" }, { status: 404 });+ return NextResponse.json({ ok: true, thread });+ } catch (err) {+ return NextResponse.json({ error: err instanceof Error ? err.message : "bad_request" }, { status: 400 });+ }+}