Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9078 refactor(chat): derive chat titles only on the server (#10393)

Jiayuan Zhang1be02cde8a5e
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
index ae7fbb0ffd..1e19ba3684 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
@@ -49,6 +49,7 @@ import {
hideQueuedChatMessages,
removePendingChatTask,
} from "@multica/core/chat/pending";
+import { refetchChatSessionsAfterCommit } from "@multica/core/chat/session-list";
import { canAssignAgentToIssue } from "@multica/core/permissions/rules";
import { api } from "@/data/api";
import { useAuthStore } from "@/data/auth-store";
@@ -264,16 +265,17 @@ export default function ChatTab() {
const sessionPromiseRef = useRef<Promise<string | null> | null>(null);
const ensureSession = useCallback(
- async (titleSeed: string): Promise<string | null> => {
+ async (): Promise<string | null> => {
if (activeSessionId) return activeSessionId;
if (!currentAgent) return null;
if (sessionPromiseRef.current) return sessionPromiseRef.current;
const promise = (async () => {
try {
+ // Untitled on purpose: the server derives the title from the first
+ // message it accepts, the same rule for every client and channel.
const session = await createSession.mutateAsync({
agent_id: currentAgent.id,
- title: titleSeed.slice(0, 50),
});
return session.id;
} finally {
@@ -314,7 +316,7 @@ export default function ChatTab() {
const isNewSession = !activeSessionId;
let sessionId: string | null;
try {
- sessionId = await ensureSession(content);
+ sessionId = await ensureSession();
} catch (err) {
// Session create runs the same invoke gate as a send, so a permission
// change refuses here too — and this is the only layer that sees the
@@ -387,6 +389,10 @@ export default function ChatTab() {
queued: result.queued,
});
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ // This send just committed the new session's server-derived title.
+ if (isNewSession) {
+ void refetchChatSessionsAfterCommit(qc, chatKeys.sessions(wsId));
+ }
if (options.clearDraft !== false) {
clearDraft(sessionId);
}
@@ -406,6 +412,7 @@ export default function ChatTab() {
}
},
[
+ wsId,
activeSessionId,
currentAgent,
accessRevoked,
diff --git a/packages/core/chat/session-list.test.ts b/packages/core/chat/session-list.test.ts
new file mode 100644
index 0000000000..fbf275784a
--- /dev/null
+++ b/packages/core/chat/session-list.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import { describe, expect, it } from "vitest";
+import { chatKeys } from "./queries";
+import { refetchChatSessionsAfterCommit } from "./session-list";
+import { applyChatSessionUpdatedToCache } from "../realtime/use-realtime-sync";
+import type { ChatSession } from "../types";
+
+describe("refetchChatSessionsAfterCommit", () => {
+ it.each([
+ { name: "cold cache", hasCache: false },
+ { name: "warm cache", hasCache: true },
+ ])("keeps a title committed while a list request is in flight ($name)", async ({ hasCache }) => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const key = chatKeys.sessions("ws-1");
+ if (hasCache) qc.setQueryData(key, []);
+ const session = { id: "session-1", title: "Release checklist" } as ChatSession;
+ let finishFirst!: (rows: ChatSession[]) => void;
+ const first = new Promise<ChatSession[]>((resolve) => {
+ finishFirst = resolve;
+ });
+ let fetches = 0;
+ const observer = new QueryObserver(qc, {
+ queryKey: key,
+ staleTime: Infinity,
+ queryFn: () => (++fetches === 1 ? first : Promise.resolve([session])),
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ try {
+ // The list GET read the newly created, still-untitled row; the send
+ // commits the title and its realtime event lands before that GET returns.
+ const inFlight = observer.refetch();
+ applyChatSessionUpdatedToCache(qc, "ws-1", {
+ chat_session_id: session.id,
+ title: session.title,
+ });
+ const refresh = refetchChatSessionsAfterCommit(qc, key);
+ finishFirst([{ ...session, title: "" }]);
+ await Promise.all([inFlight, refresh]);
+
+ expect(qc.getQueryData<ChatSession[]>(key)?.[0]?.title).toBe(session.title);
+ } finally {
+ unsubscribe();
+ qc.clear();
+ }
+ });
+});
diff --git a/packages/core/chat/session-list.ts b/packages/core/chat/session-list.ts
new file mode 100644
index 0000000000..c0f0439457
--- /dev/null
+++ b/packages/core/chat/session-list.ts
@@ -0,0 +1,18 @@
+import type { QueryClient, QueryKey } from "@tanstack/react-query";
+
+/**
+ * Refetch a chat sessions list so it reflects a server write that has just
+ * committed (e.g. the title a first send initializes).
+ *
+ * A bare invalidate joins a list request already in flight, and that request
+ * may have read the row before the write. With `staleTime: Infinity` its stale
+ * response would then stick, and a realtime patch cannot help while the row is
+ * not cached yet. Cancelling first makes the refetch start after the commit.
+ */
+export async function refetchChatSessionsAfterCommit(
+ qc: QueryClient,
+ queryKey: QueryKey,
+): Promise<void> {
+ await qc.cancelQueries({ queryKey });
+ await qc.invalidateQueries({ queryKey });
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index df00e8c477..98d94e01e0 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -80,6 +80,7 @@
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
"./chat/pending": "./chat/pending.ts",
+ "./chat/session-list": "./chat/session-list.ts",
"./chat/message-cache": "./chat/message-cache.ts",
"./chat/use-quick-actions-pending-timeout": "./chat/use-quick-actions-pending-timeout.ts",
"./chat/unread": "./chat/unread.ts",
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 3c450ada60..7aed14e877 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -196,6 +196,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => {
import { useChatController } from "./use-chat-controller";
import { api, ApiError } from "@multica/core/api";
+import { chatKeys } from "@multica/core/chat/queries";
// --- Fixtures ---------------------------------------------------------------
function makeSession(
@@ -402,6 +403,39 @@ describe("useChatController project context", () => {
);
});
+ it("creates the session untitled and refetches the list once the first send lands", async () => {
+ h.store.activeSessionId = null;
+ h.store.selectedAgentId = agentA.id;
+ h.sessions = [];
+ h.agents = [agentA];
+ h.queryClient.invalidateQueries.mockClear();
+ h.queryClient.cancelQueries.mockClear();
+ vi.mocked(api.sendChatMessage).mockResolvedValue({
+ message_id: "message-1",
+ task_id: "task-1",
+ created_at: new Date(0).toISOString(),
+ } as Awaited<ReturnType<typeof api.sendChatMessage>>);
+
+ const { result } = renderHook(() => useChatController());
+ await act(async () => {
+ await result.current.handleSend("# Release checklist\nmore", undefined, vi.fn());
+ });
+
+ expect(h.createSessionMutate).toHaveBeenCalledWith(
+ expect.not.objectContaining({ title: expect.anything() }),
+ );
+ const sessionsKey = { queryKey: chatKeys.sessions("ws-1") };
+ expect(h.queryClient.cancelQueries).toHaveBeenCalledWith(sessionsKey);
+ expect(h.queryClient.invalidateQueries).toHaveBeenCalledWith(sessionsKey);
+ const cancelOrder = h.queryClient.cancelQueries.mock.invocationCallOrder[0]!;
+ const refetchOrder = h.queryClient.invalidateQueries.mock.calls.findIndex(
+ ([arg]) => JSON.stringify(arg) === JSON.stringify(sessionsKey),
+ );
+ expect(cancelOrder).toBeLessThan(
+ h.queryClient.invalidateQueries.mock.invocationCallOrder[refetchOrder]!,
+ );
+ });
+
it("does not inherit the current session project when starting a new chat", () => {
const projectSession = makeSession({
id: "project-session",
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 97c76660f9..a16c4f9294 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -35,6 +35,7 @@ import {
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
import { upsertChatMessageToCaches } from "@multica/core/chat/message-cache";
+import { refetchChatSessionsAfterCommit } from "@multica/core/chat/session-list";
import {
enqueuePendingChatTask,
hideQueuedChatMessages,
@@ -55,23 +56,6 @@ import { useAppForeground } from "../../common/use-app-foreground";
const uiLogger = createLogger("chat.ui");
const apiLogger = createLogger("chat.api");
-// Derive a concise session title from the first user message: first line,
-// markdown stripped, whitespace collapsed, capped. A deterministic title
-// (no LLM) — the server has no summarization model, so this is the sensible
-// default until a runtime-generated title is wired up.
-const CHAT_TITLE_MAX = 30;
-export function deriveChatTitle(content: string): string {
- const firstLine = (content.split("\n").find((l) => l.trim()) ?? content).trim();
- const cleaned = firstLine
- .replace(/```[\s\S]*?```/g, " ")
- .replace(/[#*`>~_]/g, "")
- .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") // markdown links/images → their text
- .replace(/\s+/g, " ")
- .trim();
- if (cleaned.length <= CHAT_TITLE_MAX) return cleaned;
- return cleaned.slice(0, CHAT_TITLE_MAX - 1).trimEnd() + "…";
-}
-
/**
* After a send resolves: is the user still composing to the target they sent
* from? Decides whether to scrub the composer and open the sent session, or
@@ -417,7 +401,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
const sessionPromiseRef = useRef<Promise<string | null> | null>(null);
const ensureSession = useCallback(
- async (titleSeed: string): Promise<string | null> => {
+ async (): Promise<string | null> => {
// Trust the current session id only when it's real: present in the
// loaded list, or a just-created one still awaiting the list refetch
// (has an optimistic write). A dangling id (deleted / no access) must not
@@ -436,9 +420,10 @@ export function useChatController(opts?: { isActive?: boolean }) {
const promise = (async () => {
try {
+ // Untitled on purpose: the server derives the title from the first
+ // message it accepts, the same rule for every client and channel.
const session = await createSession.mutateAsync({
agent_id: activeAgent.id,
- title: deriveChatTitle(titleSeed),
project_id: activeProjectId,
});
return session.id;
@@ -536,7 +521,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
let sessionId: string | null = null;
try {
- sessionId = await ensureSession(finalContent);
+ sessionId = await ensureSession();
} catch (err) {
apiLogger.error("sendChatMessage.ensureSession.error", err);
// A revoked invoke permission blocks session create with a structured
@@ -620,6 +605,10 @@ export function useChatController(opts?: { isActive?: boolean }) {
supports_queue: result.supports_queue,
queued: result.queued,
});
+ // This send just committed the new session's server-derived title.
+ if (sessionId !== activeSessionId) {
+ void refetchChatSessionsAfterCommit(qc, chatKeys.sessions(wsId));
+ }
// Cache primed → publish the new active session, but only if the user
// hasn't navigated away mid-send. See isStillOnComposeTarget. commitInput
// clears the sent draft, and scrubs the shared editor only when the user
@@ -656,6 +645,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
return true;
},
[
+ wsId,
activeSessionId,
activeAgent,
isAgentArchived,
diff --git a/server/internal/chattitle/title.go b/server/internal/chattitle/title.go
index 4d92c065c5..e5a1d0f821 100644
--- a/server/internal/chattitle/title.go
+++ b/server/internal/chattitle/title.go
@@ -15,10 +15,10 @@ var (
titleSpace = regexp.MustCompile(`[[:space:]]+`)
)
-// Derive mirrors the existing first-party deterministic title policy for
-// channel-created Chats. Go slices valid Unicode code points rather than UTF-16
-// code units, while preserving the same first-line, Markdown, whitespace, and
-// 30-character single-ellipsis behavior.
+// Derive is the single deterministic title policy for a Chat's first message,
+// shared by first-party clients (which create sessions untitled) and channels:
+// first non-empty line, Markdown stripped, whitespace collapsed, capped at 30
+// code points with a single ellipsis.
func Derive(body string) string {
line := ""
for _, candidate := range strings.Split(body, "\n") {
diff --git a/server/internal/handler/chat_test.go b/server/internal/handler/chat_test.go
index 8342cb8f1b..b750dd5189 100644
--- a/server/internal/handler/chat_test.go
+++ b/server/internal/handler/chat_test.go
@@ -64,6 +64,50 @@ func TestSendChatMessage_ReportsPositionInsteadOfQueuedStatus(t *testing.T) {
}
}
+func TestSendChatMessage_FirstMessageTitlesUntitledSession(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ agentID := createHandlerTestAgent(t, "ChatSendFirstTitleAgent", []byte("[]"))
+ createReq := newRequest("POST", "/api/chat-sessions", map[string]any{"agent_id": agentID})
+ createReq = withChatTestWorkspaceCtx(t, createReq)
+ createW := httptest.NewRecorder()
+ testHandler.CreateChatSession(createW, createReq)
+ if createW.Code != http.StatusCreated {
+ t.Fatalf("CreateChatSession: expected 201, got %d: %s", createW.Code, createW.Body.String())
+ }
+ var created ChatSessionResponse
+ if err := json.Unmarshal(createW.Body.Bytes(), &created); err != nil {
+ t.Fatalf("decode create response: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, created.ID)
+ })
+ if created.Title != "" {
+ t.Fatalf("session created without a title got %q", created.Title)
+ }
+
+ req := newRequest("POST", "/api/chat-sessions/"+created.ID+"/messages", map[string]any{
+ "content": "\n# Release **checklist** for [MUL-1](mention://issue/abc)\nsecond line",
+ })
+ req = withURLParam(req, "sessionId", created.ID)
+ req = withChatTestWorkspaceCtx(t, req)
+ w := httptest.NewRecorder()
+ testHandler.SendChatMessage(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("SendChatMessage: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+
+ session, err := testHandler.Queries.GetChatSession(context.Background(), parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("load session: %v", err)
+ }
+ if session.Title != "Release checklist for MUL-1" {
+ t.Fatalf("title = %q, want the server-derived first-message title", session.Title)
+ }
+}
+
func TestSendChatMessage_DeferredPredecessorStaysHeadAcrossPromotion(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")