Skip to content

armgit / mso

Public Imported from GitHub
0

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.

feat(assistant): add search, rename, recency, and confirm-gated delete to thread drawer

Abdurrahman Fakhrulec2ca36c1b47
diff --git a/frontend/slices/assistant/components/thread-list-model.test.ts b/frontend/slices/assistant/components/thread-list-model.test.ts
new file mode 100644
index 00000000..fc24031e
--- /dev/null
+++ b/frontend/slices/assistant/components/thread-list-model.test.ts
@@ -0,0 +1,97 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { filterThreads, formatRelativeTime, sortThreads } from "./thread-list-model";
+
+const source = fs.readFileSync(path.join(__dirname, "thread-list.tsx"), "utf8");
+
+describe("filterThreads", () => {
+ const items = [
+ { id: "1", title: "Project Alpha discussion", updatedAt: 100 },
+ { id: "2", title: "Beta release checklist", updatedAt: 200 },
+ { id: "3", title: "ALPHABET test", updatedAt: 300 },
+ ];
+
+ it("returns all threads when query is empty or only whitespace", () => {
+ expect(filterThreads(items, "")).toEqual(items);
+ expect(filterThreads(items, " ")).toEqual(items);
+ });
+
+ it("filters threads case-insensitively by title substring", () => {
+ const alphaMatches = filterThreads(items, "alpha");
+ expect(alphaMatches.map((t) => t.id)).toEqual(["1", "3"]);
+
+ const betaMatches = filterThreads(items, "BETA");
+ expect(betaMatches.map((t) => t.id)).toEqual(["2"]);
+ });
+
+ it("returns an empty array when no titles match", () => {
+ expect(filterThreads(items, "gamma")).toEqual([]);
+ });
+});
+
+describe("sortThreads", () => {
+ it("sorts threads descending by updatedAt without mutating input", () => {
+ const original = [
+ { id: "old", title: "Old", updatedAt: 100 },
+ { id: "new", title: "New", updatedAt: 500 },
+ { id: "mid", title: "Mid", updatedAt: 300 },
+ ];
+ const clone = [...original];
+
+ const sorted = sortThreads(original);
+ expect(sorted.map((t) => t.id)).toEqual(["new", "mid", "old"]);
+ expect(original).toEqual(clone);
+ });
+
+ it("handles missing or zero timestamps gracefully", () => {
+ const items = [
+ { id: "zero", title: "Zero", updatedAt: 0 },
+ { id: "has_time", title: "Has Time", updatedAt: 50 },
+ { id: "no_time", title: "No Time" as unknown as number, updatedAt: undefined as unknown as number },
+ ];
+ const sorted = sortThreads(items);
+ expect(sorted[0].id).toBe("has_time");
+ });
+});
+
+describe("formatRelativeTime", () => {
+ const now = 1_000_000_000;
+
+ it("returns 'just now' for non-positive or future timestamps", () => {
+ expect(formatRelativeTime(0, now)).toBe("just now");
+ expect(formatRelativeTime(-500, now)).toBe("just now");
+ expect(formatRelativeTime(now + 10_000, now)).toBe("just now");
+ });
+
+ it("returns 'just now' within the first minute (< 60s)", () => {
+ expect(formatRelativeTime(now, now)).toBe("just now");
+ expect(formatRelativeTime(now - 30_000, now)).toBe("just now");
+ expect(formatRelativeTime(now - 59_999, now)).toBe("just now");
+ });
+
+ it("formats minute boundary correctly", () => {
+ expect(formatRelativeTime(now - 60_000, now)).toBe("1m ago");
+ expect(formatRelativeTime(now - 120_000, now)).toBe("2m ago");
+ expect(formatRelativeTime(now - 3_599_999, now)).toBe("59m ago");
+ });
+
+ it("formats hour boundary correctly", () => {
+ expect(formatRelativeTime(now - 3_600_000, now)).toBe("1h ago");
+ expect(formatRelativeTime(now - 7_200_000, now)).toBe("2h ago");
+ expect(formatRelativeTime(now - 86_399_999, now)).toBe("23h ago");
+ });
+
+ it("formats day boundary correctly", () => {
+ expect(formatRelativeTime(now - 86_400_000, now)).toBe("1d ago");
+ expect(formatRelativeTime(now - 172_800_000, now)).toBe("2d ago");
+ });
+});
+
+describe("thread list deletion confirmation", () => {
+ it("gates thread deletion behind a confirmation step rather than immediate delete", () => {
+ expect(source).toContain("confirmDeleteId");
+ expect(source).toContain("Confirm");
+ expect(source).not.toContain("onClick={() => del(t.id)}");
+ });
+});
diff --git a/frontend/slices/assistant/components/thread-list-model.ts b/frontend/slices/assistant/components/thread-list-model.ts
new file mode 100644
index 00000000..2816d9c1
--- /dev/null
+++ b/frontend/slices/assistant/components/thread-list-model.ts
@@ -0,0 +1,43 @@
+export interface ThreadSummaryItem {
+ id: string;
+ title: string;
+ updatedAt: number;
+}
+
+/**
+ * Filter a list of threads by search query against their title (case-insensitive).
+ * An empty or whitespace-only query returns the full list.
+ */
+export function filterThreads<T extends { title: string }>(list: T[], query: string): T[] {
+ const trimmed = query.trim().toLowerCase();
+ if (!trimmed) return list;
+ return list.filter((t) => t.title.toLowerCase().includes(trimmed));
+}
+
+/**
+ * Sort threads in descending order by updatedAt (most recent first).
+ * Does not mutate the original list.
+ */
+export function sortThreads<T extends { updatedAt?: number }>(list: T[]): T[] {
+ return [...list].sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
+}
+
+/**
+ * Formats a timestamp into a human-readable relative time string.
+ * Boundaries:
+ * - < 1 minute (or future/non-positive): "just now"
+ * - < 1 hour: "<m>m ago"
+ * - < 24 hours: "<h>h ago"
+ * - >= 24 hours: "<d>d ago"
+ */
+export function formatRelativeTime(updatedAt: number, nowMs: number = Date.now()): string {
+ if (!updatedAt || updatedAt <= 0) return "just now";
+ const diffMs = nowMs - updatedAt;
+ if (diffMs < 60_000) return "just now";
+ const minutes = Math.floor(diffMs / 60_000);
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ return `${days}d ago`;
+}
diff --git a/frontend/slices/assistant/components/thread-list.tsx b/frontend/slices/assistant/components/thread-list.tsx
index a2daae9a..f4e6a5c7 100644
--- a/frontend/slices/assistant/components/thread-list.tsx
+++ b/frontend/slices/assistant/components/thread-list.tsx
@@ -5,13 +5,15 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sh
import { useShellDesign } from "@/features/appshell";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
-import { Trash2, Plus } from "lucide-react";
+import { Input } from "@/components/ui/input";
+import { Trash2, Plus, Pencil, Check, X } from "lucide-react";
+import { filterThreads, formatRelativeTime, sortThreads } from "./thread-list-model";
type Summary = { id: string; title: string; updatedAt: number };
type FullThread = { id: string; createdAt: number; messages: unknown[]; history: unknown[] };
// Left drawer of saved chats: resume loads the full thread back into the panel,
-// New starts a fresh one, trash deletes. Reads /api/threads (YAML store).
+// New starts a fresh one, trash deletes (confirm-gated), pencil renames. Reads /api/threads.
export function ThreadList({
open,
onOpenChange,
@@ -24,29 +26,80 @@ export function ThreadList({
onNew: () => void;
}) {
const [threads, setThreads] = useState<Summary[]>([]);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [editingTitle, setEditingTitle] = useState("");
+ const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
const design = useShellDesign();
const load = useCallback(() => {
fetch("/api/threads", { cache: "no-store" })
- .then((r) => (r.ok ? r.json() : { threads: [] }))
- .then((d) => setThreads(d.threads ?? []))
- .catch(() => setThreads([]));
+ .then((r) => { if (!r.ok) throw new Error("load_failed"); return r.json(); })
+ .then((d) => { setThreads(d.threads ?? []); setError(null); })
+ .catch(() => setError("Failed to load chats"));
}, []);
+
useEffect(() => {
- if (open) load();
+ if (open) {
+ load();
+ setEditingId(null);
+ setConfirmDeleteId(null);
+ setError(null);
+ }
}, [open, load]);
async function resume(id: string) {
- const r = await fetch(`/api/threads?id=${encodeURIComponent(id)}`, { cache: "no-store" });
- if (!r.ok) return;
- onResume((await r.json()) as FullThread);
- onOpenChange(false);
+ try {
+ const r = await fetch(`/api/threads?id=${encodeURIComponent(id)}`, { cache: "no-store" });
+ if (!r.ok) { setError("Failed to resume chat"); return; }
+ setError(null);
+ onResume((await r.json()) as FullThread);
+ onOpenChange(false);
+ } catch {
+ setError("Failed to resume chat");
+ }
}
+
async function del(id: string) {
- await fetch(`/api/threads?id=${encodeURIComponent(id)}`, { method: "DELETE" }).catch(() => {});
- load();
+ try {
+ const r = await fetch(`/api/threads?id=${encodeURIComponent(id)}`, { method: "DELETE" });
+ if (!r.ok) { setError("Failed to delete chat"); return; }
+ setError(null);
+ setConfirmDeleteId(null);
+ load();
+ } catch {
+ setError("Failed to delete chat");
+ }
+ }
+
+ function startRename(t: Summary) {
+ setEditingId(t.id);
+ setEditingTitle(t.title);
+ setConfirmDeleteId(null);
+ setError(null);
}
+ async function saveRename(id: string) {
+ const clean = editingTitle.trim();
+ if (!clean) { setEditingId(null); return; }
+ try {
+ const r = await fetch("/api/threads", {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ id, title: clean }),
+ });
+ if (!r.ok) { setError("Failed to rename chat"); return; }
+ setEditingId(null);
+ setError(null);
+ load();
+ } catch {
+ setError("Failed to rename chat");
+ }
+ }
+
+ const visibleThreads = sortThreads(filterThreads(threads, searchQuery));
+
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
@@ -54,48 +107,62 @@ export function ThreadList({
data-shell-id={design.id}
data-shell-family={design.family}
side="left"
- className={cn(
- "w-80 gap-0 p-0",
- design.family === "apple" && "rounded-r-[22px]",
- design.family === "material" && "rounded-r-[28px]",
- )}
+ className={cn("w-80 gap-0 p-0", design.family === "apple" && "rounded-r-[22px]", design.family === "material" && "rounded-r-[28px]")}
>
<SheetHeader className="flex-row items-center justify-between space-y-0 border-b border-border p-3">
<SheetTitle>Chats</SheetTitle>
- <Button
- size="sm"
- variant="ghost"
- className="[@media(pointer:coarse)]:min-h-[44px]"
- onClick={() => {
- onNew();
- onOpenChange(false);
- }}
- >
+ <Button size="sm" variant="ghost" className="[@media(pointer:coarse)]:min-h-[44px]" onClick={() => { onNew(); onOpenChange(false); }}>
<Plus className="size-4" /> New
</Button>
</SheetHeader>
+ <div className="border-b border-border p-2">
+ <Input value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} placeholder="Search chats..." aria-label="Search chats" className="h-8 text-xs" />
+ </div>
+ {error ? (
+ <div role="alert" className="flex items-center justify-between bg-destructive/10 px-3 py-1.5 text-xs text-destructive">
+ <span>{error}</span>
+ <button type="button" onClick={() => setError(null)} className="ml-2 hover:opacity-75" aria-label="Dismiss error">✕</button>
+ </div>
+ ) : null}
<div className="min-h-0 flex-1 overflow-auto">
{threads.length === 0 ? (
<p className="p-4 text-sm text-muted-foreground">No saved chats yet.</p>
+ ) : visibleThreads.length === 0 ? (
+ <p className="p-4 text-sm text-muted-foreground">No matching chats found.</p>
) : (
- threads.map((t) => (
- <div key={t.id} className="flex items-center border-b border-border">
- <button
- type="button"
- onClick={() => resume(t.id)}
- className="min-w-0 flex-1 truncate px-3 py-2.5 text-left text-sm hover:bg-[var(--hover-strong)] [@media(pointer:coarse)]:min-h-[44px]"
- >
- {t.title}
- </button>
- <Button
- size="icon"
- variant="ghost"
- aria-label={`Delete ${t.title}`}
- onClick={() => del(t.id)}
- className="mr-1 size-7 shrink-0 text-muted-foreground hover:text-destructive [@media(pointer:coarse)]:size-[44px]"
- >
- <Trash2 className="size-4" />
- </Button>
+ visibleThreads.map((t) => (
+ <div key={t.id} className="border-b border-border">
+ {confirmDeleteId === t.id ? (
+ <div className="flex items-center justify-between gap-2 bg-destructive/10 px-3 py-2 text-xs">
+ <span className="truncate text-destructive font-medium">Delete chat?</span>
+ <div className="flex items-center gap-1 shrink-0">
+ <Button size="sm" variant="destructive" className="h-6 px-2 text-xs" onClick={() => void del(t.id)}>Confirm</Button>
+ <Button size="sm" variant="ghost" className="h-6 px-2 text-xs" onClick={() => setConfirmDeleteId(null)}>Cancel</Button>
+ </div>
+ </div>
+ ) : editingId === t.id ? (
+ <div className="flex items-center gap-1 px-2 py-1.5">
+ <Input
+ value={editingTitle}
+ onChange={(e) => setEditingTitle(e.target.value)}
+ onKeyDown={(e) => { if (e.key === "Enter") void saveRename(t.id); if (e.key === "Escape") setEditingId(null); }}
+ autoFocus
+ className="h-7 text-xs"
+ aria-label="Rename chat"
+ />
+ <Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Save title" onClick={() => void saveRename(t.id)}><Check className="size-3.5" /></Button>
+ <Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Cancel rename" onClick={() => setEditingId(null)}><X className="size-3.5" /></Button>
+ </div>
+ ) : (
+ <div className="flex items-center">
+ <button type="button" onClick={() => resume(t.id)} className="min-w-0 flex-1 px-3 py-2 text-left hover:bg-[var(--hover-strong)] [@media(pointer:coarse)]:min-h-[44px]">
+ <div className="truncate text-sm font-medium">{t.title}</div>
+ <div className="text-xs text-muted-foreground">{formatRelativeTime(t.updatedAt)}</div>
+ </button>
+ <Button size="icon" variant="ghost" aria-label={`Rename ${t.title}`} onClick={() => startRename(t)} className="size-7 shrink-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:size-[44px]"><Pencil className="size-3.5" /></Button>
+ <Button size="icon" variant="ghost" aria-label={`Delete ${t.title}`} onClick={() => { setConfirmDeleteId(t.id); setEditingId(null); }} className="mr-1 size-7 shrink-0 text-muted-foreground hover:text-destructive [@media(pointer:coarse)]:size-[44px]"><Trash2 className="size-4" /></Button>
+ </div>
+ )}
</div>
))
)}