Skip to content

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

feat(chat): section thread dropdown by Tasks/Crons/Chats with origin labels

Yuting Zhongc10aad7bfddb
diff --git a/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
index e6ef1143..66b78619 100644
--- a/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
@@ -6,13 +6,15 @@ import {
findSessionBySessionId,
listSessionsForAgent,
} from "@/server/openclaw/sessions";
+import { classifySessions } from "@/server/openclaw/thread-origins";
import { storedMcpKey } from "@/server/mcp-catalog";
import { getMcpStatus } from "@/server/mcp-state";
import { readTranscriptTail } from "@/server/openclaw/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 } from "@/components/thread-selector";
+import { ThreadSelector, type SessionLite } from "@/components/thread-selector";
+import { NewChatButton } from "@/components/new-chat-button";
type Params = { agent: string; thread: string; project: string };
type Search = { mcp_connected?: string; mcp_error?: string };
@@ -45,10 +47,23 @@ export default async function AgentChatThreadPage({
const { events: initialEvents, byteOffset: initialByteOffset } =
readTranscriptTail(agentFullId, threadId, 0);
+ // Classify existing sessions by origin (task / cron / chat) so the
+ // dropdown can show the task display_id, cron name, or first-message
+ // preview instead of opaque UUIDs.
+ const origins = await classifySessions(agentFullId, project.slug, allSessions);
+ const enriched: SessionLite[] = allSessions.map((s) => ({
+ sessionId: s.sessionId,
+ label: s.label,
+ sessionKey: s.sessionKey,
+ lastInteractionAt: s.lastInteractionAt,
+ pending: s.pending,
+ origin: origins.get(s.label),
+ }));
+
// For the dropdown: surface the pending thread at the top so the user sees
// it's "selected" even before sending the first message.
- const sessionsForDropdown = existing
- ? allSessions
+ const sessionsForDropdown: SessionLite[] = existing
+ ? enriched
: [
{
sessionId: threadId,
@@ -57,7 +72,7 @@ export default async function AgentChatThreadPage({
lastInteractionAt: 0,
pending: true,
},
- ...allSessions,
+ ...enriched,
];
// The Google Ads agent depends on the notfair-googleads MCP for live
@@ -89,12 +104,15 @@ export default async function AgentChatThreadPage({
? "No threads yet"
: `${sessionsForDropdown.length} thread${sessionsForDropdown.length === 1 ? "" : "s"}`}
</div>
- <ThreadSelector
- projectSlug={projectSlug}
- agentSlug={agentSlug}
- sessions={sessionsForDropdown}
- activeSessionId={threadId}
- />
+ <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">
diff --git a/src/app/(app)/[project]/agents/[agent]/chat/page.tsx b/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
index a14f2d3c..799b2cb9 100644
--- a/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
@@ -5,12 +5,16 @@ import {
listSessionsForAgent,
newSessionId,
} from "@/server/openclaw/sessions";
+import { pickLatestChatSession } from "@/server/openclaw/thread-origins";
+import { listTasksByAgent } from "@/server/db/tasks";
import { projectHref } from "@/lib/project-href";
/**
- * Default landing for /<project>/agents/[agent]/chat — pick a thread and
- * redirect into the per-thread URL so refresh/share/back-button all keep
- * the thread context.
+ * Default landing for /<project>/agents/[agent]/chat — pick a free-form
+ * chat thread (NOT a task workspace or cron run) and redirect into the
+ * per-thread URL so refresh/share/back-button all keep the thread context.
+ * Task and cron threads have their own entry points (kanban card, cron
+ * calendar) and shouldn't hijack the agent's "chat" landing.
*/
export default async function ChatIndexPage({
params,
@@ -23,7 +27,16 @@ export default async function ChatIndexPage({
const resolved = await resolveAgentBySlug(project.slug, agentSlug);
if (!resolved) notFound();
- const existing = listSessionsForAgent(resolved.agent_id);
- const target = existing[0]?.sessionId ?? newSessionId();
+ // Build a set of every thread_id that belongs to a task so we can
+ // exclude those sessions. Cron sessions self-identify via OpenClaw's
+ // `cron:<jobId>:run:<id>` label prefix.
+ const taskThreadIds = new Set<string>();
+ for (const t of listTasksByAgent(resolved.agent_id)) {
+ if (t.thread_id) taskThreadIds.add(t.thread_id);
+ }
+
+ const sessions = listSessionsForAgent(resolved.agent_id);
+ const latestChat = pickLatestChatSession(sessions, taskThreadIds);
+ const target = latestChat?.sessionId ?? newSessionId();
redirect(projectHref(projectSlug, `/agents/${agentSlug}/chat/${target}`));
}
diff --git a/src/components/new-chat-button.tsx b/src/components/new-chat-button.tsx
new file mode 100644
index 00000000..3dbcfd43
--- /dev/null
+++ b/src/components/new-chat-button.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { Plus } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { projectHref } from "@/lib/project-href";
+
+type Props = {
+ projectSlug: string;
+ agentSlug: string;
+};
+
+/**
+ * Discoverable "new chat" affordance next to the thread dropdown. Mints a
+ * fresh UUID + routes to its chat URL — the dropdown's own "New thread"
+ * item does the same, but having it as a top-level button surfaces the
+ * action without an extra click into the menu.
+ */
+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
+ variant="outline"
+ size="sm"
+ onClick={newThread}
+ disabled={pending}
+ aria-label="New chat"
+ title="New chat"
+ >
+ <Plus className="size-3.5" />
+ <span className="ml-1">New chat</span>
+ </Button>
+ );
+}
diff --git a/src/components/thread-selector.test.tsx b/src/components/thread-selector.test.tsx
index 8e7bf587..0f334425 100644
--- a/src/components/thread-selector.test.tsx
+++ b/src/components/thread-selector.test.tsx
@@ -114,6 +114,116 @@ describe("ThreadSelector trigger label", () => {
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", () => {
@@ -203,6 +313,73 @@ describe("ThreadSelector dropdown interactions", () => {
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";
diff --git a/src/components/thread-selector.tsx b/src/components/thread-selector.tsx
index f147a289..69b4261e 100644
--- a/src/components/thread-selector.tsx
+++ b/src/components/thread-selector.tsx
@@ -14,12 +14,23 @@ import {
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 = {
@@ -38,10 +49,52 @@ function timeAgo(ms: number) {
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 s.label.length > 32 ? `${s.label.slice(0, 32)}...` : s.label;
+ 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({
@@ -91,27 +144,42 @@ export function ThreadSelector({
{sessions.length === 0 && (
<DropdownMenuItem disabled>No threads yet</DropdownMenuItem>
)}
- {sessions.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>
+ {(() => {
+ 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>
- {isActive && <Check className="size-3.5 shrink-0 text-muted-foreground" />}
- </DropdownMenuItem>
- );
- })}
+ );
+ });
+ })()}
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={(e) => {
diff --git a/src/server/openclaw/thread-origins.test.ts b/src/server/openclaw/thread-origins.test.ts
new file mode 100644
index 00000000..23093b16
--- /dev/null
+++ b/src/server/openclaw/thread-origins.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ isTaskOrCronSession,
+ pickLatestChatSession,
+} from "./thread-origins";
+
+describe("isTaskOrCronSession", () => {
+ it("returns true for cron labels", () => {
+ expect(
+ isTaskOrCronSession("cron:7f879fba:run:abc", new Set()),
+ ).toBe(true);
+ });
+
+ it("returns true when the label matches a known task thread_id", () => {
+ const taskIds = new Set(["task-thread-uuid"]);
+ expect(isTaskOrCronSession("task-thread-uuid", taskIds)).toBe(true);
+ });
+
+ it("returns false for plain chat labels", () => {
+ expect(isTaskOrCronSession("random-uuid", new Set())).toBe(false);
+ expect(isTaskOrCronSession("main", new Set())).toBe(false);
+ });
+
+ it("does not treat 'cron' as cron prefix without the colon", () => {
+ // Defensive: a chat thread that happens to start with the letters
+ // "cron" but isn't an OpenClaw cron-run label should not be filtered.
+ expect(isTaskOrCronSession("crontab-discussion", new Set())).toBe(false);
+ });
+});
+
+describe("pickLatestChatSession", () => {
+ // listSessionsForAgent returns newest-first; tests mirror that order.
+ const taskIds = new Set(["task-1-thread"]);
+
+ it("returns the first chat session, skipping leading task/cron rows", () => {
+ const sessions = [
+ { label: "cron:abc:run:1" }, // cron — skip
+ { label: "task-1-thread" }, // task — skip
+ { label: "uuid-newest-chat" }, // pick this
+ { label: "uuid-older-chat" },
+ ];
+ expect(pickLatestChatSession(sessions, taskIds)?.label).toBe(
+ "uuid-newest-chat",
+ );
+ });
+
+ it("returns undefined when every session is a task or cron", () => {
+ const sessions = [
+ { label: "cron:abc:run:1" },
+ { label: "task-1-thread" },
+ ];
+ expect(pickLatestChatSession(sessions, taskIds)).toBeUndefined();
+ });
+
+ it("returns undefined for an empty list (caller mints a fresh id)", () => {
+ expect(pickLatestChatSession([], taskIds)).toBeUndefined();
+ });
+
+ it("works with the OpenClawSession shape, not just bare labels", () => {
+ // Generic over { label: string } — calling with the full session
+ // shape returns the same object so the caller can read sessionId.
+ const sessions = [
+ {
+ label: "task-1-thread",
+ sessionId: "internal-1",
+ sessionKey: "agent:x:task-1-thread",
+ lastInteractionAt: 200,
+ pending: false,
+ },
+ {
+ label: "chat-uuid",
+ sessionId: "internal-2",
+ sessionKey: "agent:x:chat-uuid",
+ lastInteractionAt: 100,
+ pending: false,
+ },
+ ];
+ const picked = pickLatestChatSession(sessions, taskIds);
+ expect(picked?.sessionId).toBe("internal-2");
+ });
+});
diff --git a/src/server/openclaw/thread-origins.ts b/src/server/openclaw/thread-origins.ts
new file mode 100644
index 00000000..41527b13
--- /dev/null
+++ b/src/server/openclaw/thread-origins.ts
@@ -0,0 +1,237 @@
+import {
+ closeSync,
+ existsSync,
+ openSync,
+ readSync,
+ statSync,
+} from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import { listTasksByAgent } from "@/server/db/tasks";
+import { listCronsForProject } from "./crons";
+import type { OpenClawSession } from "./sessions";
+
+const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");
+
+/**
+ * What spawned a chat thread. Used by the thread dropdown to label each row
+ * with something meaningful — a task's display_id, a cron's short name, or
+ * the first user message of a free-form chat — instead of an opaque UUID.
+ */
+export type SessionOrigin =
+ | { kind: "task"; display_id: string; title: string | null }
+ | { kind: "cron"; cron_name: string }
+ | { kind: "chat"; preview: string };
+
+/** OpenClaw cron-run session labels are `cron:<jobId>:run:<runSessionId>`. */
+const CRON_LABEL_PREFIX = "cron:";
+
+/**
+ * True when the session belongs to a kanban task (label matches a task's
+ * `thread_id`) or a cron run (label starts with `cron:`). Used by the chat
+ * landing redirect to skip those rows so the user lands on a free-form
+ * chat instead of a task workspace.
+ */
+export function isTaskOrCronSession(
+ label: string,
+ taskThreadIds: ReadonlySet<string>,
+): boolean {
+ return label.startsWith(CRON_LABEL_PREFIX) || taskThreadIds.has(label);
+}
+
+/**
+ * Pick the most-recent free-form chat session (skipping task + cron rows).
+ * Assumes `sessions` is already sorted newest-first, which is the order
+ * `listSessionsForAgent` returns. Returns `undefined` when no chat exists.
+ */
+export function pickLatestChatSession<
+ S extends { label: string },
+>(sessions: readonly S[], taskThreadIds: ReadonlySet<string>): S | undefined {
+ return sessions.find((s) => !isTaskOrCronSession(s.label, taskThreadIds));
+}
+const PREVIEW_MAX_CHARS = 40;
+/**
+ * Cap the file read used to find a chat thread's first user message. The
+ * first message is always at the top of the JSONL; 32 KB is enough to span
+ * the session header + first message + slack, without dragging in the full
+ * transcript (which can run into MB on a long chat).
+ */
+const FIRST_MESSAGE_PROBE_BYTES = 32 * 1024;
+
+/**
+ * Classify each session by origin so the dropdown can show meaningful labels.
+ * Tasks come from the project DB (`tasks.thread_id === session.label`); crons
+ * come from OpenClaw's cron list keyed by jobId parsed out of the label; free
+ * chats fall back to a preview of the first user message in the JSONL.
+ *
+ * Returns a map keyed by session label (the part after `agent:<id>:`). Pending
+ * sessions are skipped — they have no transcript yet and no kanban/cron link.
+ */
+export async function classifySessions(
+ agentFullId: string,
+ projectSlug: string,
+ sessions: OpenClawSession[],
+): Promise<Map<string, SessionOrigin>> {
+ const out = new Map<string, SessionOrigin>();
+ if (sessions.length === 0) return out;
+
+ const cronJobIds = new Set<string>();
+ const chatLikeLabels: string[] = [];
+ for (const s of sessions) {
+ if (s.pending) continue;
+ if (s.label.startsWith(CRON_LABEL_PREFIX)) {
+ const jobId = s.label.split(":")[1];
+ if (jobId) cronJobIds.add(jobId);
+ } else {
+ chatLikeLabels.push(s.label);
+ }
+ }
+
+ // Tasks — one DB read for the agent's queue, then a map lookup per session.
+ const taskByThread = new Map<
+ string,
+ { display_id: string; title: string | null }
+ >();
+ if (chatLikeLabels.length > 0) {
+ const tasks = listTasksByAgent(agentFullId);
+ for (const t of tasks) {
+ if (t.thread_id) {
+ taskByThread.set(t.thread_id, {
+ display_id: t.display_id,
+ title: t.title,
+ });
+ }
+ }
+ }
+
+ // Crons — only hit the cron list if at least one label looks cron-shaped.
+ const cronByJobId = new Map<string, string>();
+ if (cronJobIds.size > 0) {
+ const view = await listCronsForProject(projectSlug);
+ for (const g of view.groups) {
+ for (const c of g.crons) {
+ cronByJobId.set(c.id, c.short_name || c.name);
+ }
+ }
+ }
+
+ for (const s of sessions) {
+ if (s.pending) continue;
+ if (s.label.startsWith(CRON_LABEL_PREFIX)) {
+ const jobId = s.label.split(":")[1] ?? "";
+ const name = cronByJobId.get(jobId);
+ out.set(s.label, {
+ kind: "cron",
+ cron_name: name ?? `cron · ${jobId.slice(0, 8)}`,
+ });
+ continue;
+ }
+ const task = taskByThread.get(s.label);
+ if (task) {
+ out.set(s.label, {
+ kind: "task",
+ display_id: task.display_id,
+ title: task.title,
+ });
+ continue;
+ }
+ out.set(s.label, {
+ kind: "chat",
+ preview: readFirstUserMessagePreview(agentFullId, s.sessionId),
+ });
+ }
+ return out;
+}
+
+/**
+ * Peek at a session's JSONL transcript and return a short preview of the
+ * first user message. Reads only the first ~32 KB rather than the full file
+ * — the first user turn is always at the top, and long transcripts can run
+ * into the MBs.
+ */
+function readFirstUserMessagePreview(
+ agentFullId: string,
+ sessionId: string,
+): string {
+ const path = join(
+ OPENCLAW_HOME,
+ "agents",
+ agentFullId,
+ "sessions",
+ `${sessionId}.jsonl`,
+ );
+ if (!existsSync(path)) return "";
+ let fd: number;
+ try {
+ fd = openSync(path, "r");
+ } catch {
+ return "";
+ }
+ let raw: string;
+ try {
+ const size = statSync(path).size;
+ const len = Math.min(size, FIRST_MESSAGE_PROBE_BYTES);
+ const buf = Buffer.alloc(len);
+ readSync(fd, buf, 0, len, 0);
+ raw = buf.toString("utf8");
+ } catch {
+ return "";
+ } finally {
+ try {
+ closeSync(fd);
+ } catch {
+ // ignore — closing a stale fd shouldn't break the dropdown.
+ }
+ }
+ for (const line of raw.split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ let entry: {
+ type?: string;
+ message?: { role?: string; content?: unknown };
+ };
+ try {
+ entry = JSON.parse(trimmed) as typeof entry;
+ } catch {
+ continue;
+ }
+ if (entry.type !== "message") continue;
+ const msg = entry.message;
+ if (!msg || msg.role !== "user") continue;
+ const text = extractText(msg.content);
+ if (text) return shorten(stripUserTimestampPrefix(text));
+ }
+ return "";
+}
+
+function extractText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ const parts: string[] = [];
+ for (const c of content) {
+ if (typeof c === "string") parts.push(c);
+ else if (c && typeof c === "object") {
+ const obj = c as { type?: string; text?: string };
+ if (obj.type === "text" && typeof obj.text === "string") {
+ parts.push(obj.text);
+ }
+ }
+ }
+ return parts.join(" ");
+}
+
+// Same shape as transcript-tail.stripUserTimestampPrefix — keeps the preview
+// from leading with the bracketed timestamp OpenClaw prepends to user turns.
+function stripUserTimestampPrefix(s: string): string {
+ return s.replace(
+ /^\[[A-Z][a-z]{2} \d{4}-\d{2}-\d{2} \d{2}:\d{2} [A-Z]{2,5}\] ?/,
+ "",
+ );
+}
+
+function shorten(s: string): string {
+ const flat = s.replace(/\s+/g, " ").trim();
+ if (flat.length <= PREVIEW_MAX_CHARS) return flat;
+ return flat.slice(0, PREVIEW_MAX_CHARS - 1) + "…";
+}