Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): name Claude Code chats in a shared title session

Elian Dorana760d59ba277
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.ts
index ec47932709..3d7f0eed0c 100644
--- a/apps/server/src/services/llm/providers/acp_agent.ts
+++ b/apps/server/src/services/llm/providers/acp_agent.ts
@@ -33,7 +33,7 @@ import dataDirs from "../../data_dir.js";
import { AcpClient, AcpError } from "./acp_client.js";
import { AcpClientPool, type AcpLease, type AcpPoolConnection } from "./acp_client_pool.js";
import { getAcpMcpEndpointUrl } from "./acp_mcp_endpoint.js";
-import { buildHistoryReplay, hashTranscript } from "./transcript.js";
+import { buildHistoryReplay, buildTitlePrompt, cleanTitle, hashTranscript, MAX_TITLES_PER_SESSION } from "./transcript.js";
/** How an ACP provider starts its agent subprocess. */
export interface AcpLaunchSpec {
@@ -140,13 +140,6 @@ const PROMPT_TIMEOUT_MS = 15 * 60_000;
/** Session mappings kept per chat note; bounded to avoid unbounded growth. */
const MAX_TRACKED_SESSIONS = 200;
-/**
- * Titles one session answers before it is replaced. Titles share a session to
- * skip `session/new` (~2.5 s on Antigravity, which also keeps every session on
- * disk); the cap bounds the history each title prompt carries.
- */
-export const MAX_TITLES_PER_SESSION = 20;
-
/** The name the loopback MCP server is registered under in `session/new`. */
export const NOTE_TOOLS_MCP_SERVER_NAME = "trilium";
@@ -684,17 +677,12 @@ export abstract class AcpAgentProvider implements LlmProvider {
"session/prompt",
{
sessionId,
- prompt: [{
- type: "text",
- text: `Generate a short title (at most 5 words) summarizing the chat message below. It is a new request: earlier messages in this conversation do not apply. Reply with only the title, no quotes or punctuation around it:
-
-${firstMessage.substring(0, 500)}`
- }]
+ prompt: [{ type: "text", text: buildTitlePrompt(firstMessage) }]
},
SESSION_TIMEOUT_MS
);
answered = true;
- return title.trim().replace(/^["']|["']$/g, "").substring(0, 100);
+ return cleanTitle(title);
} catch (error) {
getLog().error(`${this.logLabel} title generation failed: ${this.describeFailure(error)}`);
return "";
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.ts
index 82465ded35..536f695c43 100644
--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts
@@ -58,6 +58,7 @@ vi.mock("child_process", () => ({ spawn: spawnMock }));
const { buildSeededPrompt, buildSubscriptionModelList, ClaudeAgentProvider, hashTranscript, resetAgentCwdForTests, resetSubscriptionModelCacheForTests } = await import("./claude_agent.js");
const { MAX_WARM_SESSIONS, Pushable, releaseSession, rememberSession: rememberWarmSession, resetClaudeSessionPoolForTests } = await import("./claude_session_pool.js");
+const { buildTitlePrompt, MAX_TITLES_PER_SESSION } = await import("./transcript.js");
type PushablePrompt = { pending: readonly { message: { role: string; content: unknown[] } }[] };
/**
@@ -1083,37 +1084,131 @@ describe("ClaudeAgentProvider.chatChunks", () => {
describe("generateTitle", () => {
beforeEach(() => {
queryMock.mockReset();
+ errorLogMock.mockReset();
+ resetClaudeSessionPoolForTests();
+ closeMock.mockClear();
});
- it("returns the agent's one-shot result with surrounding quotes stripped", async () => {
- scriptAgent([{ ...successResult(), result: '"Meeting Notes Summary"' }]);
+ it("names chats in one shared session on the cheap model, one title at a time", async () => {
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const answered: string[] = [];
+ scriptTitleAgent(async prompt => {
+ inFlight++;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise(resolve => setTimeout(resolve, 5));
+ inFlight--;
+ const name = prompt.slice(prompt.lastIndexOf("\n") + 1);
+ answered.push(name);
+ return [textDelta("streamed noise"), titleResult(` "${name.toUpperCase()} notes" `)];
+ });
+
const provider = new ClaudeAgentProvider();
- await expect(provider.generateTitle("summarize my meeting notes")).resolves.toBe("Meeting Notes Summary");
+ await expect(Promise.all([provider.generateTitle("a"), provider.generateTitle("b"), provider.generateTitle("c")]))
+ .resolves.toEqual(["A notes", "B notes", "C notes"]);
+ expect(answered).toEqual(["a", "b", "c"]);
+ expect(maxInFlight).toBe(1);
+ expect(queryMock).toHaveBeenCalledTimes(1);
const options = queryMock.mock.calls[0][0].options;
- expect(options.maxTurns).toBe(1);
- expect(options.persistSession).toBe(false);
+ expect(options).toMatchObject({ model: "claude-haiku-4-5-20251001", maxTurns: 1, persistSession: false });
+ expect(options.mcpServers).toBeUndefined();
+ expect(closeMock).not.toHaveBeenCalled();
});
- it("returns an empty string when the agent fails", async () => {
- queryMock.mockImplementation(() => (async function* () {
- throw new Error("not logged in");
- yield undefined;
- })());
+ it("sends the shared title prompt, which tells the agent to ignore earlier titles", async () => {
+ const prompts: string[] = [];
+ scriptTitleAgent(async prompt => {
+ prompts.push(prompt);
+ return [titleResult("Title")];
+ });
+
+ await new ClaudeAgentProvider().generateTitle("x".repeat(600));
+
+ expect(prompts).toEqual([buildTitlePrompt("x".repeat(600))]);
+ expect(prompts[0]).toContain("earlier messages in this conversation do not apply");
+ });
+
+ it("replaces the title session when it is full, failed, or its stream ended", async () => {
+ scriptTitleAgent(async prompt => {
+ if (prompt.endsWith("boom")) {
+ throw new Error("agent crashed");
+ }
+ if (prompt.endsWith("quit")) {
+ return null;
+ }
+ return [titleResult("Title")];
+ });
const provider = new ClaudeAgentProvider();
- await expect(provider.generateTitle("hello")).resolves.toBe("");
+
+ // Full: the next title starts a new session and closes the old one.
+ for (let i = 0; i <= MAX_TITLES_PER_SESSION; i++) {
+ await expect(provider.generateTitle("hi")).resolves.toBe("Title");
+ }
+ expect(queryMock).toHaveBeenCalledTimes(2);
+ expect(closeMock).toHaveBeenCalledTimes(1);
+
+ // Failed: the session is closed, the failure logged, and the next title starts another.
+ await expect(provider.generateTitle("boom")).resolves.toBe("");
+ expect(closeMock).toHaveBeenCalledTimes(2);
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("agent crashed"));
+ await expect(provider.generateTitle("hi")).resolves.toBe("Title");
+ expect(queryMock).toHaveBeenCalledTimes(3);
+
+ // Ended: a stream that stops before its result yields no title, and the next title starts another.
+ await expect(provider.generateTitle("quit")).resolves.toBe("");
+ await expect(provider.generateTitle("hi")).resolves.toBe("Title");
+ expect(queryMock).toHaveBeenCalledTimes(4);
});
- it("skips non-result messages and returns empty on a non-success result", async () => {
- scriptAgent([textDelta("streamed noise"), { ...successResult(), result: "The Title" }]);
+ it("keeps the session after an unsuccessful result, which leaves it in a known state", async () => {
+ scriptTitleAgent(async prompt => (prompt.endsWith("fail")
+ ? [{ ...successResult(), subtype: "error_during_execution", is_error: true, errors: [] }]
+ : [titleResult("Title")]));
const provider = new ClaudeAgentProvider();
- await expect(provider.generateTitle("hello")).resolves.toBe("The Title");
- scriptAgent([{ ...successResult(), subtype: "error_during_execution", is_error: true, errors: [] }]);
- await expect(provider.generateTitle("hello")).resolves.toBe("");
+ await expect(provider.generateTitle("fail")).resolves.toBe("");
+ await expect(provider.generateTitle("hi")).resolves.toBe("Title");
+
+ expect(queryMock).toHaveBeenCalledTimes(1);
+ expect(closeMock).not.toHaveBeenCalled();
+ });
+
+ it("returns an empty title and logs when the agent cannot start", async () => {
+ resolveClaudeBinaryMock.mockRejectedValueOnce(new Error("claude not found"));
+
+ await expect(new ClaudeAgentProvider().generateTitle("hi")).resolves.toBe("");
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("claude not found"));
});
});
+/**
+ * A title session: Claude Code in streaming input mode, answering each message
+ * pushed onto its input with what `reply` returns for its text. `null` ends the
+ * stream, as a process that exits does.
+ */
+function scriptTitleAgent(reply: (prompt: string) => Promise<unknown[] | null>) {
+ type Pushed = { message: { content: { text: string }[] } };
+ queryMock.mockImplementation(({ prompt }: { prompt: string | AsyncIterable<Pushed> }) => {
+ const generator = (async function* () {
+ const input = typeof prompt === "string" ? [prompt] : prompt;
+ for await (const pushed of input) {
+ const text = typeof pushed === "string" ? pushed : pushed.message.content.map(block => block.text).join("");
+ const messages = await reply(text);
+ if (!messages) {
+ return;
+ }
+ yield* messages;
+ }
+ })();
+ return Object.assign(generator, { setModel: setModelMock, close: closeMock });
+ });
+}
+
+function titleResult(title: string) {
+ return { ...successResult(), result: title };
+}
+
describe("transcript helpers", () => {
it("hashTranscript is stable across content shapes and sensitive to edits", () => {
const stringForm = hashTranscript([{ role: "user", content: "hello" }]);
diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.ts
index e9f71bdb43..c202ea58d1 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -46,7 +46,7 @@ import {
rememberSession as rememberWarmSession,
takeWarmSession
} from "./claude_session_pool.js";
-import { buildHistoryReplay, flattenContent, hashTranscript } from "./transcript.js";
+import { buildHistoryReplay, buildTitlePrompt, cleanTitle, flattenContent, hashTranscript, MAX_TITLES_PER_SESSION } from "./transcript.js";
// Re-exported for existing importers (specs, siblings); the implementations
// now live in the shared transcript module.
@@ -143,6 +143,13 @@ const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
const TITLE_MODEL = "claude-haiku-4-5-20251001";
+/**
+ * The pool key of the session titles share. Note IDs never contain a colon, so
+ * it cannot collide with a chat's own session.
+ */
+const TITLE_SESSION_KEY = ":title";
+const TITLE_FINGERPRINT = "title";
+
/** Upper bound on assistant↔tool round-trips within one chat turn. */
const MAX_TURNS = 25;
@@ -178,6 +185,11 @@ interface SessionEntry {
*/
const sessionsByChatNote = new Map<string, SessionEntry>();
+/** Titles the current title session answered, counting the one in progress. */
+let titleCount = 0;
+/** Settles when the title in progress does; a session answers one prompt at a time. */
+let titleQueue: Promise<unknown> = Promise.resolve();
+
function rememberSession(chatNoteId: string, entry: SessionEntry) {
// Refresh insertion order so the oldest mapping is evicted first.
sessionsByChatNote.delete(chatNoteId);
@@ -630,11 +642,67 @@ export class ClaudeAgentProvider implements LlmProvider {
}
}
+ /**
+ * Name a chat after its first message, in the session titles share. Titles
+ * take turns, because a session answers one prompt at a time.
+ */
async generateTitle(firstMessage: string): Promise<string> {
+ const title = titleQueue.then(() => this.requestTitle(firstMessage));
+ titleQueue = title;
+ return title;
+ }
+
+ private async requestTitle(firstMessage: string): Promise<string> {
+ let session: ClaudeSession | undefined;
+ let answered = false;
try {
- const query = await loadQuery();
- const response = query({
- prompt: `Generate a short title (at most 5 words) summarizing this chat message. Reply with only the title, no quotes or punctuation around it:\n\n${firstMessage.substring(0, 500)}`,
+ session = await this.titleSession();
+ await pushUserTurn(session.input, buildTitlePrompt(firstMessage));
+ // Manual iteration, as in chatChunks(): breaking out of `for await` closes the query.
+ for (;;) {
+ const next = await session.query.next();
+ if (next.done) {
+ session.closed = true;
+ return "";
+ }
+ const message = next.value;
+ if (message.type === "result") {
+ answered = true;
+ return message.subtype === "success" ? cleanTitle(message.result) : "";
+ }
+ }
+ } catch (error) {
+ getLog().error(`Claude Agent title generation failed: ${describeAgentError(error)}`);
+ return "";
+ } finally {
+ // A title that got no result leaves the session in an unknown state.
+ if (session && answered) {
+ releaseSession(TITLE_SESSION_KEY, session);
+ } else if (session) {
+ closeSession(TITLE_SESSION_KEY, session);
+ }
+ }
+ }
+
+ /**
+ * The warm title session, or a new one on {@link TITLE_MODEL} when there is
+ * none or the current one reached {@link MAX_TITLES_PER_SESSION}.
+ */
+ private async titleSession(): Promise<ClaudeSession> {
+ const warm = takeWarmSession(TITLE_SESSION_KEY, TITLE_FINGERPRINT);
+ if (warm && titleCount < MAX_TITLES_PER_SESSION) {
+ titleCount++;
+ return warm;
+ }
+ if (warm) {
+ closeSession(TITLE_SESSION_KEY, warm);
+ }
+
+ const query = await loadQuery();
+ const input = new Pushable<SDKUserMessage>();
+ const session: ClaudeSession = {
+ query: query({
+ prompt: input,
options: {
...await this.buildBaseOptions({ enableNoteTools: false }),
systemPrompt: "You generate short, descriptive titles. Reply with only the title text — no quotes, no punctuation around it.",
@@ -642,17 +710,16 @@ export class ClaudeAgentProvider implements LlmProvider {
maxTurns: 1,
persistSession: false
}
- });
-
- for await (const message of response) {
- if (message.type === "result" && message.subtype === "success") {
- return message.result.trim().replace(/^["']|["']$/g, "").substring(0, 100);
- }
- }
- } catch (error) {
- getLog().error(`Claude Agent title generation failed: ${describeAgentError(error)}`);
- }
- return "";
+ }),
+ input,
+ fingerprint: TITLE_FINGERPRINT,
+ closed: false,
+ busy: true,
+ model: TITLE_MODEL
+ };
+ rememberWarmSession(TITLE_SESSION_KEY, session);
+ titleCount = 1;
+ return session;
}
/**
diff --git a/apps/server/src/services/llm/providers/claude_session_pool.ts b/apps/server/src/services/llm/providers/claude_session_pool.ts
index 70f3c573b1..0f11f66b86 100644
--- a/apps/server/src/services/llm/providers/claude_session_pool.ts
+++ b/apps/server/src/services/llm/providers/claude_session_pool.ts
@@ -18,8 +18,9 @@
* manual: `for await (…) { break }` calls `iterator.return()`, which would
* close the query and defeat the whole point.
*
- * Sessions are keyed by chat note, reaped after {@link IDLE_TIMEOUT_MS}, and
- * rebuilt whenever an option that is fixed at construction changes.
+ * Sessions are keyed by chat note, plus one key for the session chat titles
+ * share, reaped after {@link IDLE_TIMEOUT_MS}, and rebuilt whenever an option
+ * that is fixed at construction changes.
*/
import type { Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
index 86f2501a47..433e609986 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
@@ -141,7 +141,8 @@ class FakeAcpError extends Error {
vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));
-const { buildPromptBlocks, createUpdateCollector, denyPermission, MAX_TITLES_PER_SESSION } = await import("./acp_agent.js");
+const { buildPromptBlocks, createUpdateCollector, denyPermission } = await import("./acp_agent.js");
+const { MAX_TITLES_PER_SESSION } = await import("./transcript.js");
const { IDLE_TIMEOUT_MS } = await import("./acp_client_pool.js");
const { buildCopilotModelList, CopilotAgentProvider, resetModelCatalogCacheForTests } = await import("./copilot_agent.js");
diff --git a/apps/server/src/services/llm/providers/transcript.ts b/apps/server/src/services/llm/providers/transcript.ts
index 92b4aa364c..1e2c3c055f 100644
--- a/apps/server/src/services/llm/providers/transcript.ts
+++ b/apps/server/src/services/llm/providers/transcript.ts
@@ -1,9 +1,10 @@
/**
* Transcript helpers shared by the session-based agent providers (Claude
- * Agent, Copilot Agent). These providers own their conversation history in
+ * Agent and the ACP agents). These providers own their conversation history in
* host-side sessions, so they need a stable way to detect whether the
- * transcript the client sent still matches a mapped session (hash) and to
- * reseed a fresh session when it doesn't (replay).
+ * transcript the client sent still matches a mapped session (hash), to
+ * reseed a fresh session when it doesn't (replay), and to name chats in a
+ * session that several titles share.
*/
import type { LlmMessage, LlmMessagePart } from "@triliumnext/commons";
@@ -45,3 +46,22 @@ export function flattenContent(content: string | LlmMessagePart[]): string {
.map(part => (part.type === "text" ? part.text : attachmentPlaceholder(part)))
.join("\n");
}
+
+/**
+ * Titles one session answers before it is replaced. Titles share a session to
+ * skip the session start (~2.5 s on Antigravity, which also keeps every session
+ * on disk); the cap bounds the history each title prompt carries.
+ */
+export const MAX_TITLES_PER_SESSION = 20;
+
+/** The prompt that names a chat after its first message, in a session shared by earlier titles. */
+export function buildTitlePrompt(firstMessage: string): string {
+ return `Generate a short title (at most 5 words) summarizing the chat message below. It is a new request: earlier messages in this conversation do not apply. Reply with only the title, no quotes or punctuation around it:
+
+${firstMessage.substring(0, 500)}`;
+}
+
+/** The agent's title reply without surrounding whitespace or quotes, capped at 100 characters. */
+export function cleanTitle(reply: string): string {
+ return reply.trim().replace(/^["']|["']$/g, "").substring(0, 100);
+}