Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(notfair-cmo): chat thread rail with rename, pin, and delete

Yuting Zhong2b9064a860e8
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
index 6901f560..2011f755 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
@@ -14,8 +14,7 @@ import { readTranscriptTail } from "@/server/sessions/transcript-tail";
import { LiveTranscript } from "@/components/live-transcript";
import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";
import { McpFlashBanner } from "@/components/mcp-flash-banner";
-import { ThreadSelector, type SessionLite } from "@/components/thread-selector";
-import { NewChatButton } from "@/components/new-chat-button";
+import { ChatThreadRail, type SessionLite } from "@/components/chat-thread-rail";
type Params = { agent: string; thread: string; project: string };
type Search = { mcp_connected?: string; mcp_error?: string };
@@ -56,12 +55,14 @@ export default async function AgentChatThreadPage({
sessionKey: s.sessionKey,
lastInteractionAt: s.lastInteractionAt,
pending: s.pending,
+ title: s.title,
+ pinned: s.pinned,
origin: origins.get(s.label),
}));
- // For the dropdown: surface the pending thread at the top so the user sees
+ // For the rail: surface the pending thread at the top so the user sees
// it's "selected" even before sending the first message.
- const sessionsForDropdown: SessionLite[] = existing
+ const sessionsForRail: SessionLite[] = existing
? enriched
: [
{
@@ -112,37 +113,30 @@ export default async function AgentChatThreadPage({
<GoogleAdsMcpBanner status={googleAdsMcpStatus} projectSlug={projectSlug} />
)}
- <div className="flex items-center justify-between bg-background/80 px-6 py-2 backdrop-blur">
- <div className="text-xs text-muted-foreground">
- {sessionsForDropdown.length === 0
- ? "No threads yet"
- : `${sessionsForDropdown.length} thread${sessionsForDropdown.length === 1 ? "" : "s"}`}
- </div>
- <div className="flex items-center gap-2">
- <ThreadSelector
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- sessions={sessionsForDropdown}
- activeSessionId={threadId}
- />
- <NewChatButton projectSlug={projectSlug} agentSlug={agentSlug} />
- </div>
- </div>
-
- <div className="min-h-0 flex-1">
- <LiveTranscript
- key={threadId}
+ {/* Same two-pane shape as the task workspace: thread rail on the
+ left (New chat on top), live transcript on the right. */}
+ <div className="flex min-h-0 flex-1">
+ <ChatThreadRail
projectSlug={projectSlug}
agentSlug={agentSlug}
- agentDisplayName={resolved.name}
- threadId={threadId}
- sessionKey={sessionKey}
- initialEvents={initialEvents}
- initialByteOffset={initialByteOffset}
- autoKickoff={autoKickoff}
- mcpCatalog={mcpCatalog}
- modelOptions={modelOptions}
+ sessions={sessionsForRail}
+ activeSessionId={threadId}
/>
+ <section className="flex min-w-0 flex-1 flex-col">
+ <LiveTranscript
+ key={threadId}
+ projectSlug={projectSlug}
+ agentSlug={agentSlug}
+ agentDisplayName={resolved.name}
+ threadId={threadId}
+ sessionKey={sessionKey}
+ initialEvents={initialEvents}
+ initialByteOffset={initialByteOffset}
+ autoKickoff={autoKickoff}
+ mcpCatalog={mcpCatalog}
+ modelOptions={modelOptions}
+ />
+ </section>
</div>
</div>
);
diff --git a/notfair-cmo/src/app/globals.css b/notfair-cmo/src/app/globals.css
index 9abe124a..ad4368db 100644
--- a/notfair-cmo/src/app/globals.css
+++ b/notfair-cmo/src/app/globals.css
@@ -297,7 +297,10 @@
width: 100%;
}
.ns-tile:hover { background: hsl(var(--notfair-hover)); }
- .ns-tile:disabled { cursor: not-allowed; opacity: 0.6; }
+ /* [aria-disabled] variant: the connect tile is a div[role=button] now
+ (a real <button> can't legally contain the "Select account"
+ sub-action button), so :disabled never matches it. */
+ .ns-tile:disabled, .ns-tile[aria-disabled="true"] { cursor: not-allowed; opacity: 0.6; }
.ns-tile-glyph {
@apply grid place-items-center flex-shrink-0 font-semibold uppercase;
width: 32px; height: 32px; border-radius: 8px;
@@ -634,6 +637,27 @@
.ns-dot-err { background: hsl(0 72% 51%); }
.ns-dot-mute { background: hsl(var(--notfair-border-strong)); }
+ /* Thread-rail marquee — single-line title that slides horizontally on
+ row hover to reveal overflow. The row's mouseenter handler measures
+ the overflow and sets --ns-marquee-shift in px (0 when the title
+ fits); CSS only animates it: slow reveal on hover, quick snap-back
+ on leave. (Kept JS-measured: container-query units in transform got
+ silently dropped by the CSS pipeline.) */
+ .ns-marquee {
+ overflow: hidden;
+ white-space: nowrap;
+ }
+ .ns-marquee > span {
+ display: inline-block;
+ min-width: 100%;
+ transform: translateX(0);
+ transition: transform 0.25s ease-out;
+ }
+ .ns-thread-row:hover .ns-marquee > span {
+ transform: translateX(var(--ns-marquee-shift, 0px));
+ transition: transform var(--ns-marquee-duration, 2s) linear 0.35s;
+ }
+
/* Pulsing live dot — for "running" / "live" indicators. */
.ns-dot-live {
background: hsl(var(--notfair-accent));
diff --git a/notfair-cmo/src/components/agent-task-workspace.tsx b/notfair-cmo/src/components/agent-task-workspace.tsx
index 2525dd5c..a8d2330c 100644
--- a/notfair-cmo/src/components/agent-task-workspace.tsx
+++ b/notfair-cmo/src/components/agent-task-workspace.tsx
@@ -134,7 +134,7 @@ export function AgentTaskWorkspace({
workspace. The per-thread LiveTranscript polling still handles
the open transcript. */}
{/* ── Left pane: task list ─────────────────────────────────────── */}
- <aside className="flex w-80 shrink-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
+ <aside className="flex w-72 shrink-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
{proposedCount > 0 && (
<div className="px-4 py-3">
<StartAllTasksButton
@@ -480,10 +480,6 @@ function TaskRow({
onSelect: () => void;
}) {
const isRunning = task.status === "working";
- const isInFlight =
- task.status === "working" ||
- task.status === "proposed" ||
- task.status === "approved";
return (
<button
type="button"
@@ -525,9 +521,10 @@ function TaskRow({
className={cn(
// leading-4 (1rem) × 2 lines = min-h-8: one-line titles reserve
// the second line's space so every row is the same height.
+ // Unselected rows use the same text tone as chat-rail rows —
+ // terminal tasks are no longer dimmed (the glyph carries status).
"ml-6 mt-0.5 line-clamp-2 min-h-8 text-xs leading-4",
selected ? "font-medium text-foreground" : "text-foreground/90",
- !isInFlight && task.status !== "working" && "text-muted-foreground",
)}
>
{task.title ?? task.brief.slice(0, 160)}
diff --git a/notfair-cmo/src/components/chat-thread-rail.test.tsx b/notfair-cmo/src/components/chat-thread-rail.test.tsx
new file mode 100644
index 00000000..b6373adb
--- /dev/null
+++ b/notfair-cmo/src/components/chat-thread-rail.test.tsx
@@ -0,0 +1,160 @@
+// @vitest-environment jsdom
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { render, screen, cleanup } from "@testing-library/react";
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
+}));
+
+vi.mock("@/server/actions/chat-threads", () => ({
+ renameThreadAction: vi.fn(async () => ({ ok: true })),
+ setThreadPinnedAction: vi.fn(async () => ({ ok: true })),
+ deleteThreadAction: vi.fn(async () => ({ ok: true })),
+}));
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+import { ChatThreadRail, type SessionLite } from "./chat-thread-rail";
+
+function makeSession(overrides: Partial<SessionLite> = {}): SessionLite {
+ return {
+ sessionId: "aaaa1111-0000-0000-0000-000000000000",
+ label: "aaaa1111",
+ sessionKey: "aaaa1111",
+ lastInteractionAt: Date.now(),
+ pending: false,
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("ChatThreadRail", () => {
+ it("renders the New chat button on top, text-only rows, and hides task threads", () => {
+ render(
+ <ChatThreadRail
+ projectSlug="demo"
+ agentSlug="cmo-greg"
+ activeSessionId="aaaa1111-0000-0000-0000-000000000000"
+ sessions={[
+ makeSession({
+ origin: { kind: "chat", preview: "What should we launch first?" },
+ }),
+ // Task-kickoff threads live on the Tasks tab — not here.
+ makeSession({
+ sessionId: "bbbb2222-0000-0000-0000-000000000000",
+ label: "bbbb2222",
+ sessionKey: "bbbb2222",
+ origin: { kind: "task", display_id: "demo-1", title: "Audit the account" },
+ }),
+ ]}
+ />,
+ );
+ expect(screen.getByRole("button", { name: /New chat/i })).toBeInTheDocument();
+ expect(screen.getAllByRole("listitem")).toHaveLength(1);
+ expect(screen.getByText("What should we launch first?")).toBeInTheDocument();
+ expect(screen.queryByText(/Audit the account/)).not.toBeInTheDocument();
+ // Text only — no thread-id line on the rows.
+ expect(screen.queryByText("aaaa1111")).not.toBeInTheDocument();
+ });
+
+ it("links each row to its thread and marks the active one", () => {
+ render(
+ <ChatThreadRail
+ projectSlug="demo"
+ agentSlug="cmo-greg"
+ activeSessionId="aaaa1111-0000-0000-0000-000000000000"
+ sessions={[
+ makeSession({ origin: { kind: "chat", preview: "alpha" } }),
+ makeSession({
+ sessionId: "bbbb2222-0000-0000-0000-000000000000",
+ label: "bbbb2222",
+ sessionKey: "bbbb2222",
+ origin: { kind: "chat", preview: "beta" },
+ }),
+ ]}
+ />,
+ );
+ const active = screen.getByText("alpha").closest("a");
+ const other = screen.getByText("beta").closest("a");
+ expect(active).toHaveAttribute(
+ "href",
+ "/demo/agents/cmo-greg/chat/aaaa1111-0000-0000-0000-000000000000",
+ );
+ expect(active).toHaveAttribute("aria-current", "true");
+ expect(other).not.toHaveAttribute("aria-current");
+ });
+
+ it("prefers the user-set title and marks pinned threads", () => {
+ render(
+ <ChatThreadRail
+ projectSlug="demo"
+ agentSlug="cmo-greg"
+ activeSessionId="x"
+ sessions={[
+ makeSession({
+ title: "Q4 planning",
+ pinned: true,
+ origin: { kind: "chat", preview: "ignored preview" },
+ }),
+ ]}
+ />,
+ );
+ expect(screen.getByText("Q4 planning")).toBeInTheDocument();
+ expect(screen.queryByText("ignored preview")).not.toBeInTheDocument();
+ expect(screen.getByLabelText("Pinned")).toBeInTheDocument();
+ });
+
+ it("opens the ⋮ menu with Rename / Pin / Delete", async () => {
+ const { fireEvent } = await import("@testing-library/react");
+ render(
+ <ChatThreadRail
+ projectSlug="demo"
+ agentSlug="cmo-greg"
+ activeSessionId="x"
+ sessions={[makeSession({ origin: { kind: "chat", preview: "alpha" } })]}
+ />,
+ );
+ const trigger = screen.getByRole("button", { name: /Thread actions for alpha/i });
+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
+ fireEvent.click(trigger);
+ expect(await screen.findByText("Rename")).toBeInTheDocument();
+ expect(screen.getByText("Pin")).toBeInTheDocument();
+ expect(screen.getByText("Delete")).toBeInTheDocument();
+ // Delete routes through an explicit confirm dialog.
+ fireEvent.click(screen.getByText("Delete"));
+ expect(await screen.findByText("Delete thread?")).toBeInTheDocument();
+ });
+
+ it("labels pending threads as new and shows the empty state without threads", () => {
+ const { unmount } = render(
+ <ChatThreadRail
+ projectSlug="demo"
+ agentSlug="cmo-greg"
+ activeSessionId="cccc3333-0000-0000-0000-000000000000"
+ sessions={[
+ makeSession({
+ sessionId: "cccc3333-0000-0000-0000-000000000000",
+ pending: true,
+ }),
+ ]}
+ />,
+ );
+ expect(screen.getByText("New thread")).toBeInTheDocument();
+ unmount();
+
+ render(
+ <ChatThreadRail
+ projectSlug="demo"
+ agentSlug="cmo-greg"
+ activeSessionId="x"
+ sessions={[]}
+ />,
+ );
+ expect(screen.getByText(/No threads yet/)).toBeInTheDocument();
+ });
+});
diff --git a/notfair-cmo/src/components/chat-thread-rail.tsx b/notfair-cmo/src/components/chat-thread-rail.tsx
new file mode 100644
index 00000000..2359d899
--- /dev/null
+++ b/notfair-cmo/src/components/chat-thread-rail.tsx
@@ -0,0 +1,359 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { MoreVertical, Pin, PinOff, Plus } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Input } from "@/components/ui/input";
+import {
+ deleteThreadAction,
+ renameThreadAction,
+ setThreadPinnedAction,
+} from "@/server/actions/chat-threads";
+import { cn } from "@/lib/utils";
+import { projectHref } from "@/lib/project-href";
+
+/**
+ * Left rail for the agent chat page — mirrors the task workspace's rail:
+ * a full-width "New chat" row on top, then a flat scrollable list of
+ * threads. Rows are one line high; hovering a row slides overflowing
+ * titles horizontally (marquee) to reveal the rest, and surfaces a ⋮
+ * menu with Rename / Pin / Delete.
+ */
+
+export type SessionOriginLite =
+ | { kind: "task"; display_id: string; title: string | null }
+ | { kind: "cron"; cron_name: string }
+ | { kind: "chat"; preview: string };
+
+export type SessionLite = {
+ sessionId: string;
+ label: string;
+ sessionKey: string;
+ lastInteractionAt: number;
+ pending: boolean;
+ /** User-set display title (rename). Overrides the derived preview. */
+ title?: string | null;
+ /** True when pinned — the server sorts pinned threads first. */
+ pinned?: boolean;
+ /**
+ * Server-classified origin. Drives the row title so users see a cron
+ * name or first-message preview instead of a raw UUID. Undefined for
+ * pending threads (no transcript yet).
+ */
+ origin?: SessionOriginLite;
+};
+
+function displayTitle(s: SessionLite): string {
+ if (s.title) return s.title;
+ if (s.pending) return "New thread";
+ if (s.origin?.kind === "cron") return s.origin.cron_name;
+ if (s.origin?.kind === "chat" && s.origin.preview) return s.origin.preview;
+ if (s.label === "main") return "Main thread";
+ return s.label;
+}
+
+/** Row shell shared by thread rows and the New chat button. */
+const ROW_CLASS =
+ "ns-thread-row group/row relative mx-2 block w-[calc(100%-1rem)] rounded-md px-2.5 py-2 text-left text-xs leading-4 transition-colors hover:bg-sidebar-accent focus-visible:outline-none focus-visible:bg-sidebar-accent";
+
+/**
+ * Measure how far the row's title overflows its clip box and stash it as
+ * a CSS var; the .ns-marquee hover rule animates the text by exactly that
+ * distance. Runs on mouseenter so it always reflects current widths.
+ */
+function primeMarquee(e: React.MouseEvent<HTMLElement>) {
+ const clip = e.currentTarget.querySelector<HTMLElement>(".ns-marquee");
+ const text = clip?.firstElementChild as HTMLElement | null;
+ if (!clip || !text) return;
+ const overflow = Math.max(0, text.scrollWidth - clip.clientWidth);
+ text.style.setProperty("--ns-marquee-shift", `-${overflow}px`);
+ // Constant reading speed regardless of title length — a fixed duration
+ // made long titles whip past.
+ const PX_PER_SECOND = 25;
+ text.style.setProperty(
+ "--ns-marquee-duration",
+ `${Math.max(1.5, overflow / PX_PER_SECOND)}s`,
+ );
+}
+
+export function ChatThreadRail({
+ projectSlug,
+ agentSlug,
+ sessions,
+ activeSessionId,
+}: {
+ projectSlug: string;
+ agentSlug: string;
+ sessions: SessionLite[];
+ activeSessionId: string;
+}) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [renaming, setRenaming] = useState<SessionLite | null>(null);
+ const [deleting, setDeleting] = useState<SessionLite | null>(null);
+
+ // Task-kickoff threads belong to the Tasks tab (each task page shows
+ // its own transcript) — listing them here would double-surface them.
+ const visible = sessions.filter((s) => s.origin?.kind !== "task");
+
+ function newThread() {
+ const id = crypto.randomUUID();
+ startTransition(() =>
+ router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${id}`)),
+ );
+ }
+
+ function togglePin(s: SessionLite) {
+ startTransition(async () => {
+ const r = await setThreadPinnedAction({
+ projectSlug,
+ agentSlug,
+ threadLabel: s.sessionId,
+ pinned: !s.pinned,
+ });
+ if (!r.ok) toast.error(r.error);
+ else router.refresh();
+ });
+ }
+
+ function confirmDelete(s: SessionLite) {
+ startTransition(async () => {
+ const r = await deleteThreadAction({
+ projectSlug,
+ agentSlug,
+ threadLabel: s.sessionId,
+ });
+ setDeleting(null);
+ if (!r.ok) {
+ toast.error(r.error);
+ return;
+ }
+ toast.success("Thread deleted.");
+ if (s.sessionId === activeSessionId) {
+ // The open thread just vanished — move to a fresh one.
+ newThread();
+ } else {
+ router.refresh();
+ }
+ });
+ }
+
+ return (
+ <aside className="flex w-72 shrink-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
+ <div className="pt-2">
+ {/* Same shell as a thread row so the rail reads as one list. */}
+ <button
+ type="button"
+ onClick={newThread}
+ disabled={pending}
+ className={cn(ROW_CLASS, "disabled:opacity-50")}
+ >
+ <span className="inline-flex items-center gap-1.5 font-medium text-muted-foreground group-hover/row:text-foreground">
+ <Plus className="size-3.5" />
+ New chat
+ </span>
+ </button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto py-1">
+ {visible.length === 0 ? (
+ <div className="px-4 py-8 text-center text-xs text-muted-foreground">
+ No threads yet — say hi below.
+ </div>
+ ) : (
+ /* gap-1 matches SidebarMenu's item spacing, same as the task rail. */
+ <ul className="flex flex-col gap-1">
+ {visible.map((s) => {
+ const isActive = s.sessionId === activeSessionId;
+ return (
+ <li key={s.sessionId} className="relative">
+ <Link
+ href={projectHref(
+ projectSlug,
+ `/agents/${agentSlug}/chat/${s.sessionId}`,
+ )}
+ aria-current={isActive ? "true" : undefined}
+ onMouseEnter={primeMarquee}
+ className={cn(
+ ROW_CLASS,
+ // Reserve space for the ⋮ button (and pin glyph).
+ "pr-8",
+ isActive && "bg-sidebar-accent",
+ )}
+ >
+ <span className="flex items-center gap-1.5">
+ {s.pinned && (
+ <Pin
+ aria-label="Pinned"
+ className="size-3 shrink-0 text-muted-foreground"
+ />
+ )}
+ <span className="ns-marquee min-w-0 flex-1">
+ <span
+ className={cn(
+ isActive
+ ? "font-medium text-foreground"
+ : "text-foreground/90",
+ )}
+ >
+ {displayTitle(s)}
+ </span>
+ </span>
+ </span>
+ </Link>
+ {/* ⋮ menu — a sibling of the Link (not a child: nested
+ interactive elements are invalid HTML), absolutely
+ positioned into the row's reserved right padding. */}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={`Thread actions for ${displayTitle(s)}`}
+ className="absolute right-3.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[state=open]:opacity-100 [li:hover_&]:opacity-100"
+ >
+ <MoreVertical className="size-3.5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" side="right">
+ <DropdownMenuItem onSelect={() => setRenaming(s)}>
+ Rename
+ </DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => togglePin(s)}>
+ {s.pinned ? (
+ <>
+ <PinOff className="mr-1.5 size-3.5" /> Unpin
+ </>
+ ) : (
+ <>
+ <Pin className="mr-1.5 size-3.5" /> Pin
+ </>
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() => setDeleting(s)}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+
+ {renaming && (
+ <RenameThreadDialog
+ session={renaming}
+ onClose={() => setRenaming(null)}
+ onSubmit={(title) => {
+ const target = renaming;
+ startTransition(async () => {
+ const r = await renameThreadAction({
+ projectSlug,
+ agentSlug,
+ threadLabel: target.sessionId,
+ title,
+ });
+ setRenaming(null);
+ if (!r.ok) toast.error(r.error);
+ else router.refresh();
+ });
+ }}
+ />
+ )}
+
+ <Dialog open={deleting !== null} onOpenChange={(o) => !o && setDeleting(null)}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Delete thread?</DialogTitle>
+ <DialogDescription>
+ This permanently deletes the conversation
+ {deleting ? ` "${displayTitle(deleting)}"` : ""} and its
+ transcript. There is no undo.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" size="sm" onClick={() => setDeleting(null)}>
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={pending}
+ onClick={() => deleting && confirmDelete(deleting)}
+ >
+ Delete
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </aside>
+ );
+}
+
+function RenameThreadDialog({
+ session,
+ onClose,
+ onSubmit,
+}: {
+ session: SessionLite;
+ onClose: () => void;
+ onSubmit: (title: string) => void;
+}) {
+ const [value, setValue] = useState(session.title ?? "");
+ return (
+ <Dialog open onOpenChange={(o) => !o && onClose()}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Rename thread</DialogTitle>
+ <DialogDescription>
+ Leave empty to go back to the automatic title.
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ onSubmit(value.trim());
+ }}
+ >
+ <Input
+ autoFocus
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder={displayTitle({ ...session, title: null })}
+ aria-label="Thread title"
+ />
+ <DialogFooter className="mt-4">
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="submit" size="sm">
+ Save
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/notfair-cmo/src/components/new-chat-button.tsx b/notfair-cmo/src/components/new-chat-button.tsx
deleted file mode 100644
index bb461cc8..00000000
--- a/notfair-cmo/src/components/new-chat-button.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-"use client";
-
-import { useTransition } from "react";
-import { useRouter } from "next/navigation";
-import { Plus } from "lucide-react";
-import { projectHref } from "@/lib/project-href";
-
-type Props = {
- projectSlug: string;
- agentSlug: string;
-};
-
-/**
- * Discoverable "new chat" affordance next to the thread dropdown.
- */
-export function NewChatButton({ projectSlug, agentSlug }: Props) {
- const router = useRouter();
- const [pending, start] = useTransition();
-
- function newThread() {
- const id = crypto.randomUUID();
- start(() =>
- router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${id}`)),
- );
- }
-
- return (
- <button
- type="button"
- onClick={newThread}
- disabled={pending}
- aria-label="New chat"
- title="New chat"
- className="ns-btn ns-btn-outline ns-btn-sm"
- >
- <Plus className="size-3.5" />
- <span>New chat</span>
- </button>
- );
-}
diff --git a/notfair-cmo/src/components/thread-selector.test.tsx b/notfair-cmo/src/components/thread-selector.test.tsx
deleted file mode 100644
index 0f334425..00000000
--- a/notfair-cmo/src/components/thread-selector.test.tsx
+++ /dev/null
@@ -1,407 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, fireEvent, waitFor } from "@testing-library/react";
-
-const pushMock = vi.fn();
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: pushMock }),
-}));
-
-import { ThreadSelector, type SessionLite } from "./thread-selector";
-
-function openTrigger() {
- const trigger = screen.getByRole("button");
- fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });
- fireEvent.click(trigger);
-}
-
-beforeEach(() => {
- pushMock.mockReset();
- // jsdom + radix dropdown rely on these primitives that older jsdom is missing.
- Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
- configurable: true,
- writable: true,
- value: vi.fn(),
- });
- // Radix uses pointer events; jsdom lacks hasPointerCapture/setPointerCapture/releasePointerCapture
- Object.defineProperty(HTMLElement.prototype, "hasPointerCapture", {
- configurable: true,
- writable: true,
- value: () => false,
- });
- Object.defineProperty(HTMLElement.prototype, "setPointerCapture", {
- configurable: true,
- writable: true,
- value: () => {},
- });
- Object.defineProperty(HTMLElement.prototype, "releasePointerCapture", {
- configurable: true,
- writable: true,
- value: () => {},
- });
-});
-
-function makeSession(overrides: Partial<SessionLite> = {}): SessionLite {
- return {
- sessionId: "s-1",
- sessionKey: "agent:demo-cmo:s-1",
- label: "main",
- lastInteractionAt: Date.now() - 30_000,
- pending: false,
- ...overrides,
- };
-}
-
-describe("ThreadSelector trigger label", () => {
- it("renders 'Main thread' when active session.label is main", () => {
- const sessions = [makeSession({ label: "main" })];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- expect(
- screen.getByRole("button", { name: /Main thread/ }),
- ).toBeInTheDocument();
- });
-
- it("renders 'New thread · <prefix>' for pending sessions", () => {
- const sessions = [
- makeSession({ pending: true, sessionId: "1234567890abcdef", label: "ignored" }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="1234567890abcdef"
- />,
- );
- expect(
- screen.getByRole("button", { name: /New thread · 12345678/ }),
- ).toBeInTheDocument();
- });
-
- it("truncates long labels at 32 chars with an ellipsis", () => {
- const longLabel = "this-is-a-very-long-thread-label-that-exceeds-32-characters";
- const sessions = [makeSession({ label: longLabel })];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- const trigger = screen.getByRole("button");
- expect(trigger.textContent).toContain(`${longLabel.slice(0, 32)}...`);
- expect(trigger.textContent).not.toContain(longLabel);
- });
-
- it("shows 'Pick a thread' when no active session matches", () => {
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={[makeSession()]}
- activeSessionId="not-here"
- />,
- );
- expect(
- screen.getByRole("button", { name: /Pick a thread/ }),
- ).toBeInTheDocument();
- });
-
- it("renders the task as '<DISPLAY-ID> <title>' (uppercased id)", () => {
- const sessions = [
- makeSession({
- label: "8c2f1a1b-1234-4abc-9def-1234567890ab",
- origin: {
- kind: "task",
- display_id: "demo-7",
- title: "Audit and write PROJECT.md",
- },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- expect(
- screen.getByRole("button", { name: /DEMO-7 Audit and write PROJECT\.md/ }),
- ).toBeInTheDocument();
- // The raw UUID label must NOT leak into the trigger.
- expect(
- screen.queryByRole("button", { name: /8c2f1a1b/ }),
- ).toBeNull();
- });
-
- it("renders just the uppercased display_id when title is null", () => {
- const sessions = [
- makeSession({
- label: "8c2f1a1b-1234",
- origin: { kind: "task", display_id: "demo-3", title: null },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- const trigger = screen.getByRole("button");
- expect(trigger.textContent).toContain("DEMO-3");
- expect(trigger.textContent).not.toContain("demo-3");
- });
-
- it("renders the cron name when origin.kind is 'cron'", () => {
- const sessions = [
- makeSession({
- label: "cron:7f879fba-e3c8-412a-b576-34ded35b44a8:run:abc",
- origin: { kind: "cron", cron_name: "daily-audit" },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- expect(
- screen.getByRole("button", { name: /daily-audit/ }),
- ).toBeInTheDocument();
- });
-
- it("renders the first-message preview when origin.kind is 'chat'", () => {
- const sessions = [
- makeSession({
- label: "fresh-uuid",
- origin: { kind: "chat", preview: "what should we do about CPC drift?" },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- expect(
- screen.getByRole("button", { name: /what should we do about CPC drift\?/ }),
- ).toBeInTheDocument();
- });
-
- it("falls back to label when origin.kind is 'chat' but preview is empty", () => {
- const sessions = [
- makeSession({
- label: "main",
- origin: { kind: "chat", preview: "" },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- // Empty preview should not blank the label out — keep the legacy
- // "Main thread" affordance so the trigger is never empty.
- expect(
- screen.getByRole("button", { name: /Main thread/ }),
- ).toBeInTheDocument();
- });
-});
-
-describe("ThreadSelector dropdown interactions", () => {
- it("opens the menu and lists sessions including counts", async () => {
- const sessions = [
- makeSession({ sessionId: "s-1", label: "main" }),
- makeSession({
- sessionId: "s-2-other",
- label: "feature branch",
- lastInteractionAt: Date.now() - 3_600_000,
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- openTrigger();
- await waitFor(() => {
- expect(screen.getByText(/Threads \(2\)/)).toBeInTheDocument();
- expect(screen.getByText("feature branch")).toBeInTheDocument();
- // session id prefix appears in the menu line.
- expect(screen.getAllByText(/s-1/).length).toBeGreaterThan(0);
- });
- });
-
- it("shows 'No threads yet' when sessions array is empty", async () => {
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={[]}
- activeSessionId=""
- />,
- );
- openTrigger();
- await waitFor(() => {
- expect(screen.getByText("No threads yet")).toBeInTheDocument();
- expect(screen.getByText(/Threads \(0\)/)).toBeInTheDocument();
- });
- });
-
- it("clicking a non-active session pushes to its chat URL", async () => {
- const sessions = [
- makeSession({ sessionId: "s-1", label: "main" }),
- makeSession({ sessionId: "s-2", label: "draft" }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- openTrigger();
- await waitFor(() => {
- expect(screen.getByText("draft")).toBeInTheDocument();
- });
- fireEvent.click(screen.getByText("draft"));
- await waitFor(() => {
- expect(pushMock).toHaveBeenCalledWith("/demo/agents/cmo/chat/s-2");
- });
- });
-
- it("clicking the active session is a no-op (no router.push)", async () => {
- const sessions = [makeSession({ sessionId: "s-1", label: "main" })];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="s-1"
- />,
- );
- openTrigger();
- let menuitem: HTMLElement | null = null;
- await waitFor(() => {
- menuitem = screen.getByRole("menuitem", { name: /Main thread/ });
- expect(menuitem).toBeInTheDocument();
- });
- fireEvent.click(menuitem!);
- await new Promise((r) => setTimeout(r, 10));
- expect(pushMock).not.toHaveBeenCalled();
- });
-
- it("groups rows under Tasks / Crons / Chats section headers", async () => {
- const sessions = [
- makeSession({
- sessionId: "task-s",
- label: "uuid-task",
- origin: { kind: "task", display_id: "demo-1", title: "Do the thing" },
- }),
- makeSession({
- sessionId: "cron-s",
- label: "cron:abc:run:1",
- origin: { kind: "cron", cron_name: "daily-audit" },
- }),
- makeSession({
- sessionId: "chat-s",
- label: "uuid-chat",
- origin: { kind: "chat", preview: "hello there" },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="task-s"
- />,
- );
- openTrigger();
- await waitFor(() => {
- // Section headers — each shows its own count, separate from the
- // outer "Threads (N)" total at the top of the menu.
- expect(screen.getByText(/^Tasks \(1\)$/)).toBeInTheDocument();
- expect(screen.getByText(/^Crons \(1\)$/)).toBeInTheDocument();
- expect(screen.getByText(/^Chats \(1\)$/)).toBeInTheDocument();
- // Outer total still present.
- expect(screen.getByText(/Threads \(3\)/)).toBeInTheDocument();
- // Each row's label rendered. DEMO-1 also appears in the trigger
- // (active session), so use getAllByText for that one specifically.
- expect(screen.getAllByText(/DEMO-1 Do the thing/).length).toBeGreaterThanOrEqual(1);
- expect(screen.getByText("daily-audit")).toBeInTheDocument();
- expect(screen.getByText("hello there")).toBeInTheDocument();
- });
- });
-
- it("omits sections that have no rows", async () => {
- const sessions = [
- makeSession({
- sessionId: "chat-only",
- label: "uuid-only",
- origin: { kind: "chat", preview: "just a chat" },
- }),
- ];
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={sessions}
- activeSessionId="chat-only"
- />,
- );
- openTrigger();
- await waitFor(() => {
- expect(screen.getByText(/^Chats \(1\)$/)).toBeInTheDocument();
- expect(screen.queryByText(/^Tasks/)).toBeNull();
- expect(screen.queryByText(/^Crons/)).toBeNull();
- });
- });
-
- it("clicking 'New thread' navigates to a fresh uuid", async () => {
- // Stub crypto.randomUUID for determinism.
- const uuid = "11111111-2222-3333-4444-555555555555";
- Object.defineProperty(globalThis, "crypto", {
- configurable: true,
- value: { randomUUID: () => uuid },
- });
- render(
- <ThreadSelector
- projectSlug="demo"
- agentSlug="cmo"
- sessions={[makeSession()]}
- activeSessionId="s-1"
- />,
- );
- openTrigger();
- await waitFor(() => {
- expect(screen.getByText("New thread")).toBeInTheDocument();
- });
- fireEvent.click(screen.getByText("New thread"));
- await waitFor(() => {
- expect(pushMock).toHaveBeenCalledWith(`/demo/agents/cmo/chat/${uuid}`);
- });
- });
-});
diff --git a/notfair-cmo/src/components/thread-selector.tsx b/notfair-cmo/src/components/thread-selector.tsx
deleted file mode 100644
index 69b4261e..00000000
--- a/notfair-cmo/src/components/thread-selector.tsx
+++ /dev/null
@@ -1,197 +0,0 @@
-"use client";
-
-import { useTransition } from "react";
-import { useRouter } from "next/navigation";
-import { ChevronsUpDown, Plus, Check } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { projectHref } from "@/lib/project-href";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-
-export type SessionOriginLite =
- | { kind: "task"; display_id: string; title: string | null }
- | { kind: "cron"; cron_name: string }
- | { kind: "chat"; preview: string };
-
-export type SessionLite = {
- sessionId: string;
- label: string;
- sessionKey: string;
- lastInteractionAt: number;
- pending: boolean;
- /**
- * Server-classified origin. Drives the dropdown row label so users see
- * a task display id, cron name, or chat preview instead of a raw UUID.
- * Undefined for pending threads (no transcript / task / cron yet).
- */
- origin?: SessionOriginLite;
-};
-
-type Props = {
- projectSlug: string;
- agentSlug: string;
- sessions: SessionLite[];
- activeSessionId: string;
-};
-
-function timeAgo(ms: number) {
- if (!ms) return "new";
- const seconds = Math.max(0, (Date.now() - ms) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
-function truncate(s: string, max = 40): string {
- return s.length > max ? `${s.slice(0, max)}...` : s;
-}
-
-function formatTaskTitle(o: { display_id: string; title: string | null }): string {
- const id = o.display_id.toUpperCase();
- return o.title ? truncate(`${id} ${o.title}`) : id;
-}
-
-function displayTitle(s: SessionLite): string {
- if (s.pending) return `New thread · ${s.sessionId.slice(0, 8)}`;
- if (s.origin?.kind === "task") return formatTaskTitle(s.origin);
- if (s.origin?.kind === "cron") return truncate(s.origin.cron_name);
- if (s.origin?.kind === "chat" && s.origin.preview) {
- return truncate(s.origin.preview);
- }
- if (s.label === "main") return "Main thread";
- return truncate(s.label, 32);
-}
-
-type SectionKey = "tasks" | "crons" | "chats";
-
-const SECTION_ORDER: SectionKey[] = ["tasks", "crons", "chats"];
-const SECTION_TITLES: Record<SectionKey, string> = {
- tasks: "Tasks",
- crons: "Crons",
- chats: "Chats",
-};
-
-function sectionFor(s: SessionLite): SectionKey {
- if (s.origin?.kind === "task") return "tasks";
- if (s.origin?.kind === "cron") return "crons";
- // Pending threads + classified chats + unclassified fallbacks all go under
- // "Chats" so the dropdown never strands a row in an unlabeled section.
- return "chats";
-}
-
-function groupBySection(sessions: SessionLite[]): Map<SectionKey, SessionLite[]> {
- const groups = new Map<SectionKey, SessionLite[]>();
- for (const s of sessions) {
- const key = sectionFor(s);
- const list = groups.get(key) ?? [];
- list.push(s);
- groups.set(key, list);
- }
- return groups;
-}
-
-export function ThreadSelector({
- projectSlug,
- agentSlug,
- sessions,
- activeSessionId,
-}: Props) {
- const router = useRouter();
- const [pending, start] = useTransition();
- const active = sessions.find((s) => s.sessionId === activeSessionId);
-
- function go(sessionId: string) {
- if (sessionId === activeSessionId) return;
- start(() =>
- router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${sessionId}`)),
- );
- }
-
- function newThread() {
- const id = crypto.randomUUID();
- start(() =>
- router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${id}`)),
- );
- }
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className="min-w-[200px] justify-between"
- disabled={pending}
- >
- <span className="truncate text-left">
- {active ? displayTitle(active) : "Pick a thread"}
- </span>
- <ChevronsUpDown className="ml-2 size-3.5 shrink-0 text-muted-foreground" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-72">
- <DropdownMenuLabel className="text-xs text-muted-foreground">
- Threads ({sessions.length}) · from OpenClaw
- </DropdownMenuLabel>
- <DropdownMenuSeparator />
- {sessions.length === 0 && (
- <DropdownMenuItem disabled>No threads yet</DropdownMenuItem>
- )}
- {(() => {
- const groups = groupBySection(sessions);
- const present = SECTION_ORDER.filter((k) => (groups.get(k)?.length ?? 0) > 0);
- return present.map((key, idx) => {
- const rows = groups.get(key)!;
- return (
- <div key={key}>
- {idx > 0 && <DropdownMenuSeparator />}
- <DropdownMenuLabel className="text-[10px] uppercase tracking-wide text-muted-foreground">
- {SECTION_TITLES[key]} ({rows.length})
- </DropdownMenuLabel>
- {rows.map((s) => {
- const isActive = s.sessionId === activeSessionId;
- return (
- <DropdownMenuItem
- key={s.sessionId}
- onSelect={(e) => {
- e.preventDefault();
- go(s.sessionId);
- }}
- className="flex items-center gap-2"
- >
- <div className="flex-1 min-w-0">
- <div className="truncate text-sm">{displayTitle(s)}</div>
- <div className="text-[10px] text-muted-foreground font-mono">
- {s.sessionId.slice(0, 8)} · {timeAgo(s.lastInteractionAt)}
- </div>
- </div>
- {isActive && <Check className="size-3.5 shrink-0 text-muted-foreground" />}
- </DropdownMenuItem>
- );
- })}
- </div>
- );
- });
- })()}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={(e) => {
- e.preventDefault();
- newThread();
- }}
- disabled={pending}
- >
- <Plus className="mr-2 size-3.5" />
- New thread
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}
diff --git a/notfair-cmo/src/server/actions/chat-threads.ts b/notfair-cmo/src/server/actions/chat-threads.ts
new file mode 100644
index 00000000..d0ee4679
--- /dev/null
+++ b/notfair-cmo/src/server/actions/chat-threads.ts
@@ -0,0 +1,95 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import { getProject } from "@/server/db/projects";
+import {
+ deleteSession,
+ setSessionPinned,
+ setSessionTitle,
+} from "@/server/sessions";
+import { findSessionBySessionId } from "@/server/sessions/view";
+
+export type ThreadActionResult = { ok: true } | { ok: false; error: string };
+
+/**
+ * Resolve (project, agent slug, thread label) → the sessions row id, with
+ * ownership checks. The thread label is the UUID in the /chat/<label> URL;
+ * SessionView.sessionKey carries the DB primary key.
+ */
+async function resolveThread(
+ projectSlug: string,
+ agentSlug: string,
+ threadLabel: string,
+): Promise<{ ok: true; sessionId: string } | { ok: false; error: string }> {
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) {
+ return { ok: false, error: "Project not found." };
+ }
+ const agent = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!agent) return { ok: false, error: `Unknown agent '${agentSlug}'` };
+ const session = findSessionBySessionId(
+ project.slug,
+ agent.agent_id,
+ threadLabel,
+ );
+ if (!session) return { ok: false, error: "Thread not found." };
+ return { ok: true, sessionId: session.sessionKey };
+}
+
+/** Rename a thread (empty title clears back to the derived preview). */
+export async function renameThreadAction(input: {
+ projectSlug: string;
+ agentSlug: string;
+ threadLabel: string;
+ title: string;
+}): Promise<ThreadActionResult> {
+ const resolved = await resolveThread(
+ input.projectSlug,
+ input.agentSlug,
+ input.threadLabel,
+ );
+ if (!resolved.ok) return resolved;
+ setSessionTitle(resolved.sessionId, input.title);
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/** Pin or unpin a thread — pinned threads sort to the top of the rail. */
+export async function setThreadPinnedAction(input: {
+ projectSlug: string;
+ agentSlug: string;
+ threadLabel: string;
+ pinned: boolean;
+}): Promise<ThreadActionResult> {
+ const resolved = await resolveThread(
+ input.projectSlug,
+ input.agentSlug,
+ input.threadLabel,
+ );
+ if (!resolved.ok) return resolved;
+ setSessionPinned(resolved.sessionId, input.pinned);
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/**
+ * Permanently delete a thread and its transcript (FK cascade). The rail
+ * confirms with the user before calling this.
+ */
+export async function deleteThreadAction(input: {
+ projectSlug: string;
+ agentSlug: string;
+ threadLabel: string;
+}): Promise<ThreadActionResult> {
+ const resolved = await resolveThread(
+ input.projectSlug,
+ input.agentSlug,
+ input.threadLabel,
+ );
+ if (!resolved.ok) return resolved;
+ deleteSession(resolved.sessionId);
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
diff --git a/notfair-cmo/src/server/db/migrations.ts b/notfair-cmo/src/server/db/migrations.ts
index 5260c5bb..3439ce71 100644
--- a/notfair-cmo/src/server/db/migrations.ts
+++ b/notfair-cmo/src/server/db/migrations.ts
@@ -567,6 +567,19 @@ ALTER TABLE scheduled_job_runs ADD COLUMN summary TEXT;
ALTER TABLE projects ADD COLUMN meta_ads_account_id TEXT;
ALTER TABLE projects ADD COLUMN gsc_property_id TEXT;
+`,
+ },
+ {
+ name: "016_session_title_pin.sql",
+ sql: `
+-- Chat-thread management for the thread rail: user-set display titles
+-- (rename), and pinning. \`title\` overrides the derived first-message
+-- preview when set; \`pinned_at\` doubles as the pin flag and the
+-- pin-order tiebreaker (most recently pinned first). Delete needs no
+-- schema: transcript_events already cascades on session delete.
+
+ALTER TABLE sessions ADD COLUMN title TEXT;
+ALTER TABLE sessions ADD COLUMN pinned_at TEXT;
`,
},
];
diff --git a/notfair-cmo/src/server/db/migrations/016_session_title_pin.sql b/notfair-cmo/src/server/db/migrations/016_session_title_pin.sql
new file mode 100644
index 00000000..5a8d0e24
--- /dev/null
+++ b/notfair-cmo/src/server/db/migrations/016_session_title_pin.sql
@@ -0,0 +1,8 @@
+-- Chat-thread management for the thread rail: user-set display titles
+-- (rename), and pinning. `title` overrides the derived first-message
+-- preview when set; `pinned_at` doubles as the pin flag and the
+-- pin-order tiebreaker (most recently pinned first). Delete needs no
+-- schema: transcript_events already cascades on session delete.
+
+ALTER TABLE sessions ADD COLUMN title TEXT;
+ALTER TABLE sessions ADD COLUMN pinned_at TEXT;
diff --git a/notfair-cmo/src/server/sessions/index.ts b/notfair-cmo/src/server/sessions/index.ts
index 31814e51..d0a3b19b 100644
--- a/notfair-cmo/src/server/sessions/index.ts
+++ b/notfair-cmo/src/server/sessions/index.ts
@@ -20,6 +20,10 @@ export interface Session {
harness_adapter: HarnessAdapterId;
harness_session_id: string | null;
task_id: string | null;
+ /** User-set display title (thread rename). Null = derive from content. */
+ title: string | null;
+ /** Set when the user pins the thread; doubles as pin-order tiebreaker. */
+ pinned_at: string | null;
created_at: string;
updated_at: string;
}
@@ -41,6 +45,8 @@ interface SessionRow {
harness_adapter: string;
harness_session_id: string | null;
task_id: string | null;
+ title: string | null;
+ pinned_at: string | null;
created_at: string;
updated_at: string;
}
@@ -72,6 +78,8 @@ export function getOrCreateSession(input: {
harness_adapter: input.harness_adapter,
harness_session_id: null,
task_id: input.task_id ?? null,
+ title: null,
+ pinned_at: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
@@ -91,6 +99,28 @@ export function getOrCreateSession(input: {
return session;
}
+/** Set / clear the user-facing display title (thread rename). */
+export function setSessionTitle(id: string, title: string | null): void {
+ getDb()
+ .prepare("UPDATE sessions SET title = ? WHERE id = ?")
+ .run(title?.trim() || null, id);
+}
+
+/** Pin or unpin a thread. */
+export function setSessionPinned(id: string, pinned: boolean): void {
+ getDb()
+ .prepare("UPDATE sessions SET pinned_at = ? WHERE id = ?")
+ .run(pinned ? new Date().toISOString() : null, id);
+}
+
+/**
+ * Permanently delete a thread. transcript_events cascades on the FK, so
+ * the whole conversation history goes with it.
+ */
+export function deleteSession(id: string): void {
+ getDb().prepare("DELETE FROM sessions WHERE id = ?").run(id);
+}
+
export function getSession(id: string): Session | null {
const row = getDb()
.prepare("SELECT * FROM sessions WHERE id = ?")
@@ -101,7 +131,9 @@ export function getSession(id: string): Session | null {
export function listAgentSessions(project_slug: string, agent_id: string): Session[] {
const rows = getDb()
.prepare(
- "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? ORDER BY updated_at DESC",
+ // Pinned threads first (most recently pinned on top), then by
+ // recency — the thread rail renders this order verbatim.
+ "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? ORDER BY (pinned_at IS NULL) ASC, pinned_at DESC, updated_at DESC",
)
.all(project_slug, agent_id) as SessionRow[];
return rows.map(rowToSession);
diff --git a/notfair-cmo/src/server/sessions/view.ts b/notfair-cmo/src/server/sessions/view.ts
index e1c1d222..5279dd5d 100644
--- a/notfair-cmo/src/server/sessions/view.ts
+++ b/notfair-cmo/src/server/sessions/view.ts
@@ -24,6 +24,10 @@ export interface SessionView {
lastInteractionAt: number;
/** True when the row exists only in our cookie (no turns yet). */
pending: boolean;
+ /** User-set display title (thread rename). Null = derive from content. */
+ title: string | null;
+ /** True when the user pinned this thread to the top of the rail. */
+ pinned: boolean;
}
function cookieName(project_slug: string, agent_template_key: string): string {
@@ -37,6 +41,8 @@ function sessionRowToView(s: Session): SessionView {
sessionKey: s.id,
lastInteractionAt: Date.parse(s.updated_at) || 0,
pending: false,
+ title: s.title,
+ pinned: s.pinned_at !== null,
};
}
@@ -98,6 +104,8 @@ export async function getSessionsView(
sessionKey: cookieLabel,
lastInteractionAt: 0,
pending: true,
+ title: null,
+ pinned: false,
};
}
}
@@ -113,6 +121,8 @@ export async function getSessionsView(
sessionKey: newLabel,
lastInteractionAt: 0,
pending: true,
+ title: null,
+ pinned: false,
};
}
}
@@ -183,7 +193,10 @@ export function pickLatestChatSession<S extends { label: string }>(
return sessions.find((s) => !isTaskOrCronSession(s.label, taskThreadIds));
}
-const PREVIEW_MAX_CHARS = 40;
+// Generous cap: the rail shows ~40 chars at rest and reveals the rest by
+// scrolling the text horizontally on hover — a 40-char preview would give
+// the marquee nothing to reveal.
+const PREVIEW_MAX_CHARS = 140;
/**
* Classify each session by origin so the dropdown can show meaningful labels.