Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(server): generate session titles from user input alone, with immediate fallback (#367)

Yaowei Zheng4f29ab69e0e2
diff --git a/changelog/unreleased/2026-08-20-title-from-input.md b/changelog/unreleased/2026-08-20-title-from-input.md
new file mode 100644
index 00000000..310899d0
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-title-from-input.md
@@ -0,0 +1,17 @@
+# Session titles generate from the user input alone, with an immediate fallback
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `server`
+- **PR:** [#367](https://github.com/Prism-Shadow/penguin-harness/pull/367)
+
+[中文版](2026-08-20-title-from-input.zh.md)
+
+Reworked automatic Session title generation so it never waits for model output. The moment a Task starts with user text, the first words of that text are persisted as a fallback title and pushed to the UI; the LLM title request fires at the same time, in the background, with the user input as its only material, and replaces the fallback when it lands. Previously the title appeared only after enough of the answer had streamed (or the Task finished), and the generation prompt could include assistant text.
+
+## Details
+
+- The fallback truncation became word-aware: long English input is cut at a word boundary instead of mid-word, CJK input is cut per character, and leading punctuation no longer consumes the length budget.
+- A manual rename is final: the LLM result only ever replaces the fallback the generator itself wrote, and while that fallback is still standing after an LLM failure, the next Task start retries the request.
+- A subagent's title now generates at registration, from the `run_subagent` prompt that spawned it, instead of at the end of the parent's run from the subagent's collected output — subagent titles appear while the run is still going.
+- `session_title` now also rides the user-level event channel (the same delivery `session_state` uses), and the Web routes it into the session list from there; the draft flow re-fetches the row after the first task starts. Start-of-run titles fire before the new conversation's own channel has any subscriber, so without these the list kept showing the "New chat" placeholder.
diff --git a/changelog/unreleased/2026-08-20-title-from-input.zh.md b/changelog/unreleased/2026-08-20-title-from-input.zh.md
new file mode 100644
index 00000000..265585fa
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-title-from-input.zh.md
@@ -0,0 +1,17 @@
+# 会话标题仅由用户输入生成,并即时写入 fallback
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `server`
+- **PR:** [#367](https://github.com/Prism-Shadow/penguin-harness/pull/367)
+
+[English](2026-08-20-title-from-input.md)
+
+重做了 Session 标题的自动生成,使其完全不等待模型输出。Task 一开始,用户输入的前几个词就被持久化为 fallback 标题并推送到界面;同时在后台发起 LLM 标题请求,材料只含用户输入,生成成功后替换 fallback。此前标题要等回答流式输出到一定长度(或 Task 结束)才出现,且生成 prompt 可能包含助手文本。
+
+## 细节
+
+- fallback 截断改为按词处理:较长的英文输入在词边界截断而不再从单词中间切开,CJK 输入按字截断,行首标点不再占用长度预算。
+- 手动重命名为最终值:LLM 结果只会替换生成器自己写入的 fallback;LLM 失败后 fallback 仍在时,下一次 Task 开始会重试请求。
+- subagent 的标题改为在注册时由派生它的 `run_subagent` prompt 生成,不再等父会话运行结束后用 subagent 的输出汇总生成——运行途中即可看到 subagent 标题。
+- `session_title` 现在同时走用户级事件通道(与 `session_state` 同一条列表通道),Web 从该通道更新会话列表;草稿流程在首个任务启动后重新拉取会话行。运行起点生成的标题在新会话自身通道尚无订阅者时就已推送,没有这两处改动列表会一直停留在「新对话」占位。
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 4c7175af..76792f72 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -31,6 +31,7 @@ import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
import { UsageRepo } from "./db/repos/usage.js";
import { UsersRepo } from "./db/repos/users.js";
import type { UserRow } from "./db/repos/users.js";
+import type { ServerEvent } from "./api/types.js";
import { authMiddleware, jsonOnlyWrites, SESSION_COOKIE } from "./auth/middleware.js";
import { IDENTITY_RESOURCE_ID } from "./platform/terminal/identity.js";
import type { AppEnv } from "./auth/middleware.js";
@@ -238,9 +239,34 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
});
const recorder = new UsageRecorder(usageRepo, overrides.now ?? (() => new Date()));
const errors = new ErrorRecorder(errorsRepo, overrides.now ?? (() => new Date()));
+ // Shared by SessionManager (run-state flips) and TitleGenerator (title updates): both are
+ // list-row facts that must reach tabs not subscribed to the Session's own channel.
+ //
+ // Audience = the Project's owner plus its members, i.e. exactly who
+ // ProjectsRepo.listAccessible would grant the Project to — nobody learns that a Session they
+ // cannot open changed state or gained a title.
+ //
+ // `peek`, deliberately not `get`: a user who has never opened an event stream has no
+ // channel, and conjuring one to buffer badge updates nobody is listening to is pure waste
+ // (their next connection fetches the list, which carries the same statuses anyway).
+ const notifyProjectUsers = (projectId: string, event: ServerEvent): void => {
+ const ownerUserId = projectsRepo.findById(projectId)?.ownerUserId;
+ if (ownerUserId === undefined) return;
+ const audience = new Set([ownerUserId, ...membersRepo.list(projectId).map((m) => m.userId)]);
+ for (const userId of audience) {
+ channels.peek(userChannelKey(userId))?.publish(event, "server_event");
+ }
+ };
const titles =
overrides.titles ??
- new TitleGenerator({ sessions: sessionsRepo, channels, recorder, errors, log });
+ new TitleGenerator({
+ sessions: sessionsRepo,
+ channels,
+ recorder,
+ errors,
+ log,
+ notifyProjectUsers,
+ });
const manager = new SessionManager({
sessions: sessionsRepo,
channels,
@@ -252,21 +278,8 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
log,
goals: goalsRepo,
// Run-state flips reach the whole login session, not just the tab watching that one
- // conversation. Audience = the Project's owner plus its members, i.e. exactly who
- // ProjectsRepo.listAccessible would grant the Project to — nobody learns that a Session
- // they cannot open changed state.
- //
- // `peek`, deliberately not `get`: a user who has never opened an event stream has no
- // channel, and conjuring one to buffer badge updates nobody is listening to is pure waste
- // (their next connection fetches the list, which carries the same statuses anyway).
- notifyProjectUsers: (projectId, event) => {
- const ownerUserId = projectsRepo.findById(projectId)?.ownerUserId;
- if (ownerUserId === undefined) return;
- const audience = new Set([ownerUserId, ...membersRepo.list(projectId).map((m) => m.userId)]);
- for (const userId of audience) {
- channels.peek(userChannelKey(userId))?.publish(event, "server_event");
- }
- },
+ // conversation (see the shared publisher above for the audience).
+ notifyProjectUsers,
...(overrides.now ? { now: overrides.now } : {}),
});
managerRef = manager;
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 243a3015..edcc9bbf 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -554,7 +554,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
}
let updated: SessionRow = { ...row };
if (title !== undefined) {
- // Manual renaming takes priority over auto-generation: TitleGenerator only persists a title while it's still NULL.
+ // Manual renaming takes priority over auto-generation: TitleGenerator only ever replaces the fallback title it wrote itself, never a manual rename.
deps.sessionsRepo.updateTitle(row.sessionId, title);
updated = { ...updated, title };
}
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 9789309b..b85351b4 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -364,16 +364,6 @@ interface RuntimeEntry {
const ENTRY_IDLE_MS = 30 * 60 * 1000;
const ENTRY_SWEEP_INTERVAL_MS = 60 * 1000;
-/** Cap on collected model text for title material (accumulation stops beyond this; the generator side also truncates further). */
-const TITLE_EXCERPT_LIMIT = 4000;
-/**
- * Early title trigger: once this many characters of main-session body text have streamed,
- * title generation starts right away instead of waiting for the Task to finish — the core
- * Session has captured its (capped) material by then, and a long answer would only overrun
- * it. Short conversations are still covered by the completion trigger in drive's finally.
- */
-const EARLY_TITLE_BODY_CHARS = 1000;
-
/** Composite Agent key (used as a Set key, avoiding projectId/agentId concatenation ambiguity). */
function agentKey(projectId: string, agentId: string): string {
return `${projectId}\0${agentId}`;
@@ -434,11 +424,8 @@ function settledToolCallId(msg: OmniMessage): string | null {
interface ChildSession {
sessionId: string;
agentId: string;
- modelId: string;
/** The prompt of the run_subagent call that spawned it (user material for title generation, and the fallback title). */
prompt: string;
- /** The model text the subagent itself produced (assistant material for title generation). */
- assistantExcerpt: string;
}
/** Predicate for a plain-text message on the main session (no origin): title material is drawn only from user/model text. */
@@ -454,14 +441,6 @@ function isPlainText(role: "user" | "assistant") {
};
}
-/** For a nested message, the owning Session (end of the origin chain) and text of the model reply; null if it isn't model text. */
-function nestedAssistantText(msg: OmniMessage): { sessionId: string; text: string } | null {
- const p = msg.payload as { type?: string; role?: string; text?: string };
- if (msg.type !== "model_msg" || p.type !== "text" || p.role !== "assistant") return null;
- if (!msg.origin || msg.origin.length === 0 || typeof p.text !== "string") return null;
- return { sessionId: msg.origin[msg.origin.length - 1]!, text: p.text };
-}
-
export class SessionManager {
private readonly entries = new Map<string, RuntimeEntry>();
/** Per-Session mutex (serializes get-or-load and status flips); auto-cleaned once the chain drains. */
@@ -920,9 +899,9 @@ export class SessionManager {
signal: ac.signal,
...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
});
- // Title material is collected by the core Session itself during run; here we only
- // keep this call's input user text, used both as the "material present → attempt
- // generation" criterion and as the fallback title source if the LLM call fails.
+ // This call's input user text is the whole title source: drive persists its first
+ // words as the immediate fallback and hands it to the LLM as the generation material
+ // (user input only — generation never waits for model output).
const userExcerpt = input
.filter(isPlainText("user"))
.map((m) => m.payload.text)
@@ -1404,15 +1383,13 @@ export class SessionManager {
* Drive the output stream in the background: publish each message + persist usage +
* persist LLM/tool errors; on completion (including errors) resets to idle and pushes
* the status. `titleSource` is passed only for Task runs (compaction doesn't generate
- * a title): it collects model text for automatic title generation.
+ * a title): its user text drives automatic title generation at run start.
*/
private async drive(
entry: RuntimeEntry,
gen: AsyncGenerator<OmniMessage>,
titleSource?: { userExcerpt: string },
): Promise<void> {
- let earlyTitleFired = false;
- let mainBodyChars = 0;
const ctx: UsageContext = {
projectId: entry.projectId,
agentId: entry.agentId,
@@ -1420,6 +1397,16 @@ export class SessionManager {
provider: entry.provider,
modelId: entry.modelId,
};
+ // Title policy fires at run start, from the user input alone: the generator persists
+ // the input's first words as an immediate fallback and issues the LLM replacement
+ // request without waiting for any model output (maybeGenerate self-guards: manual
+ // renames are final, one generation in flight per session).
+ if (titleSource?.userExcerpt.trim()) {
+ this.deps.titles?.maybeGenerate(ctx, entry.session, {
+ fallbackText: titleSource.userExcerpt,
+ material: { userText: titleSource.userExcerpt, assistantText: "" },
+ });
+ }
// Every driven run (a Task, a compaction, or a whole goal loop — startGoal hands all of
// its rounds to ONE drive) writes Trace lines: flip the row's has_trace cache here, the
// single choke point, so listing can serve it from the DB without a directory walk (see
@@ -1450,7 +1437,7 @@ export class SessionManager {
// yields it), so we can't rely on the subagent's first user message; instead we use
// the run_subagent tool_call arguments immediately preceding it on the parent stream
// (depth limited to 1, spawned in order, so taking the most recent one suffices).
- /** Subagents registered during this run (keyed by session id); titles are generated for each on completion. */
+ /** Subagents registered during this run (keyed by session id); each gets its title generated at registration, from its spawning prompt alone. */
const children = new Map<string, ChildSession>();
// Unclaimed run_subagent prompts, queued in call order: a single round may spawn
// multiple subagents in parallel, and a subagent's session_meta only carries the
@@ -1495,6 +1482,24 @@ export class SessionManager {
child.prompt = subagentPrompts.get(pendingId) ?? "";
subagentPrompts.delete(pendingId); // Consumed by this session_meta
}
+ // The subagent's title is generated right here at registration, from the
+ // spawning prompt alone (its "user input") — never waiting for the
+ // subagent's own output. It piggybacks a one-shot request on the parent
+ // Session's bare LLM (the child Session object never leaves the SDK):
+ // Session/Agent record the subagent (the title belongs to it), but the
+ // model reference keeps ctx's parent-Session (provider, modelId) pair —
+ // a subagent may switch models via run_subagent's model_id.
+ if (child.prompt.trim()) {
+ this.deps.titles?.maybeGenerate(
+ { ...ctx, agentId: child.agentId, sessionId: child.sessionId },
+ entry.session,
+ {
+ fallbackText: child.prompt,
+ material: { userText: child.prompt, assistantText: "" },
+ notifyOn: entry.sessionId, // Notify the frontend via the parent Session's SSE channel
+ },
+ );
+ }
}
} catch (err) {
this.log(
@@ -1507,35 +1512,6 @@ export class SessionManager {
code: "subagent_register_failed",
});
}
- } else {
- // A subagent's model text: its title is generated from the subagent's **own
- // conversation**, so the material is accumulated here.
- const nested = nestedAssistantText(msg);
- const child = nested ? children.get(nested.sessionId) : undefined;
- if (nested && child && child.assistantExcerpt.length < TITLE_EXCERPT_LIMIT) {
- child.assistantExcerpt += (child.assistantExcerpt ? "\n" : "") + nested.text;
- }
- }
- // Early title trigger (see EARLY_TITLE_BODY_CHARS): fire as soon as enough main-
- // session body text has streamed; maybeGenerate self-guards (NULL title, single
- // flight), so the completion trigger in finally stays as the short-answer fallback.
- if (!earlyTitleFired && titleSource?.userExcerpt.trim()) {
- const p = msg.payload as { type?: string; role?: string; text?: string };
- if (
- (!msg.origin || msg.origin.length === 0) &&
- msg.type === "model_msg" &&
- p.type === "text" &&
- p.role === "assistant" &&
- p.text
- ) {
- mainBodyChars += p.text.length;
- if (mainBodyChars >= EARLY_TITLE_BODY_CHARS) {
- earlyTitleFired = true;
- this.deps.titles?.maybeGenerate(ctx, entry.session, {
- fallbackText: titleSource.userExcerpt,
- });
- }
- }
}
// Bootstrap records (first-run MCP connect + toolset): held for GET /messages
// until the engine's deferred Trace write catches up (see pendingBootstrap).
@@ -1598,62 +1574,29 @@ export class SessionManager {
entry.pendingSteering = [];
entry.lastActivityMs = Date.now();
// Run-end stamp (see the run-start counterpart at the top of drive). Guarded like
- // every other write in this finally: what follows — the idle broadcast, title
- // generation, and the auto-start of queued follow-ups (this is its only call site) —
- // must not be skippable by a DB failure, or SSE clients would sit on "running"
- // forever with their queue stranded. A no-op UPDATE when the row is already gone:
- // deletion normally awaits the drive first, so that only happens once its 5s wait
- // times out.
+ // every other write in this finally: what follows — the idle broadcast and the
+ // auto-start of queued follow-ups (this is its only call site) — must not be
+ // skippable by a DB failure, or SSE clients would sit on "running" forever with
+ // their queue stranded. A no-op UPDATE when the row is already gone: deletion
+ // normally awaits the drive first, so that only happens once its 5s wait times out.
this.touchRow(ctx, (repo, at) => repo.touchLastActive(ctx.sessionId, at));
this.publishState(entry, "idle");
- if (titleSource && titleSource.userExcerpt.trim()) {
- // Attempt generation whenever there's user material; whether generation is
- // actually needed (title still NULL, etc.) is decided by the generator itself.
- // Material is collected by the core Session during run; here we only pass the
- // fallback text.
- this.deps.titles?.maybeGenerate(ctx, entry.session, {
- fallbackText: titleSource.userExcerpt,
- });
- }
// Queued follow-ups: whenever a run finishes (Task or compaction, abort included),
// the next queued input auto-starts as an ordinary task. Fire-and-forget — it
// revalidates under the session lock.
if (entry.followUps.length > 0) void this.startQueuedFollowUp(entry.sessionId);
- // A subagent's title is likewise generated by the model, with material being the
- // subagent's **own conversation**: the prompt that spawned it plus its own reply
- // (material the parent Session collects belongs to the parent, hence the explicit
- // override here). It piggybacks a one-shot request on the parent Session's bare
- // LLM (the child Session object never leaves the SDK); on failure/empty result the
- // generator falls back to the prompt's first line.
- for (const child of children.values()) {
- if (!child.prompt.trim()) continue;
- this.deps.titles?.maybeGenerate(
- // Bookkeeping: Session/Agent record the subagent (the title belongs to it),
- // but the model reference still uses ctx's **parent-Session** pair
- // (provider, modelId) — this one-shot request really does run on the parent
- // Session's bare LLM (a subagent may switch models via run_subagent's
- // model_id).
- { ...ctx, agentId: child.agentId, sessionId: child.sessionId },
- entry.session,
- {
- fallbackText: child.prompt,
- material: { userText: child.prompt, assistantText: child.assistantExcerpt },
- notifyOn: entry.sessionId, // Notify the frontend via the parent Session's SSE channel
- },
- );
- }
}
}
/**
* Register a subagent: persisted only when the origin message is session_meta
* (agentId is derived from the agent_state path: `<…>/<agentId>/agent_state`).
- * **The title is left blank** — it's generated at the end of this run by the model
- * from the subagent's own conversation (see drive's finally), falling back to the
- * first line of the run_subagent prompt if generation fails. Idempotent (children
- * dedup + insertOrIgnore); a subagent has its own Trace, so it's visible in both the
- * list and the trace view. On successful registration, the entry is put into
- * `children` and returned; a duplicate session_meta returns null.
+ * **The title is left blank here** — the registration site in drive generates it
+ * right away from the spawning prompt (fallback first words + LLM replacement), so
+ * it never waits for the subagent's own output. Idempotent (children dedup +
+ * insertOrIgnore); a subagent has its own Trace, so it's visible in both the list
+ * and the trace view. On successful registration, the entry is put into `children`
+ * and returned; a duplicate session_meta returns null.
*/
private registerChildSession(
entry: RuntimeEntry,
@@ -1703,9 +1646,7 @@ export class SessionManager {
const child: ChildSession = {
sessionId: childSid,
agentId,
- modelId: p.model_id,
prompt: "",
- assistantExcerpt: "",
};
children.set(childSid, child);
return child;
diff --git a/packages/server/src/runtime/title-generator.ts b/packages/server/src/runtime/title-generator.ts
index e2f3529d..322bbde9 100644
--- a/packages/server/src/runtime/title-generator.ts
+++ b/packages/server/src/runtime/title-generator.ts
@@ -5,21 +5,29 @@
* "How to generate" lives in the core SDK (`session.generateTitle`: an out-of-band
* one-shot request on the session's own Model, no tools, thinking disabled, writes no
* history/Trace); this module is only responsible for host-side policy:
- * - When to generate: after a Task completes and the DB row's title is still NULL
- * (i.e. after the first successful conversation);
+ * - When: at Task start, from the **user input alone** — the moment a run begins with
+ * user text, the first words of that text are persisted as an immediate fallback
+ * title, and the LLM request fires in the background to replace it. Neither step
+ * waits for any model output.
* - Persistence and notification: writes sessions.title and pushes a `session_title`
- * server event to the Session channel;
+ * server event to the Session channel (once for the fallback, once more if the LLM
+ * result replaces it).
+ * - Manual renames win: the LLM result only ever replaces the fallback this generator
+ * wrote itself (tracked in memory per session); any other value is left alone.
* - Bookkeeping: the one-shot request's token consumption is converted to token_usage
* and handed to usage-recorder for persistence;
- * - Silent failure (logged): the title stays NULL and naturally retries after the next
- * Task completes.
+ * - Silent failure (logged): the fallback stays in place, and while the stored title
+ * still equals it the next Task start retries the LLM request.
*/
import {
emptyTokenCounts,
+ matchAttachedFileLine,
+ matchAttachedImageLine,
sanitizeTitle,
stripConversationMarkers,
tokenUsage,
} from "@prismshadow/penguin-core";
+import type { ServerEvent } from "../api/types.js";
import type { SessionsRepo } from "../db/repos/sessions.js";
import type { ChannelHub } from "./channel.js";
import type { ErrorSink } from "./error-recorder.js";
@@ -33,13 +41,21 @@ export interface TitleGeneratorDeps {
/** Error persistence (optional: without it, only logs — same as before this was wired up). */
errors?: ErrorSink;
log?: (line: string) => void;
+ /**
+ * Publishes the `session_title` event on the user-level channel of everyone who can see
+ * the Project (same contract as SessionManager's dep of the same name). This is what
+ * reaches the session list: titles land at Task start, typically before any tab has
+ * subscribed to the brand-new Session's own channel — the per-Session publish alone
+ * would be dropped unheard. Optional: without it only the per-Session channel is served.
+ */
+ notifyProjectUsers?: (projectId: string, event: ServerEvent) => void;
}
/** Host-side parameters for one title-generation request. */
export interface TitleRequest {
- /** Fallback material for when the LLM fails or returns an empty result (cleaned and truncated from the first non-empty line). */
+ /** The user input this run started from: its first words become the immediate fallback title. */
fallbackText: string;
- /** Material override (for subagents — the material is the subagent's own conversation); defaults to the first Task's material self-collected by the core Session. */
+ /** Material override (the main session passes its input text, a subagent the prompt that spawned it — assistant material stays empty either way, so the request never waits on model output); defaults to the material self-collected by the core Session. */
material?: { userText: string; assistantText: string };
/** The channel to push the `session_title` event to; defaults to `ctx.sessionId`. A
* subagent has no SSE channel of its own, so its title must reach the frontend via
@@ -58,20 +74,41 @@ export interface TitleNotifier {
export class TitleGenerator implements TitleNotifier {
private readonly inflight = new Set<string>();
+ /**
+ * sessionId → the fallback title this generator wrote and the LLM may still replace.
+ * An entry is dropped once the LLM result lands or a differing stored title (a manual
+ * rename, or a title from before a restart) is observed — from then on the title is
+ * treated as final. In-memory on purpose: the sessions table stores no auto/manual
+ * marker, and after a restart an existing title is simply left alone.
+ */
+ private readonly pendingFallbacks = new Map<string, string>();
private readonly log: (line: string) => void;
constructor(private readonly deps: TitleGeneratorDeps) {
this.log = deps.log ?? ((line) => console.error(line));
}
- /** Generate a title in the background (fire-and-forget) when conditions are met: the row exists, title is still NULL, and no generation is already in flight. */
+ /**
+ * Runs the title policy for one run start (fire-and-forget): persists the user-input
+ * fallback if the row has no title yet, then generates the LLM replacement in the
+ * background. No-ops when the stored title is anything other than NULL or the fallback
+ * this generator wrote (manual renames and pre-existing titles are final), or when a
+ * generation is already in flight.
+ */
maybeGenerate(
ctx: UsageContext,
session: Pick<RuntimeSession, "generateTitle">,
req: TitleRequest,
): void {
- const row = this.deps.sessions.findById(ctx.sessionId);
- if (!row || row.title !== null) return;
+ // Bookkeeping must never take down a run: call sites sit on the run's drive path, so
+ // a DB failure here is logged and swallowed like every other bookkeeping write.
+ try {
+ if (!this.prepare(ctx, req)) return;
+ } catch (err) {
+ this.log(`[title] Fallback failed: ${err instanceof Error ? err.message : String(err)}`);
+ this.deps.errors?.record({ source: "title", err, ctx, code: "title_fallback_failed" });
+ return;
+ }
if (this.inflight.has(ctx.sessionId)) return;
this.inflight.add(ctx.sessionId);
void this.generate(ctx, session, req)
@@ -84,6 +121,29 @@ export class TitleGenerator implements TitleNotifier {
});
}
+ /** Synchronous half of the policy: decides whether the LLM should run, writing the immediate fallback title on the way. */
+ private prepare(ctx: UsageContext, req: TitleRequest): boolean {
+ const row = this.deps.sessions.findById(ctx.sessionId);
+ if (!row) return false;
+ if (row.title !== null) {
+ // Only the fallback this generator wrote is still replaceable; anything else
+ // (manual rename, pre-restart title) is final.
+ if (row.title !== this.pendingFallbacks.get(ctx.sessionId)) {
+ this.pendingFallbacks.delete(ctx.sessionId);
+ return false;
+ }
+ return true;
+ }
+ // First words of the user input, persisted before the LLM request is even issued —
+ // the UI shows a title the moment the task starts.
+ const fallback = fallbackTitle(req.fallbackText);
+ if (fallback !== null) {
+ this.pendingFallbacks.set(ctx.sessionId, fallback);
+ this.persist(ctx, fallback, req.notifyOn);
+ }
+ return true;
+ }
+
private async generate(
ctx: UsageContext,
session: Pick<RuntimeSession, "generateTitle">,
@@ -91,8 +151,8 @@ export class TitleGenerator implements TitleNotifier {
): Promise<void> {
let title: string | null = null;
try {
- // Material defaults to what the core Session self-collects during run; it's only
- // overridden in scenarios like subagents where the material isn't on that Session.
+ // The material is the run's own user input (assistant material empty); it's absent
+ // only for callers that rely on the core Session's self-collected material.
const res = await session.generateTitle(
req.material ? { material: req.material } : undefined,
);
@@ -114,41 +174,106 @@ export class TitleGenerator implements TitleNotifier {
}
}
} catch (err) {
- // A model request error (rate limit / timeout / network, etc.) shouldn't leave the
- // title permanently missing: log it and fall through to the fallback.
+ // A model request error (rate limit / timeout / network, etc.) leaves the fallback
+ // title standing; while the stored title still equals it, the next Task start retries.
this.log(`[title] Model request failed: ${err instanceof Error ? err.message : String(err)}`);
this.deps.errors?.record({ source: "title", err, ctx, code: "title_llm_failed" });
}
- // When the LLM produces no usable title (failure / empty result), truncate the fallback material's first line — this guarantees a title is always generated.
- const finalTitle = title ?? fallbackTitle(req.fallbackText);
- if (finalTitle === null) return;
- // There may already be a concurrent write during generation (e.g. a future manual rename): only persist if still NULL.
+ if (title === null) return;
+ // The LLM result replaces only the fallback this generator wrote (or fills a still-NULL
+ // title); a manual rename that landed during generation wins.
const latest = this.deps.sessions.findById(ctx.sessionId);
- if (!latest || latest.title !== null) return;
- this.deps.sessions.updateTitle(ctx.sessionId, finalTitle);
- this.deps.channels
- .get(req.notifyOn ?? ctx.sessionId)
- .publish(
- { type: "session_title", sessionId: ctx.sessionId, title: finalTitle },
- "server_event",
- );
+ if (!latest) return;
+ if (latest.title !== null && latest.title !== this.pendingFallbacks.get(ctx.sessionId)) {
+ this.pendingFallbacks.delete(ctx.sessionId);
+ return;
+ }
+ this.pendingFallbacks.delete(ctx.sessionId);
+ this.persist(ctx, title, req.notifyOn);
+ }
+
+ /**
+ * Writes sessions.title and pushes the `session_title` event — to the given Session
+ * channel (the session's own unless overridden) for the tab watching the conversation,
+ * and to the Project's user-level channels for every session list. The latter is the
+ * delivery that survives the start-of-run timing: a first Task's title fires before the
+ * new Session's own channel has any subscriber.
+ */
+ private persist(ctx: UsageContext, title: string, notifyOn: string | undefined): void {
+ this.deps.sessions.updateTitle(ctx.sessionId, title);
+ const event: ServerEvent = { type: "session_title", sessionId: ctx.sessionId, title };
+ this.deps.channels.get(notifyOn ?? ctx.sessionId).publish(event, "server_event");
+ this.deps.notifyProjectUsers?.(ctx.projectId, event);
}
}
+/** Cap on the fallback title's length (same bound the LLM path's sanitizeTitle enforces). */
+const FALLBACK_MAX_CHARS = 30;
+
/**
- * Fallback title: take the material's first non-empty line, sanitize and truncate; if
- * sanitizing empties it out (pure punctuation, etc.) fall back to the truncated original
- * text; returns null if all-whitespace. Exported for the Trace listing's title fallback
- * (trace-service derives a title from the first user prompt of Sessions the DB has no
- * title for) so both fallbacks stay one algorithm.
+ * Fallback title: take the material's first non-empty line, truncate it to the first few
+ * words, and sanitize; if sanitizing empties it out (pure punctuation, etc.) fall back to
+ * the truncated line itself; returns null if all-whitespace. Exported for the Trace
+ * listing's title fallback (trace-service derives a title from the first user prompt of
+ * Sessions the DB has no title for) so both fallbacks stay one algorithm.
*/
export function fallbackTitle(text: string): string | null {
// Strip machine markers first: a skill invocation prepends a `[use_skills]` block, so the
// raw first non-empty line would otherwise be that marker rather than the user's request.
const firstLine = stripConversationMarkers(text)
.split("\n")
- .find((l) => l.trim().length > 0);
+ .find((l) => l.trim().length > 0 && !isAttachmentLine(l.trim()));
if (!firstLine) return null;
- // sanitizeTitle strips a pure-punctuation line down to empty — in that case keep the truncated original text, guaranteeing "a title is always obtained".
- return sanitizeTitle(firstLine) ?? firstLine.trim().slice(0, 30);
+ const collapsed = firstLine.replace(/\s+/g, " ").trim();
+ // Drop leading punctuation/quotes before truncating, so a decorated line spends the
+ // length budget on words (a line that is nothing but punctuation is kept as-is).
+ const lead = collapsed.replace(
+ /^["'“”‘’「」『』《》〈〉【】()()。..!!??;;,,、::\s]+/,
+ "",
+ );
+ const cut = truncateAtWord(lead || collapsed);
+ // sanitizeTitle strips a pure-punctuation line down to empty — in that case keep the truncated line, guaranteeing "a title is always obtained".
+ return sanitizeTitle(cut) ?? cut;
+}
+
+/**
+ * A line that is nothing but an `[attached image: …]` / `[attached file: …]` marker. A message
+ * that carries attachments and no typed text is exactly this line, so a title taken from it
+ * would be a truncated absolute path out of the sender's home directory. Such a message gets
+ * no fallback at all — the LLM material still carries the path, so the model can name the
+ * conversation after the file, and until it answers the UI shows its untitled placeholder.
+ */
+function isAttachmentLine(line: string): boolean {
+ return matchAttachedImageLine(line) !== null || matchAttachedFileLine(line) !== null;
+}
+
+/**
+ * Truncates to `FALLBACK_MAX_CHARS`, avoiding a mid-word cut: when the boundary splits an
+ * ASCII word the cut backs up to the last space instead. CJK text has no spaces and every
+ * character stands alone, so a plain character cut is already a word cut there.
+ *
+ * A character outside the BMP (an emoji, a rare CJK ideograph) is two UTF-16 units, and a cut
+ * between them leaves a lone surrogate, which has no UTF-8 encoding: SQLite stores U+FFFD in
+ * its place and the SSE frame carries the same replacement. The boundary therefore steps back
+ * one unit rather than splitting the pair.
+ */
+function truncateAtWord(text: string): string {
+ if (text.length <= FALLBACK_MAX_CHARS) return text;
+ const end = splitsSurrogatePair(text, FALLBACK_MAX_CHARS)
+ ? FALLBACK_MAX_CHARS - 1
+ : FALLBACK_MAX_CHARS;
+ const cut = text.slice(0, end);
+ const wordChar = /[A-Za-z0-9'’_-]/;
+ if (wordChar.test(text[end]!) && wordChar.test(cut[cut.length - 1]!)) {
+ const lastSpace = cut.lastIndexOf(" ");
+ if (lastSpace > 0) return cut.slice(0, lastSpace).trimEnd();
+ }
+ return cut.trimEnd();
+}
+
+/** True when index `i` falls between the high and low halves of one surrogate pair. */
+function splitsSurrogatePair(text: string, i: number): boolean {
+ const high = text.charCodeAt(i - 1);
+ const low = text.charCodeAt(i);
+ return high >= 0xd800 && high <= 0xdbff && low >= 0xdc00 && low <= 0xdfff;
}
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index a355cc84..e954cf9d 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -635,7 +635,7 @@ describe("session-manager", () => {
);
});
- it("sub-session (origin) registration: session_meta persists; the title is left to the model using the sub-session's own conversation", async () => {
+ it("sub-session (origin) registration: session_meta persists; the title is generated from the spawning prompt", async () => {
const fake: RuntimeSession = {
sessionId: "session-1",
toolPermission: () => "rw",
@@ -692,16 +692,17 @@ describe("session-manager", () => {
// predates the source field (this fake omits it): the registration path is the fallback.
expect(sources.get("child-1")).toBe("subagent");
expect(child && "source" in child).toBe(false);
- // Title left blank: produced by the title generator from the sub-session's own conversation (falls back to the prompt's first line on failure).
+ // The row itself is inserted with a blank title: the title generator (faked here) is
+ // notified at registration and owns the write.
expect(child?.title).toBeNull();
await waitFor(() => notified.length === 2);
const childTitle = notified.find((n) => n.ctx.sessionId === "child-1");
expect(childTitle).toBeTruthy();
- // Explicit material override for the sub-session: user material = the prompt that spawned it; assistant material = the sub-session's **own** model output.
+ // Explicit material override for the sub-session: the prompt that spawned it, alone — its own output is never waited for.
expect(childTitle!.req.material).toEqual({
userText: "Research the background of this question",
- assistantText: "child done",
+ assistantText: "",
});
expect(childTitle!.req.fallbackText).toBe("Research the background of this question");
// Session/Agent record the sub-session, but modelId records the parent — the request runs on the parent's bare LLM.
@@ -984,7 +985,7 @@ describe("session-manager", () => {
]);
});
- it("notifies title generation after a Task completes: fallback material is the user text, generation material is self-collected by the Session; compaction doesn't notify", async () => {
+ it("notifies title generation at Task start: fallback and generation material are the user input alone; compaction doesn't notify", async () => {
const notified: { ctx: UsageContext; session: unknown; req: TitleRequest }[] = [];
const plainSession: RuntimeSession = {
sessionId: "session-1",
@@ -1019,8 +1020,11 @@ describe("session-manager", () => {
await manager.startTask("session-1", [userText("question 1"), userText("question 2")]);
await waitFor(() => notified.length === 1);
expect(notified[0]!.req.fallbackText).toBe("question 1\nquestion 2");
- // No material override for the main session: material is gathered by the core Session during run.
- expect(notified[0]!.req.material).toBeUndefined();
+ // The generation material is the user input alone — no assistant text, nothing waits on it.
+ expect(notified[0]!.req.material).toEqual({
+ userText: "question 1\nquestion 2",
+ assistantText: "",
+ });
expect(notified[0]!.session).toBe(plainSession);
expect(notified[0]!.ctx).toMatchObject({
projectId: "p1",
@@ -1030,18 +1034,23 @@ describe("session-manager", () => {
provider: "custom",
});
+ // The notification fires at start, so the Task is still running here — let it finish
+ // (completion adds no second trigger), then compact.
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ expect(notified.length).toBe(1);
await manager.startCompact("session-1");
await waitFor(() => manager.statusOf("session-1") === "idle");
await new Promise((r) => setTimeout(r, 10));
expect(notified.length).toBe(1);
});
- it("fires title generation early once 1000 chars of body text have streamed (mid-run, before the Task finishes)", async () => {
+ it("fires title generation at Task start, before any model output has streamed", async () => {
const notified: { ctx: UsageContext; req: TitleRequest }[] = [];
- // Gate the run after the big body text so the early trigger provably happens mid-run.
+ // Gate the run before its first yield: a notification while the gate is closed proves
+ // generation starts without waiting on any model output.
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
- const longSession: RuntimeSession = {
+ const gatedRun: RuntimeSession = {
sessionId: "session-1",
toolPermission: () => "rw",
generateTitle: async () => ({ title: null, usage: null }),
@@ -1049,13 +1058,8 @@ describe("session-manager", () => {
steer: () => false,
skipReconnectWait: () => false,
async *run() {
- yield assistantText("x".repeat(600));
- // Sub-session text doesn't count toward the main-session body threshold
- // (asserted on its own in the next test).
- yield withOrigin(assistantText("z".repeat(2000)), "session-sub");
- yield assistantText("y".repeat(600)); // crosses the 1000-char threshold
await gate;
- yield assistantText("tail");
+ yield assistantText("answer");
},
async *compact() {},
};
@@ -1063,7 +1067,7 @@ describe("session-manager", () => {
sessions,
channels,
sources,
- loader: loaderOf(longSession),
+ loader: loaderOf(gatedRun),
recorder: { record: async () => {} },
titles: {
maybeGenerate: (ctx, _session, req) => notified.push({ ctx, req }),
@@ -1072,25 +1076,24 @@ describe("session-manager", () => {
});
await manager.startTask("session-1", [userText("long question")]);
- // The early trigger fires while the run is still in flight (gated before completion).
+ // The trigger fires while the run is still parked before its first message.
await waitFor(() => notified.length === 1);
expect(manager.statusOf("session-1")).toBe("running");
expect(notified[0]!.req.fallbackText).toBe("long question");
- expect(notified[0]!.req.material).toBeUndefined();
+ expect(notified[0]!.req.material).toEqual({ userText: "long question", assistantText: "" });
- // Completion still notifies as the short-answer fallback path (the generator itself dedups).
+ // Completion adds no second trigger — the start is the only one.
release();
await waitFor(() => manager.statusOf("session-1") === "idle");
- await waitFor(() => notified.length === 2);
+ await new Promise((r) => setTimeout(r, 10));
+ expect(notified.length).toBe(1);
});
- it("a subagent's output never fires the early title: only main-session body text counts toward the 1000 chars", async () => {
+ it("a subagent's title fires at registration (mid-run), from its spawning prompt alone", async () => {
const notified: { ctx: UsageContext; req: TitleRequest }[] = [];
const driven: OmniMessage[] = [];
- // Gate the run right after the sub-session's long output: while the parent is parked
- // here the completion trigger hasn't run yet, so an empty `notified` proves the child's
- // text alone never crossed the threshold (without the gate an early fire would be
- // indistinguishable from the completion one).
+ // Gate the run right after the sub-session's output: both notifications must already
+ // be in by then, proving neither waited for the run to complete.
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
const delegating: RuntimeSession = {
@@ -1119,10 +1122,9 @@ describe("session-manager", () => {
}),
hop,
);
- // Far past the threshold, but it belongs to the sub-session's own conversation.
yield withOrigin(assistantText("z".repeat(3000)), hop);
await gate;
- yield assistantText("short answer"); // the parent's whole body, well under 1000 chars
+ yield assistantText("short answer");
},
async *compact() {},
};
@@ -1143,17 +1145,23 @@ describe("session-manager", () => {
});
await manager.startTask("session-1", [userText("delegate this")]);
- // Recording happens after the early-title check, so once the sub-session's 3000 chars
- // have been driven through the parent's counter has already seen everything it will
- // ever see from the child — and it must still be at zero.
+ // By the time the sub-session's output has been driven through, both titles have
+ // already fired: the parent's at Task start, the child's at registration.
await waitFor(() => driven.length === 3);
expect(manager.statusOf("session-1")).toBe("running");
- expect(notified.length).toBe(0);
+ expect(notified.map((n) => n.ctx.sessionId)).toEqual(["session-1", "child-1"]);
+ const child = notified[1]!;
+ // The child's material is its spawning prompt alone — its own output is never waited for.
+ expect(child.req.material).toEqual({
+ userText: "Research the background of this question",
+ assistantText: "",
+ });
+ expect(child.req.notifyOn).toBe("session-1");
- // Only the completion path notifies: once for the parent, once for the sub-session's own title.
+ // Completion adds nothing further.
release();
await waitFor(() => manager.statusOf("session-1") === "idle");
- await waitFor(() => notified.length === 2);
- expect(notified.map((n) => n.ctx.sessionId)).toEqual(["session-1", "child-1"]);
+ await new Promise((r) => setTimeout(r, 10));
+ expect(notified.length).toBe(2);
});
});
diff --git a/packages/server/test/title-generator.test.ts b/packages/server/test/title-generator.test.ts
index b99d2678..6a06249b 100644
--- a/packages/server/test/title-generator.test.ts
+++ b/packages/server/test/title-generator.test.ts
@@ -1,12 +1,13 @@
/**
* Unit tests for the Session title policy layer (the generation logic lives in
* core `session.generateTitle`; a fake implementation is injected here):
- * persisting + event push + usage accounted as token usage, idempotency (no
- * regeneration when a title already exists / generation is in flight), and
- * silent failure.
+ * the immediate user-input fallback (persisted synchronously, before the LLM
+ * resolves), the LLM replacement, manual renames winning over both, retry while
+ * the fallback is still standing, usage accounted as token usage, and silent
+ * failure.
* The Chinese conversation/title fixtures are intentional: a Session title must
* follow the conversation language (zh chat → zh title), including the fallback
- * path that derives the title from the conversation text itself.
+ * path that derives the title from the user input itself.
*/
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import type { DatabaseSync } from "node:sqlite";
@@ -16,7 +17,7 @@ import { SessionsRepo } from "../src/db/repos/sessions.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import { ChannelHub } from "../src/runtime/channel.js";
import type { ChannelEvent } from "../src/runtime/channel.js";
-import { TitleGenerator } from "../src/runtime/title-generator.js";
+import { TitleGenerator, fallbackTitle } from "../src/runtime/title-generator.js";
import type { UsageContext } from "../src/runtime/usage-recorder.js";
import { waitFor } from "./helpers.js";
@@ -52,6 +53,23 @@ function fakeSession(result: SessionTitleResult, calls: { count: number; args: u
};
}
+/** Fake session whose generateTitle blocks until release() — for asserting what happens while the LLM is still in flight. */
+function gatedSession(result: SessionTitleResult, calls: { count: number; args: unknown[] }) {
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ return {
+ session: {
+ generateTitle: async (args: unknown) => {
+ calls.count += 1;
+ calls.args.push(args);
+ await gate;
+ return result;
+ },
+ },
+ release,
+ };
+}
+
describe("title-generator", () => {
let db: DatabaseSync;
let sessions: SessionsRepo;
@@ -93,24 +111,27 @@ describe("title-generator", () => {
db.close();
});
- it("title generation: persists + pushes session_title + usage converted and recorded; material defaults to Session self-collection", async () => {
+ it("persists the user-input fallback synchronously, then the LLM result replaces it; both push session_title; usage recorded", async () => {
const events = captureChannel();
const calls = { count: 0, args: [] as unknown[] };
- const gen = makeGenerator();
- gen.maybeGenerate(
- CTX,
- fakeSession(
- {
- title: "Tailwind theme setup",
- usage: { cache_read: 1, cache_write: 2, output: 3, total: 6 },
- },
- calls,
- ),
- { fallbackText: "explain @theme" },
+ const { session, release } = gatedSession(
+ {
+ title: "Tailwind theme setup",
+ usage: { cache_read: 1, cache_write: 2, output: 3, total: 6 },
+ },
+ calls,
);
- await waitFor(() => sessions.findById(ROW.sessionId)?.title !== null);
+ const gen = makeGenerator();
+ gen.maybeGenerate(CTX, session, { fallbackText: "explain @theme" });
+
+ // The fallback is in place before the LLM has resolved — nothing waits on model output.
+ expect(sessions.findById(ROW.sessionId)?.title).toBe("explain @theme");
+ expect(
+ serverEvents(events).some((e) => e.type === "session_title" && e.title === "explain @theme"),
+ ).toBe(true);
- expect(sessions.findById(ROW.sessionId)?.title).toBe("Tailwind theme setup");
+ release();
+ await waitFor(() => sessions.findById(ROW.sessionId)?.title === "Tailwind theme setup");
// No material override passed: generateTitle is called with no argument, and the core Session gathers its own material.
expect(calls.args[0]).toBeUndefined();
expect(
@@ -123,20 +144,19 @@ describe("title-generator", () => {
expect((usageMsg?.payload as { request?: { total: number } }).request?.total).toBe(6);
});
- it("material override (sub-session scenario) is passed to generateTitle verbatim", async () => {
+ it("material override is passed to generateTitle verbatim", async () => {
const calls = { count: 0, args: [] as unknown[] };
const gen = makeGenerator();
- const material = { userText: "sub-session prompt", assistantText: "sub-session reply" };
+ const material = { userText: "sub-session prompt", assistantText: "" };
gen.maybeGenerate(CTX, fakeSession({ title: "Sub title", usage: null }, calls), {
fallbackText: "sub-session prompt",
material,
});
- await waitFor(() => sessions.findById(ROW.sessionId)?.title !== null);
+ await waitFor(() => sessions.findById(ROW.sessionId)?.title === "Sub title");
expect(calls.args[0]).toEqual({ material });
- expect(sessions.findById(ROW.sessionId)?.title).toBe("Sub title");
});
- it("an existing title is never regenerated (no one-shot request issued)", async () => {
+ it("an existing title from outside the generator is never touched (no one-shot request issued)", async () => {
sessions.updateTitle(ROW.sessionId, "existing title");
const calls = { count: 0, args: [] as unknown[] };
makeGenerator().maybeGenerate(CTX, fakeSession({ title: "new title", usage: null }, calls), {
@@ -147,7 +167,53 @@ describe("title-generator", () => {
expect(sessions.findById(ROW.sessionId)?.title).toBe("existing title");
});
- it("when the LLM returns null (failed request / empty result), the fallback material's first line is persisted; usage still recorded", async () => {
+ it("a manual rename during generation wins: the LLM result does not overwrite it", async () => {
+ const calls = { count: 0, args: [] as unknown[] };
+ const { session, release } = gatedSession(
+ { title: "LLM title", usage: { cache_read: 0, cache_write: 0, output: 1, total: 1 } },
+ calls,
+ );
+ const gen = makeGenerator();
+ gen.maybeGenerate(CTX, session, { fallbackText: "first question" });
+ expect(sessions.findById(ROW.sessionId)?.title).toBe("first question");
+ // The user renames while the LLM request is still in flight.
+ sessions.updateTitle(ROW.sessionId, "my custom name");
+ release();
+ // Usage recording happens before the title decision, so it marks the request as settled.
+ await waitFor(() => recorded.length > 0);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(sessions.findById(ROW.sessionId)?.title).toBe("my custom name");
+ });
+
+ it("while the fallback is still standing, the next trigger retries the LLM and replaces it", async () => {
+ const failing = { count: 0, args: [] as unknown[] };
+ const gen = makeGenerator();
+ gen.maybeGenerate(CTX, fakeSession({ title: null, usage: null }, failing), {
+ fallbackText: "Configure the Tailwind theme",
+ });
+ await waitFor(() => failing.count === 1);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(sessions.findById(ROW.sessionId)?.title).toBe("Configure the Tailwind theme");
+
+ // Second Task start: the stored title still equals the fallback, so the LLM runs again.
+ const succeeding = { count: 0, args: [] as unknown[] };
+ gen.maybeGenerate(CTX, fakeSession({ title: "Theme setup", usage: null }, succeeding), {
+ fallbackText: "Configure the Tailwind theme",
+ });
+ await waitFor(() => sessions.findById(ROW.sessionId)?.title === "Theme setup");
+ expect(succeeding.count).toBe(1);
+
+ // After the LLM title lands, further triggers are no-ops.
+ const after = { count: 0, args: [] as unknown[] };
+ gen.maybeGenerate(CTX, fakeSession({ title: "unused", usage: null }, after), {
+ fallbackText: "Configure the Tailwind theme",
+ });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(after.count).toBe(0);
+ expect(sessions.findById(ROW.sessionId)?.title).toBe("Theme setup");
+ });
+
+ it("when the LLM returns null (failed request / empty result), the fallback stands; usage still recorded", async () => {
const calls = { count: 0, args: [] as unknown[] };
const gen = makeGenerator();
gen.maybeGenerate(
@@ -158,31 +224,27 @@ describe("title-generator", () => {
),
{ fallbackText: "Configure the Tailwind theme\nsecond line" },
);
- // Fallback = the material's first non-empty line, sanitized and truncated, guaranteeing a title is always produced.
- await waitFor(() => sessions.findById(ROW.sessionId)?.title !== null);
+ // Fallback = the input's first non-empty line, truncated and sanitized — written up front.
expect(sessions.findById(ROW.sessionId)?.title).toBe("Configure the Tailwind theme");
// The one-off request's usage is still recorded normally.
await waitFor(() => recorded.length > 0);
+ expect(sessions.findById(ROW.sessionId)?.title).toBe("Configure the Tailwind theme");
});
- it("fallback strips a leading [use_skills] block so the marker never becomes the title", async () => {
+ it("fallback strips a leading [use_skills] block so the marker never becomes the title", () => {
const calls = { count: 0, args: [] as unknown[] };
- const gen = makeGenerator();
- gen.maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
+ makeGenerator().maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
fallbackText: "[use_skills]\nskills: web-design\n[/use_skills]\nBuild a landing page",
});
- await waitFor(() => sessions.findById(ROW.sessionId)?.title !== null);
// Not "[use_skills]" — the marker block is removed before the first line is taken.
expect(sessions.findById(ROW.sessionId)?.title).toBe("Build a landing page");
});
- it("fallback also strips the legacy angle-bracket <use_skills> block (material from old Traces)", async () => {
+ it("fallback also strips the legacy angle-bracket <use_skills> block (material from old Traces)", () => {
const calls = { count: 0, args: [] as unknown[] };
- const gen = makeGenerator();
- gen.maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
+ makeGenerator().maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
fallbackText: "<use_skills>\nskills: web-design\n</use_skills>\nBuild a landing page",
});
- await waitFor(() => sessions.findById(ROW.sessionId)?.title !== null);
expect(sessions.findById(ROW.sessionId)?.title).toBe("Build a landing page");
});
@@ -196,14 +258,72 @@ describe("title-generator", () => {
expect(sessions.findById(ROW.sessionId)?.title).toBeNull();
});
- it("LLM returns null and the fallback material is pure punctuation → falls back to the truncated original text (never NULL)", async () => {
+ it("fallback material is pure punctuation → falls back to the truncated original text (never NULL)", () => {
const calls = { count: 0, args: [] as unknown[] };
- const gen = makeGenerator();
// sanitizeTitle strips "???" down to empty — the fallback must revert to the truncated original text so a title is still produced.
- gen.maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
+ makeGenerator().maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
fallbackText: "???",
});
- await waitFor(() => sessions.findById(ROW.sessionId)?.title !== null);
expect(sessions.findById(ROW.sessionId)?.title).toBe("???");
});
+
+ describe("fallbackTitle truncation", () => {
+ it("keeps short input as-is", () => {
+ expect(fallbackTitle("fix bug")).toBe("fix bug");
+ });
+
+ it("cuts long English input at a word boundary", () => {
+ expect(fallbackTitle("Please fix the database connection timeout problem")).toBe(
+ "Please fix the database",
+ );
+ });
+
+ it("cuts long CJK input at the character cap (every character is a word)", () => {
+ const long = "帮我修复数据库连接超时的问题然后写一个测试用例覆盖它再检查一下配置文件";
+ expect(fallbackTitle(long)).toBe(long.slice(0, 30));
+ });
+
+ it("hard-cuts a single overlong word (no space to back up to)", () => {
+ expect(fallbackTitle("a".repeat(40))).toBe("a".repeat(30));
+ });
+
+ it("spends the length budget on words, not leading punctuation", () => {
+ expect(fallbackTitle("!!!Please fix the database connection timeout")).toBe(
+ "Please fix the database",
+ );
+ });
+
+ it("never cuts between the halves of a surrogate pair", () => {
+ // The emoji straddles the 30-char boundary: a plain slice would leave its high half
+ // alone, which SQLite and the SSE frame both render as U+FFFD.
+ const title = fallbackTitle(`${"a".repeat(29)}🎉 and more text`)!;
+ expect(title).toBe("a".repeat(29));
+ expect(/[\uD800-\uDFFF]/.test(title)).toBe(false);
+ });
+ });
+
+ describe("fallbackTitle attachment material", () => {
+ const filePath = "/home/someone/.penguin/agents/default_agent/scratchpad/s-1/report.pdf";
+
+ it("gives an attachment-only message no fallback rather than a truncated path", () => {
+ // The composer sends a file with no typed text as a message whose whole body is the
+ // marker line; "[attached file" is not a title, and the path is the sender's home dir.
+ expect(fallbackTitle(`[attached file: ${filePath}]`)).toBeNull();
+ expect(fallbackTitle(`[attached image: ${filePath}]`)).toBeNull();
+ });
+
+ it("still titles a message that has text alongside its attachment", () => {
+ expect(fallbackTitle(`Summarise this report\n\n[attached file: ${filePath}]`)).toBe(
+ "Summarise this report",
+ );
+ });
+
+ it("leaves the row NULL when the whole input is an attachment line", () => {
+ const calls = { count: 0, args: [] as unknown[] };
+ makeGenerator().maybeGenerate(CTX, fakeSession({ title: null, usage: null }, calls), {
+ fallbackText: `[attached file: ${filePath}]`,
+ });
+ expect(sessions.findById(ROW.sessionId)?.title).toBeNull();
+ });
+ });
});
diff --git a/packages/server/test/title-http-path.test.ts b/packages/server/test/title-http-path.test.ts
new file mode 100644
index 00000000..83a83a92
--- /dev/null
+++ b/packages/server/test/title-http-path.test.ts
@@ -0,0 +1,128 @@
+/**
+ * End-to-end title generation over the same HTTP path the Web App uses: create the
+ * Session via POST /api/projects/:p/agents/:a/sessions, start the first Task via
+ * POST /api/sessions/:id/tasks, and assert against the real wiring (real
+ * SessionManager, real TitleGenerator, real ChannelHub, real DB) that
+ * 1. the created row's title is NULL (the "New chat" label is a client-side
+ * display fallback, not a stored default),
+ * 2. the user-input fallback title is persisted and pushed on the session's SSE
+ * channel while the run is still parked before any model output,
+ * 3. the LLM title replaces it when the one-shot request resolves.
+ * Only the runtime Session is faked (adopted into the manager's active table); the
+ * fake's generateTitle is gated so "before any model output" is provable.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { RuntimeSession } from "../src/runtime/session-manager.js";
+import type { ChannelEvent } from "../src/runtime/channel.js";
+import { userChannelKey } from "../src/http/routes/events.js";
+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** Fake runtime Session: the run parks until released, generateTitle parks until released. */
+function gatedSession(
+ sessionId: string,
+ runGate: Promise<void>,
+ titleGate: Promise<void>,
+): RuntimeSession {
+ return {
+ sessionId,
+ toolPermission: () => "rw",
+ generateTitle: async () => {
+ await titleGate;
+ return { title: "Login page bug", usage: null };
+ },
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run() {
+ await runGate;
+ },
+ async *compact() {},
+ };
+}
+
+describe("title generation over the web's HTTP path", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let releaseRun!: () => void;
+ let releaseTitle!: () => void;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "titler");
+ api = apiClient(t.app, cookie);
+ // The draft flow creates the Session with no model reference, so the Project must carry
+ // a default one. Seed it explicitly rather than relying on what the first-run seed
+ // detects: that comes from ambient provider credentials, which a dev box has and CI
+ // does not, and without a default createSession answers 400.
+ await api.put("/api/projects/titler-default_project/models", {
+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6" }],
+ });
+ });
+
+ afterEach(async () => {
+ releaseRun?.();
+ releaseTitle?.();
+ await t.cleanup();
+ });
+
+ it("writes the user-input fallback before any model output, pushes session_title, then the LLM result replaces it", async () => {
+ // 1. Create the Session exactly like the Web draft flow does.
+ const created = await api.post(
+ "/api/projects/titler-default_project/agents/default_agent/sessions",
+ {},
+ );
+ expect(created.status).toBe(201);
+ const { session } = (await created.json()) as {
+ session: { sessionId: string; title?: string | null };
+ };
+ const sid = session.sessionId;
+ // The stored title of a fresh Session is NULL — "New chat" is purely a display fallback.
+ expect(t.deps.sessionsRepo.findById(sid)!.title).toBeNull();
+
+ // Swap in the gated fake runtime for the first Task.
+ const runGate = new Promise<void>((r) => (releaseRun = r));
+ const titleGate = new Promise<void>((r) => (releaseTitle = r));
+ t.deps.manager.adopt(t.deps.sessionsRepo.findById(sid)!, gatedSession(sid, runGate, titleGate));
+
+ // Subscribe to the session's channel the way the SSE endpoint does — and to the
+ // user-level channel, which the real app holds open from startup. The user channel is
+ // the delivery the session list depends on: at first-Task time no tab has subscribed
+ // to the brand-new session's own channel yet.
+ const events: ChannelEvent[] = [];
+ t.deps.channels.get(sid).subscribe((e) => events.push(e));
+ const userEvents: ChannelEvent[] = [];
+ t.deps.channels.get(userChannelKey("titler")).subscribe((e) => userEvents.push(e));
+
+ // 2. First message, same body shape the Web composer sends.
+ const res = await api.post(`/api/sessions/${sid}/tasks`, {
+ input: [{ type: "text", text: "Fix the login page rendering bug please" }],
+ });
+ expect(res.status).toBe(202);
+
+ // 3. The fallback is persisted and pushed while the run is still parked (the fake
+ // has produced no output, and the LLM gate is still closed).
+ await waitFor(() => t.deps.sessionsRepo.findById(sid)!.title !== null);
+ expect(t.deps.sessionsRepo.findById(sid)!.title).toBe("Fix the login page rendering");
+ const titlesOf = (list: ChannelEvent[]) => () =>
+ list
+ .filter((e) => e.event === "server_event")
+ .map((e) => JSON.parse(e.data) as { type: string; title?: string })
+ .filter((e) => e.type === "session_title")
+ .map((e) => e.title);
+ const titles = titlesOf(events);
+ const userTitles = titlesOf(userEvents);
+ await waitFor(() => titles().includes("Fix the login page rendering"));
+ await waitFor(() => userTitles().includes("Fix the login page rendering"));
+
+ // 4. The LLM result replaces the fallback and is pushed on both channels as well.
+ releaseTitle();
+ await waitFor(() => t.deps.sessionsRepo.findById(sid)!.title === "Login page bug");
+ await waitFor(() => titles().includes("Login page bug"));
+ await waitFor(() => userTitles().includes("Login page bug"));
+
+ releaseRun();
+ await waitFor(() => t.deps.manager.statusOf(sid) === "idle");
+ });
+});
diff --git a/packages/web/e2e/mock-llm.mjs b/packages/web/e2e/mock-llm.mjs
index 9ff4774e..09c73ece 100644
--- a/packages/web/e2e/mock-llm.mjs
+++ b/packages/web/e2e/mock-llm.mjs
@@ -195,11 +195,10 @@ const server = http.createServer((req, res) => {
messageStart(res, msgCount);
if (isTitle) {
- // The child session's title request carries **the child session's own answer** as
- // assistant material; respond with a distinguishable title based on that, so the E2E
- // test can prove the child session's title really comes from its own conversation,
- // not from the run_subagent prompt.
- const forSubagent = flat.includes("Subagent report");
+ // A subagent's title request carries **the run_subagent prompt that spawned it** and
+ // nothing else (the parent's own title request never contains that prompt); respond
+ // with a distinguishable title so the E2E test can tell the two titles apart.
+ const forSubagent = flat.includes(SUBAGENT_PROMPT);
block(res, 0, { type: "text", text: "" }, [
{
type: "text_delta",
diff --git a/packages/web/e2e/subagent.spec.mjs b/packages/web/e2e/subagent.spec.mjs
index d4f71cfe..47bafb65 100644
--- a/packages/web/e2e/subagent.spec.mjs
+++ b/packages/web/e2e/subagent.spec.mjs
@@ -220,7 +220,7 @@ test("subagent renders as a chip; the panel shows the call graph and child conve
await agentsToggle.click(); // reopen from the toolbar -> back to the DEFAULT latest-Task scope
await expect(page.getByText("本次任务尚未派生子智能体")).toBeVisible();
- // --- Child session title: generated by the model from the child session's own conversation (async, poll until persisted). ---
+ // --- Child session title: generated by the model from the run_subagent prompt that spawned it (async, poll until persisted). ---
const childOf = async () => {
const list = await (
await page.request.get(`${BASE}/api/projects/${projectId}/agents/${agentId}/sessions`)
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index b292c429..59a0d6a6 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -627,7 +627,12 @@ export function DraftView({
const created = await api.createSession(projectId, agentId, body);
createdId = created.session.sessionId;
const res = await api.postTask(createdId, { input, ...(goal ? { goal } : {}) });
- add(created.session);
+ // Re-fetch the row before listing it: the server persisted the fallback title at
+ // Task start (inside the postTask call), and its session_title push may have gone
+ // out before this row existed in the list, where it patched nothing. The fresh row
+ // also carries the post-self-heal id, matching where we navigate.
+ const fresh = await api.getSession(res.sessionId).catch(() => null);
+ add(fresh?.session ?? created.session);
if (!keepDraft) discardDraft();
// The draft now has an id of its own, so its terminals move with it: every draft
// shares one dock scope, and anything left behind under that key would surface in
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index e85d50a1..e1b63212 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -439,9 +439,19 @@ export function createSessionsStore() {
});
},
+ /**
+ * Same drop rule as `setStatus`: an id no loaded page holds is ignored rather than
+ * turned into a row. The title now arrives on the user channel too, which carries every
+ * Session of every Project this user can see — most of them absent from this list — and
+ * both channels deliver the same title to a tab subscribed to both. Replacing the array
+ * either way would re-render every row for nothing.
+ */
setTitle: (sessionId, title) => {
+ const prev = get().sessions;
+ const target = prev.find((s) => s.sessionId === sessionId);
+ if (!target || target.title === title) return;
set({
- sessions: get().sessions.map((s) => (s.sessionId === sessionId ? { ...s, title } : s)),
+ sessions: prev.map((s) => (s.sessionId === sessionId ? { ...s, title } : s)),
});
},
@@ -491,6 +501,14 @@ export function applyUserEvent(
});
return;
}
+ // A title landed. Titles generate at Task start, before the brand-new Session's own
+ // channel has any subscriber (the tab is still navigating from the draft), so the user
+ // channel is the delivery that reliably updates the list row — and rows this tab never
+ // opens (another tab's session, a subagent) get their titles the same way.
+ if (ev.type === "session_title") {
+ store.getState().setTitle(ev.sessionId, ev.title);
+ return;
+ }
// The reconnect landed outside the channel's replay buffer, so an unknown number of the flips
// above were lost — away long enough and a row sits on an hourglass that will never stop.
// Refetch once, on the event that says so, rather than polling for it.
diff --git a/packages/web/test/session-status-events.test.ts b/packages/web/test/session-status-events.test.ts
index f35a9479..7d99125d 100644
--- a/packages/web/test/session-status-events.test.ts
+++ b/packages/web/test/session-status-events.test.ts
@@ -133,6 +133,41 @@ describe("session_state on the user channel", () => {
});
});
+describe("session_title on the user channel", () => {
+ const titleEvent = (sessionId: string, title: string): ServerEvent => ({
+ type: "session_title",
+ sessionId,
+ title,
+ });
+
+ it("renames the named row in place and leaves every other row alone", () => {
+ // Titles land at Task start — before the tab watching the brand-new conversation has
+ // subscribed to its Session channel — so the list depends on this delivery.
+ const store = storeWith(session("a"), session("b"));
+ applyUserEvent(store, titleEvent("b", "Login page bug"), neverReload);
+ expect(rowOf(store, "b").title).toBe("Login page bug");
+ expect(rowOf(store, "a").title).toBeUndefined();
+ });
+
+ it("ignores a Session no loaded page holds instead of inventing a row", () => {
+ const store = storeWith(session("a"));
+ const before = store.getState().sessions;
+ applyUserEvent(store, titleEvent("not-loaded", "whatever"), neverReload);
+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["a"]);
+ // The user channel carries every Session this user can see, most of them absent from this
+ // list: an unlisted id must not churn the array and re-render every row.
+ expect(store.getState().sessions).toBe(before);
+ });
+
+ it("is a no-op when the row already carries that title (both channels deliver it)", () => {
+ const store = storeWith(session("a"));
+ applyUserEvent(store, titleEvent("a", "Login page bug"), neverReload);
+ const after = store.getState().sessions;
+ applyUserEvent(store, titleEvent("a", "Login page bug"), neverReload);
+ expect(store.getState().sessions).toBe(after);
+ });
+});
+
describe("hasTrace across a status flip", () => {
// The regression this pins: `sessionActivity` checks status first, so `running` draws the
// hourglass whatever hasTrace says — and then falls to `if (!hasTrace) return null` once the
@@ -312,7 +347,17 @@ describe("other user-channel events keep their behaviour", () => {
const store = storeWith(session("a"));
const before = store.getState().sessions;
applyUserEvent(store, { type: "hello" }, neverReload);
- applyUserEvent(store, { type: "session_title", sessionId: "a", title: "T" }, neverReload);
+ applyUserEvent(
+ store,
+ {
+ type: "schedule_queued",
+ projectId: "proj",
+ agentId: "default_agent",
+ name: "n",
+ sessionId: "a",
+ },
+ neverReload,
+ );
expect(store.getState().sessions).toBe(before);
});