Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Fix #7793: auto thread titles from first bot reply, with helper/custom model support

vincent0897f8978107
diff --git a/docs/verification/README.md b/docs/verification/README.md
index f3a7fe1043..e0d02d3022 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -81,6 +81,7 @@ Use only mapped, tested commands:
- [Phone web app installation and safe areas](phone-web-app.md)
- [Welcome flow and guided tour](onboarding.md)
- [Channels](channels.md)
+- [Automatic thread titles](thread-titles.md)
- [In-chat team coordination](room-coordination.md)
- [Question cards: a teammate's question, in its chat and the person's inbox](question-cards.md)
- [Chief authority over additional departments](team-access.md)
diff --git a/docs/verification/thread-titles.md b/docs/verification/thread-titles.md
new file mode 100644
index 0000000000..5c20aad74c
--- /dev/null
+++ b/docs/verification/thread-titles.md
@@ -0,0 +1,13 @@
+# Automatic thread titles
+
+```sh
+pnpm exec vitest run server/thread-title-auto.e2e.test.ts
+pnpm exec vitest run server/index.test.ts -t 'title|snippet'
+pnpm exec vitest run server/thread-title.test.ts server/thread-title-generate.test.ts server/host/handed-thread-title.test.ts server/side-jobs.test.ts server/tasks.test.ts server/group-tasks.test.ts server/team-backup.test.ts server/drivers/openai-responses.test.ts src/components/settings/pages/FeaturesPage.test.ts
+```
+
+The isolated server fixture uses a scripted Claude CLI. A new conversation first shows the user's opening line. When the first turn settles with an answer, its generated title uses the request and the answer. If the turn fails, ends without an answer or takes longer than 30 seconds, the original request is used. The title call has a separate 30-second limit. A failed or empty answer leaves the current title intact.
+
+Settings → Features selects a connected model for titles; Automatic uses the conversation's engine or, when it cannot generate text, the configured helper if the bot permits it. Automatic follow-up titles are off by default. When enabled, a generated title may update after a later reply; a manual rename stays fixed. Explicit Regenerate still works on a manually named thread.
+
+The title model receives redacted excerpts. Confined guest, linked hand-off and voice-call titles stay on the conversation's engine. Backups carry the follow-up preference and title provenance. The destination keeps its own provider selection.
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index ac5a800392..4ff1a61aaf 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -122,8 +122,8 @@ export interface WireTask extends InboxTask, HandoffStatusField {
origin?: ForkOrigin;
title: string;
createdAt: number;
- /** The first message already drove a title attempt for this thread, so a
- * later one does not rename a thread the person may have retitled. */
+ /** Whether the title is eligible for automatic updates. Absent on older threads. */
+ titleMode?: "automatic" | "manual";
titleFromFirstMessage?: true;
/** Team Cloud only: this is the bot's main chat, everyone's who sees the bot. Its title is SHARED_CHAT_TITLE on every
* person's copy, whatever is stored, and it can't be renamed. */
@@ -824,8 +824,8 @@ export interface GroupTask {
/** Epoch ms of the newest message, or createdAt when the thread has none. */
updatedAt?: number;
lastThreadOrderAt?: number;
- /** The first message already drove a title attempt for this thread, so a
- * later one does not rename a room the person may have retitled. */
+ /** Whether the title is eligible for automatic updates. Absent on older threads. */
+ titleMode?: WireTask["titleMode"];
titleFromFirstMessage?: true;
/** Whether a turn is actively running in this thread. */
working?: boolean;
diff --git a/server/cloud-chat-merge.ts b/server/cloud-chat-merge.ts
index 4bea827c39..593ce95a23 100644
--- a/server/cloud-chat-merge.ts
+++ b/server/cloud-chat-merge.ts
@@ -26,9 +26,9 @@ export interface ChatMergeResult { conversations: number; messages: number; into
export interface ChatMergePlan extends ChatMergeResult { threads: ThreadMerge[] }
export type ChatStore = Pick<Store, "bots" | "groups" | "bot" | "group" | "messagesFor" | "activeLeaf" | "importTranscript" | "patchBot" | "patchGroup" | "createGroup">;
-const BOT_TASK_KEYS = ["threadId", "title", "createdAt", "titleFromFirstMessage", "openedBy", "closedBy", "archivedAt", "pinned", "link", "linkAuto",
+const BOT_TASK_KEYS = ["threadId", "title", "createdAt", "titleFromFirstMessage", "titleMode", "openedBy", "closedBy", "archivedAt", "pinned", "link", "linkAuto",
"lastReadMessageId", "pinnedMessageId", "routineRunId", "askedAt", "snoozedUntil", "outside"] as const;
-const GROUP_TASK_KEYS = ["threadId", "title", "createdAt", "titleFromFirstMessage", "pinned", "pinnedMessageId", "turnTimeoutMinutes"] as const;
+const GROUP_TASK_KEYS = ["threadId", "title", "createdAt", "titleFromFirstMessage", "titleMode", "pinned", "pinnedMessageId", "turnTimeoutMinutes"] as const;
export const ATTACHMENT_NAME = /^[A-Za-z0-9-]{1,80}\.[A-Za-z0-9]{1,10}$/;
const ownerKey = (owner: Owner) => `${owner.kind}:${owner.id}`;
diff --git a/server/cloud-send-chats.ts b/server/cloud-send-chats.ts
index dd997b3ec8..9c9b480f05 100644
--- a/server/cloud-send-chats.ts
+++ b/server/cloud-send-chats.ts
@@ -128,7 +128,7 @@ function sentTask(task: TaskRecord): TaskRecord {
const pick = <T extends object>(source: T, keys: readonly string[]) => Object.fromEntries(keys.filter((key) => (source as Record<string, unknown>)[key] !== undefined)
.map((key) => [key, (source as Record<string, unknown>)[key]]));
/** What a room's thread carries to My Cloud: never this computer's folders. */
-const sentRoomTask = (task: GroupTaskRecord) => pick(task, ["threadId", "title", "createdAt", "titleFromFirstMessage", "pinned", "pinnedMessageId", "turnTimeoutMinutes"]) as unknown as GroupTaskRecord;
+const sentRoomTask = (task: GroupTaskRecord) => pick(task, ["threadId", "title", "createdAt", "titleFromFirstMessage", "titleMode", "pinned", "pinnedMessageId", "turnTimeoutMinutes"]) as unknown as GroupTaskRecord;
/** As My Cloud takes a room (sentSchema): a calendar call's room keeps the call's name, which may be longer, and one room it
* refuses refuses every conversation sent beside it. */
const sentRoom = (room: GroupRecord) => ({ ...pick(room, ["defaultResponder", "section", "setupCompletedAt", "setupSkippedAt", "audienceFloor"]),
diff --git a/server/config.ts b/server/config.ts
index 502f1b16fa..1cd8b1ed04 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -23,7 +23,7 @@ import { API_KEY_FLEET, DEFAULT_FLEET, OPENAI_API_INSTANCE, OPENROUTER_API_INSTA
export { CLAUDE_API_INSTANCE, OPENAI_API_INSTANCE, OPENROUTER_API_INSTANCE, XAI_API_INSTANCE } from "./instance-fleets.ts";
import { DEFAULT_WINDOW_MINUTES, MAX_WINDOW_MINUTES } from "./cache-keepwarm.ts";
import { PROVIDER_ICON_PRESETS, providerIconError } from "../shared/provider-icon.ts";
-import { helperStoredShape, type HelperConfig } from "./side-jobs.ts";
+import { helperStoredShape, ONE_OFF_MODEL_ID, type HelperConfig } from "./side-jobs.ts";
import { loopGuardConfigSchema, type LoopGuardConfig } from "./host/loop-guard.ts";
import { migrateLegacyFeatureFlags } from "./legacy-feature-flags.ts";
import { settledFileCache, settledFileStamp } from "./settled-file.ts";
@@ -386,6 +386,11 @@ const appConfigSchema = z.object({
tidyHour: z.number().int().min(0).max(23).optional(),
}).strict().optional(),
threads: threadsConfigSchema.optional(), /** Burst mode on an open-source install; a Cloud's plan sets it instead. `maxParallel`: burst threads running at once (default 10). */ burst: z.object({ maxParallel: z.number().int().min(1).max(100).optional() }).strict().optional(),
+ /** Null selects automatic routing. Follow-up renames are off unless enabled. */
+ threadTitles: z.object({
+ model: z.object({ instanceId: defaultModelSelectionSchema.shape.instanceId, model: defaultModelSelectionSchema.shape.model.regex(ONE_OFF_MODEL_ID) }).strict().nullable().optional(),
+ followUp: z.boolean().optional(),
+ }).strict().optional(),
/** Minimum days of decision-log month files kept; OMB_DECISION_RETENTION_DAYS wins. */
decisions: z.object({ retentionDays: z.number().int().min(1).max(3650).optional() }).strict().optional(),
loopGuard: loopGuardConfigSchema.optional(),
@@ -414,7 +419,7 @@ const appConfigPatchSchema = appConfigSchema.omit({ instances: true, mcpServers:
.extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional() }); export const CONFIG_PATCH_FIELDS = appConfigPatchSchema.shape;
const jsonObjectSchema = z.record(z.string(), z.json());
-export interface AppConfig extends HelperConfig {
+export interface AppConfig extends HelperConfig, Pick<z.output<typeof appConfigSchema>, "rooms" | "mcp" | "threadTitles" | "memory" | "features" | "onboarding"> {
customDomain?: string;
signIn?: { admins?: string[]; members?: string[] };
/** Preferred selection for newly created bots; existing bots keep theirs. */
@@ -461,14 +466,9 @@ export interface AppConfig extends HelperConfig {
imageGen?: ImageGenerationConfig;
live?: LiveConfig;
profile?: { name?: string; email?: string; aboutMe?: string; avatarUrl?: string }; everyBotRules?: string;
- rooms?: { turnTimeoutMinutes: number };
- mcp?: { callTimeoutMinutes?: number };
threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number }; burst?: { maxParallel?: number };
context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };
- memory?: { captureQuietMs?: number; tidyHour?: number };
vpsIdle?: z.infer<typeof vpsIdleConfigSchema>; localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };
- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean; phonePush?: boolean; skillBurger?: boolean; threadTabs?: boolean; suggestedReplies?: boolean };
- onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };
browserProfiles?: BrowserProfile[];
browserEngine?: BrowserEngineConfig;
instances?: InstanceConfigMap;
@@ -889,7 +889,7 @@ export function saveConfig(
const keepImageModels = keepKeysOutOfImageModels(disk, checkedPatch.imageGen);
const storedProfiles = storedBrowserProfilesSchema.safeParse(disk.browserProfiles);
if (storedProfiles.success) disk.browserProfiles = storedProfiles.data;
- for (const key of ["xai", "anthropic", "mistral", "cerebras", "treg", "postiz", "groq", "greenference", "modelgo", "meta", "deepseek", "openai", "openrouter", "openaiCompat", "composio", "box", "opencodeGo", "tts", "decider", "imageGen", "live", "profile", "rooms", "mcp", "threads", "context", "memory", "localVm", "vpsIdle", "features", "budgets", "billing", "decisions", "loopGuard", "onboarding", "browserEngine", "newBots", "safetyFloor"] as const) {
+ for (const key of ["xai", "anthropic", "mistral", "cerebras", "treg", "postiz", "groq", "greenference", "modelgo", "meta", "deepseek", "openai", "openrouter", "openaiCompat", "composio", "box", "opencodeGo", "tts", "decider", "imageGen", "live", "profile", "rooms", "mcp", "threads", "threadTitles", "context", "memory", "localVm", "vpsIdle", "features", "budgets", "billing", "decisions", "loopGuard", "onboarding", "browserEngine", "newBots", "safetyFloor"] as const) {
const section = checkedPatch[key];
if (!section) continue;
const current = jsonObjectSchema.safeParse(disk[key]);
@@ -897,7 +897,7 @@ export function saveConfig(
if (key === "threads" && !current.success) merged.maxConcurrentPerBot = defaultBotThreads();
Object.assign(merged, section, key === "browserEngine" && checkedPatch.browserEngine?.egress ? { egress: { ...jsonObjectSchema.safeParse(merged.egress).data, ...checkedPatch.browserEngine.egress } } : {}); // a partial egress patch keeps the stored allow-list
for (const [sectionKey, sectionValue] of Object.entries(section as Record<string, unknown>)) {
- if (sectionValue === null) delete merged[sectionKey];
+ if (sectionValue === null && key !== "threadTitles") delete merged[sectionKey];
}
disk[key] = merged;
}
diff --git a/server/contracts.ts b/server/contracts.ts
index f9bf9d260c..99abec792d 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -615,6 +615,10 @@ export interface TextGenerationOptions {
checkModel?: (model: string) => void;
/** How long the caller will wait; drivers with their own process timer use it instead of their default. */
timeoutMs?: number;
+ /** Output token budget, including reasoning where the provider counts it. */
+ maxOutputTokens?: number;
+ /** Return final answer text only. Empty final content is allowed. */
+ finalTextOnly?: boolean;
/** For a bot's own engine whose driver picks a small model of its own. */
fallback?: SmallModelFallback;
}
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index ae669dfc18..c48466689d 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -1772,7 +1772,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
};
/** One-shot call, prompt on stdin (approval summaries can hold secrets), no tools or MCP servers. */
- const generateReview = async (prompt: string, signal?: AbortSignal, onUsage?: TextGenerationOptions["onUsage"], timeoutMs?: number, named?: string): Promise<string> => {
+ const generateReview = async (prompt: string, signal?: AbortSignal, onUsage?: TextGenerationOptions["onUsage"], timeoutMs?: number, named?: string, maxOutputTokens?: number): Promise<string> => {
await ensureCliVersion(environment());
return new Promise((resolve, reject) => {
if (config.requireApiKey && !input.environment.ANTHROPIC_API_KEY) {
@@ -1780,7 +1780,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
return;
}
const model = named ?? config.managedModels?.[0] ?? config.endpointModels?.[0] ?? "claude-haiku-5-5";
- const env = environment(config.endpointModels ? undefined : model);
+ const env = { ...environment(config.endpointModels ? undefined : model), ...(maxOutputTokens === undefined ? {} : { CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(maxOutputTokens) }) };
const args = backgroundCallArgs({ model, outputFormat: onUsage ? "json" : "text", supports: (flag) => cliVersion !== null && claudeCliSupports(cliVersion, flag), isolated: !inheritsUserConfig(env) });
const { child, removeCwd } = spawnBackgroundCall(config.cli, args, env);
let stdout = "";
@@ -1936,7 +1936,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
return () => listeners.delete(listener);
},
},
- generateText: (prompt, options) => generateReview(prompt, options?.signal, options?.onUsage, options?.timeoutMs, options?.model),
+ generateText: (prompt, options) => generateReview(prompt, options?.signal, options?.onUsage, options?.timeoutMs, options?.model, options?.maxOutputTokens),
reviewPermission: generateReview,
dispose: async () => {
try {
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index ab9d089bf9..41672cdd74 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -82,6 +82,11 @@ interface NativeLog {
incoming(completion: Completion): unknown;
}
const LIVENESS_MISSES = 3;
+function finalResponseText(output: ResponseItem[]): string {
+ return output.filter(({ type, role, phase }) => type === "message" && role === "assistant" && (phase == null || phase === "final_answer"))
+ .map(({ content }) => Array.isArray(content) ? content.map((part) => part?.type === "output_text" && typeof part.text === "string" ? part.text : "").join("") : "")
+ .filter(Boolean).join("\n\n");
+}
interface RuntimeOptions<Config> {
input: DriverCreateInput<Config>;
@@ -252,7 +257,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
signal?: AbortSignal,
onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,
tools: ChatToolDefinition[] = [],
- onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string,
+ variant?: string, threadId?: string, { onUsage, maxOutputTokens }: Pick<TextGenerationOptions, "onUsage" | "maxOutputTokens"> = {},
): Promise<Completion> => {
const timeoutController = new AbortController();
let idleTimer: NodeJS.Timeout | null = null;
@@ -275,10 +280,11 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const requestBody = options.requestBody(served, messages, stream, variant, threadId, model);
const effort = selectedReasoningEffort(requestBody, route, variant, options.selectedReasoning?.(model, variant));
const payload = JSON.stringify(route === "responses"
- ? responsesRequest({ model: served, messages, tools, replay: (message) => responseOutputs.get(message), summaries: routes.summaries(model), effort })
+ ? { ...responsesRequest({ model: served, messages, tools, replay: (message) => responseOutputs.get(message), summaries: tools.length > 0 && routes.summaries(model), effort }), max_output_tokens: maxOutputTokens }
: {
...requestBody,
...(route === "chat-reasoning-off" ? (options.reasoningOffBody?.(served) ?? { reasoning_effort: "none" }) : {}),
+ ...(maxOutputTokens === undefined ? {} : { [isOpenAIAddress(options.apiUrl) ? "max_completion_tokens" : "max_tokens"]: maxOutputTokens }),
...(tools.length ? { tools } : {}),
});
const send = options.timeoutMs > FETCH_LIMIT_MS ? fetchPastLimit : fetch;
@@ -309,6 +315,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (route === "responses") {
const reply = await readResponsesStream(response.body, { reasoning: Boolean(options.reasoning), onBytes: resetIdleTimer, onDelta: (text, kind) => onDelta?.(text, kind), fail: failure });
activeSignal.throwIfAborted();
+ onUsage?.({ model, input: reply.usage?.input, output: reply.usage?.output, cachedInput: reply.usage?.cachedInput });
return reply;
}
@@ -342,9 +349,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
activeSignal.throwIfAborted();
return {
text: options.contentText ? options.contentText(message?.content) : typeof message?.content === "string" ? message.content : "",
- reasoning: options.reasoning && typeof reasoning === "string"
- ? reasoning
- : "",
+ reasoning: options.reasoning && typeof reasoning === "string" ? reasoning : "",
usage: usageFrom(tokenUsage),
toolCalls: calls.finish(finishReason, false),
finishReason,
@@ -353,9 +358,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
};
}
- if (!response.body) {
- throw new Error(options.noBodyError ?? `${options.httpErrorLabel} returned no response body`);
- }
+ if (!response.body) throw new Error(options.noBodyError ?? `${options.httpErrorLabel} returned no response body`);
let text = "";
let reasoning = "";
let protocolReasoning = "";
@@ -391,9 +394,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (choice?.finish_reason) finishReason = choice.finish_reason;
const reasoningPart = delta?.reasoning_content ?? delta?.reasoning;
if (typeof reasoningPart === "string") protocolReasoning += reasoningPart;
- const reasoningDelta = options.reasoning && typeof reasoningPart === "string"
- ? reasoningPart
- : "";
+ const reasoningDelta = options.reasoning && typeof reasoningPart === "string" ? reasoningPart : "";
const contentDelta = options.contentText ? options.contentText(delta?.content) : typeof delta?.content === "string" ? delta.content : "";
if (reasoningDelta) {
reasoning += reasoningDelta;
@@ -457,7 +458,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
signal?: AbortSignal,
onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,
tools: ChatToolDefinition[] = [],
- onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string,
+ variant?: string, threadId?: string,
): Promise<Completion> => {
for (;;) {
const attemptedRoute = routes.routeFor(model, tools.length > 0); let replied = false;
@@ -465,7 +466,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
return await completeOn(attemptedRoute, messages, model, stream, signal, onDelta && ((text, kind) => {
replied = true;
onDelta(text, kind);
- }), tools, onUsage, variant, threadId);
+ }), tools, variant, threadId);
} catch (error) {
if (!(error instanceof ModelRouteRefused) || replied || signal?.aborted) throw error;
if (routes.routeFor(model, tools.length > 0) === attemptedRoute && !routes.advance(model, error.refusal)) throw new ChatProtocolError(noRouteLeft(error.message));
@@ -648,7 +649,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (streamKind === "assistant_text") answerStreamed = true;
const shown = holdback && streamKind === "assistant_text" ? holdback.feed(text) : text;
if (shown) delta(shown, streamKind);
- }, tools.definitions, undefined, turn.variant, turn.threadId);
+ }, tools.definitions, turn.variant, turn.threadId);
// A reply cut off at the token limit may be a call cut short; running half of one is worse than saying so.
const written = holdback && !completion.toolCalls.length && completion.finishReason !== "length" ? textToolCalls(completion.text, tools.definitions) : null;
unreadable = written?.kind === "unreadable" && !askedAgain;
@@ -978,13 +979,16 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
return () => listeners.delete(listener);
},
},
- generateText: async (prompt, { signal, onUsage, model: named, checkModel } = {}) => {
+ generateText: async (prompt, { signal, onUsage, model: named, checkModel, maxOutputTokens, finalTextOnly } = {}) => {
const model = named ?? options.generateModel?.() ?? options.models().default;
signal?.throwIfAborted();
checkModel?.(model);
- const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage);
+ const route = finalTextOnly && routes.routeFor(model, true) === "responses" ? "responses" : "chat";
+ const { text, reasoning, toolCalls, responseOutput } = await completeOn(route,
+ [{ role: "user", content: prompt }], model, false, signal, undefined, [], undefined, undefined, { onUsage, maxOutputTokens });
if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");
- return text.trim() ? text : reasoning;
+ if (finalTextOnly && responseOutput) return finalResponseText(responseOutput);
+ return finalTextOnly || text.trim() ? text : reasoning;
},
dispose: async () => {
const turns = [...active.values()];
diff --git a/server/drivers/openai-responses.test.ts b/server/drivers/openai-responses.test.ts
index 24a51984d8..05ca6481de 100644
--- a/server/drivers/openai-responses.test.ts
+++ b/server/drivers/openai-responses.test.ts
@@ -359,6 +359,34 @@ describe("a model that refuses tools over Chat Completions, at OpenAI's address"
expect(f.calls[2]!.body).not.toHaveProperty("reasoning_effort");
expect(onUsage).toHaveBeenCalledWith(expect.objectContaining({ input: 3, output: 2 }));
});
+
+ it.each([[OPENAI, "max_completion_tokens"], ["relay", "max_tokens"]])("caps a title completion and discards reasoning-only output on %s", async (apiUrl, field) => {
+ const f = await fixture((_call, response) => {
+ reject(response, 200, JSON.stringify({ choices: [{ message: { content: null, reasoning_content: "Thinking it over." }, finish_reason: "length" }] }));
+ }, apiUrl);
+ await expect(f.instance.generateText!("Name this", { model: MODEL, finalTextOnly: true, maxOutputTokens: 512 })).resolves.toBe("");
+ await expect(f.instance.generateText!("Other helper job", { model: MODEL })).resolves.toBe("Thinking it over.");
+ expect(f.calls[0]?.body[field]).toBe(512);
+ expect(f.calls[1]?.body).not.toHaveProperty(field);
+ });
+
+ it("caps a title on the learned Responses route and keeps only final assistant text", async () => {
+ const f = await fixture((call, response, nth) => {
+ if (call.path.endsWith("/chat/completions")) return reject(response, 400, refusalOf(MODEL));
+ if (nth === 2) return answer(response);
+ const output = [reasoningItem(), messageItem("I will name this chat.", "msg_intro", "commentary")];
+ if (nth === 3) output.push(messageItem("A short title"));
+ events(response, [completed(output)]);
+ });
+ expect(await f.turn()).toMatchObject({ end: { ok: true } });
+ const onUsage = vi.fn();
+ const options = { model: MODEL, finalTextOnly: true, maxOutputTokens: 512, onUsage };
+ await expect(f.instance.generateText!("Name this", options)).resolves.toBe("A short title");
+ await expect(f.instance.generateText!("Name this", options)).resolves.toBe("");
+ expect(f.paths().slice(2)).toEqual(["/v1/responses", "/v1/responses"]);
+ expect(f.calls[2]?.body).toMatchObject({ max_output_tokens: 512, store: false, tools: [] });
+ expect(onUsage).toHaveBeenCalledWith({ model: MODEL, input: 40, output: 12, cachedInput: 8 });
+ });
});
describe("tool rounds over Responses", () => {
diff --git a/server/host/handed-thread-title.test.ts b/server/host/handed-thread-title.test.ts
index 255ec8caf0..18e37557aa 100644
--- a/server/host/handed-thread-title.test.ts
+++ b/server/host/handed-thread-title.test.ts
@@ -1,52 +1,79 @@
import { describe, expect, it, vi } from "vitest";
import type { BotRecord, TaskRecord } from "../store.ts";
import { createHandedThreadTitle } from "./handed-thread-title.ts";
+import { createAutomaticThreadTitles, TITLE_REPLY_WAIT_MS } from "./thread-titles.ts";
-function place(options: { gate?: boolean; answer?: string | null; renamedTo?: string } = {}) {
- const tasks = new Map<string, { title: string }>([["work-1", { title: "@Clive · work" }]]);
- const generate = vi.fn(async () => {
- if (options.renamedTo) tasks.get("work-1")!.title = options.renamedTo;
- return options.answer === undefined ? "CSV export build" : options.answer;
- });
+function place() {
+ const task = { title: "@Clive · work" } as TaskRecord;
+ const generate = vi.fn<typeof import("../thread-title-generate.ts").generateThreadTitle>().mockResolvedValue("CSV export build");
+ const titles = createAutomaticThreadTitles(generate);
const title = createHandedThreadTitle({
store: {
- bot: (id) => (id === "dana" ? ({ id } as BotRecord) : null),
- taskByThread: (_botId, threadId) => tasks.get(threadId) as TaskRecord | undefined,
- retitleTask: (_botId, threadId, machineTitle, next) => {
- const task = tasks.get(threadId);
- if (!task || task.title !== machineTitle) return null;
+ projectBotForTask: (id) => id === "dana" ? { id } as BotRecord : null,
+ taskByThread: (id) => id === "dana" ? task : undefined,
+ retitleTask: (_botId, _threadId, machineTitle, next) => {
+ if (task.title !== machineTitle) return null;
task.title = next;
- return task as TaskRecord;
+ return task;
},
},
- gate: () => (options.gate === false ? { ok: false } : { ok: true, instance: {} }),
- generate,
+ gate: () => ({ ok: true, instance: {} }),
+ start: titles.start,
});
- return { title, generate, titleOf: () => tasks.get("work-1")!.title };
+ return { title, titles, generate, task };
}
describe("a thread a teammate opened", () => {
- it("is named from the job it was handed, behind who handed it", async () => {
+ it("waits for the right reply and keeps the prefix on its generated title", async () => {
const p = place();
p.title("dana", "work-1", "Implement the CSV export", "@Clive · ");
- await vi.waitFor(() => expect(p.titleOf()).toBe("@Clive · CSV export build"));
- expect(p.generate).toHaveBeenCalledWith({}, "Implement the CSV export");
+ p.titles.turnStarted("work-1", "current");
+ p.titles.turnEnded("work-1", "previous", "An earlier reply");
+ expect(p.generate).not.toHaveBeenCalled();
+ p.titles.turnEnded("work-1", "current", "Added accounting CSV support.");
+ await vi.waitFor(() => expect(p.task.title).toBe("@Clive · CSV export build"));
+ expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "User: Implement the CSV export\nBot: Added accounting CSV support.", "first-reply");
});
- it("keeps a rename made while the name was being thought of", async () => {
- const p = place({ renamedTo: "Mine" });
- p.title("dana", "work-1", "Implement the CSV export", "@Clive · ");
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(p.generate).toHaveBeenCalled();
- expect(p.titleOf()).toBe("Mine");
+ it("accepts a room summary reply from the next speaker after an empty turn", async () => {
+ const p = place();
+ p.title("dana", "work-1", "Implement it", "@Clive · ");
+ p.titles.turnStarted("work-1", "first", true);
+ p.titles.turnStarted("work-1", "reask", true);
+ p.titles.turnEnded("work-1", "first", "Old progress message");
+ expect(p.generate).not.toHaveBeenCalled();
+ p.titles.turnEnded("work-1", "reask", "Implemented.");
+ await vi.waitFor(() => expect(p.task.title).toBe("@Clive · CSV export build"));
+ expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "User: Implement it\nBot: Implemented.", "first-reply");
+ });
+
+ it("keeps a manual rename even if the text matches the opening title", async () => {
+ const p = place();
+ p.generate.mockImplementationOnce(async () => {
+ p.task.titleMode = "manual";
+ return "New name";
+ });
+ p.title("dana", "work-1", "Implement it", "@Clive · ");
+ p.titles.turnEnded("work-1", "current", "Implemented.");
+ await Promise.resolve();
+ expect(p.generate).toHaveBeenCalledOnce();
+ expect(p.task.title).toBe("@Clive · work");
});
- it("keeps its first title when the model can't name it, gives no name, or there is nothing to name it from", async () => {
- for (const [p, brief, botId] of [[place({ gate: false }), "Implement it", "dana"], [place({ answer: null }), "Implement it", "dana"],
- [place(), " ", "dana"], [place(), "Implement it", "gone"]] as const) {
- p.title(botId, "work-1", brief, "@Clive · ");
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(p.titleOf()).toBe("@Clive · work");
+ it("uses the sanitised brief once after the wait runs out and ignores a late reply", async () => {
+ vi.useFakeTimers();
+ try {
+ const p = place();
+ p.title("dana", "work-1", 'Implement it <attached-image path="/private/image" />', "@Clive · ");
+ await vi.advanceTimersByTimeAsync(TITLE_REPLY_WAIT_MS - 1);
+ expect(p.generate).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "User: Implement it", "first-message");
+ p.titles.turnEnded("work-1", "current", "Implemented.");
+ expect(p.generate).toHaveBeenCalledOnce();
+ expect(p.task.title).toBe("@Clive · CSV export build");
+ } finally {
+ vi.useRealTimers();
}
});
});
diff --git a/server/host/handed-thread-title.ts b/server/host/handed-thread-title.ts
index 59c4d6c2f6..a6fc115cd6 100644
--- a/server/host/handed-thread-title.ts
+++ b/server/host/handed-thread-title.ts
@@ -1,24 +1,23 @@
import type { BotRecord, Store } from "../store.ts";
+import type { AutomaticTitle, ThreadTitleGate } from "./thread-titles.ts";
-type TitleModel = { generateText?: (prompt: string, options?: { signal?: AbortSignal }) => Promise<string> };
-
-/** A thread a teammate opened is named from the job it was handed, as a person's first message names theirs. A work
- * thread keeps "@Sender · " in front, so the sidebar still says who the work is for. The name lands only while the
- * thread still has the title it opened with: a rename in the meantime wins. */
-export function createHandedThreadTitle<Model extends TitleModel>(deps: {
- store: Pick<Store, "bot" | "taskByThread" | "retitleTask">;
- gate: (bot: BotRecord) => { ok: true; instance: Model } | { ok: false };
- generate: (model: Model, text: string) => Promise<string | null>;
+export function createHandedThreadTitle(deps: {
+ store: Pick<Store, "projectBotForTask" | "taskByThread" | "retitleTask">;
+ gate: (bot: BotRecord) => ThreadTitleGate;
+ start: (threadId: string, attempt: AutomaticTitle) => void;
}): (botId: string, threadId: string, brief: string, prefix: string) => void {
return (botId, threadId, brief, prefix) => {
- const bot = deps.store.bot(botId), machineTitle = deps.store.taskByThread(botId, threadId)?.title;
- if (!bot || !machineTitle || !brief.trim()) return;
- const gate = deps.gate(bot);
- if (!gate.ok) return;
- void deps.generate(gate.instance, brief)
- .then((title) => {
- if (title) deps.store.retitleTask(botId, threadId, machineTitle, `${prefix}${title}`);
- })
- .catch(() => undefined);
+ const task = () => deps.store.taskByThread(botId, threadId);
+ const machineTitle = task()?.title;
+ if (!machineTitle || !brief.trim()) return;
+ deps.start(threadId, {
+ request: brief,
+ stillCurrent: () => task()?.title === machineTitle && task()?.titleMode !== "manual",
+ model: () => {
+ const bot = deps.store.projectBotForTask(botId, threadId);
+ return bot ? deps.gate(bot) : { ok: false, refusal: "The thread is unavailable." };
+ },
+ apply: (title) => { deps.store.retitleTask(botId, threadId, machineTitle, `${prefix}${title}`); },
+ });
};
}
diff --git a/server/host/thread-titles.ts b/server/host/thread-titles.ts
new file mode 100644
index 0000000000..7428df2862
--- /dev/null
+++ b/server/host/thread-titles.ts
@@ -0,0 +1,70 @@
+import { generateThreadTitle } from "../thread-title-generate.ts";
+import { titleTurnExcerpt, type ThreadTitleSource } from "../thread-title.ts";
+
+export const TITLE_REPLY_WAIT_MS = 30_000;
+type TitleModel = Parameters<typeof generateThreadTitle>[0];
+export type ThreadTitleGate = { ok: true; instance: TitleModel } | { ok: false; refusal: string };
+
+export interface AutomaticTitle {
+ request: string;
+ currentTitle?: string;
+ stillCurrent(): boolean;
+ model(): ThreadTitleGate;
+ apply(title: string): void;
+}
+
+export function createAutomaticThreadTitles(generate = generateThreadTitle) {
+ const pending = new Map<string, {
+ attempt: AutomaticTitle;
+ timer: ReturnType<typeof setTimeout>;
+ turnId?: string;
+ generating?: true;
+ }>();
+
+ function drop(threadId: string) {
+ const current = pending.get(threadId);
+ if (current) clearTimeout(current.timer);
+ pending.delete(threadId);
+ }
+
+ async function finish(threadId: string, turnId?: string, reply?: string) {
+ const current = pending.get(threadId);
+ if (!current || current.generating || (turnId !== undefined && current.turnId !== undefined && current.turnId !== turnId)) return;
+ clearTimeout(current.timer);
+ current.generating = true;
+ try {
+ const { attempt } = current;
+ if (!attempt.stillCurrent() || (attempt.currentTitle && !reply)) return;
+ const excerpt = titleTurnExcerpt(attempt.request, reply, attempt.currentTitle);
+ if (!excerpt) return;
+ const gate = attempt.model();
+ if (!gate.ok) {
+ console.warn("title generation: model-unavailable");
+ return;
+ }
+ const source: ThreadTitleSource = attempt.currentTitle ? "follow-up" : reply ? "first-reply" : "first-message";
+ const title = await generate(gate.instance, excerpt, source);
+ if (title && pending.get(threadId) === current && attempt.stillCurrent()) attempt.apply(title);
+ } catch (error) {
+ console.warn(`title generation: ${error instanceof Error ? error.name : "error"}`);
+ } finally {
+ if (pending.get(threadId) === current) drop(threadId);
+ }
+ }
+
+ return {
+ start(threadId: string, attempt: AutomaticTitle) {
+ if (pending.has(threadId)) return;
+ const timer = setTimeout(() => void finish(threadId), TITLE_REPLY_WAIT_MS);
+ timer.unref();
+ pending.set(threadId, { attempt, timer });
+ },
+ generating: (threadId: string) => pending.get(threadId)?.generating === true,
+ turnStarted(threadId: string, turnId?: string, room = false) {
+ const current = pending.get(threadId);
+ if (current && turnId && (room || current.turnId === undefined)) current.turnId = turnId;
+ },
+ turnEnded: (threadId: string, turnId?: string, reply?: string) => void finish(threadId, turnId, reply?.trim() || undefined),
+ drop,
+ };
+}
diff --git a/server/index.test.ts b/server/index.test.ts
index 0b816667bf..3a766a5442 100644
--- a/server/index.test.ts
+++ b/server/index.test.ts
@@ -2266,8 +2266,9 @@ describe("harness HTTP API", () => {
}
});
- it("replaces a first-message snippet title with a generated one once the one-shot answers", async () => {
+ it("replaces a first-message snippet title after the bot replies, using both excerpts", async () => {
writeFileSync(oneShotTextFile, "Fix login timeout\n");
+ rmSync(oneShotTextDump, { force: true });
const created = await api("POST", "/api/bots", {
modelSelection: { instanceId: "claude", model: "claude-sonnet-5" },
requireAvailableModel: true,
@@ -2279,12 +2280,16 @@ describe("harness HTTP API", () => {
text: "every login hangs after the session expires",
});
expect(sent.status).toBe(202);
+ await releaseTurn(bot.id);
await expect.poll(async () => {
const state = (await api("GET", "/api/bots?messages=0")).body.bots.find(
(candidate: { id: string }) => candidate.id === bot.id,
);
return state?.tasks?.find((task: { threadId: string }) => task.threadId === sent.body.threadId)?.title;
}, { timeout: 5_000 }).toBe("Fix login timeout");
+ const { prompt } = JSON.parse(readFileSync(oneShotTextDump, "utf8"));
+ expect(prompt).toContain("every login hangs after the session expires");
+ expect(prompt).toContain("Bot: released");
} finally {
await api("POST", `/api/bots/${bot.id}/interrupt`).catch(() => undefined);
await api("DELETE", `/api/bots/${bot.id}`);
@@ -2292,6 +2297,60 @@ describe("harness HTTP API", () => {
}
});
+ it("validates and saves the title model without losing the follow-up setting", async () => {
+ try {
+ expect((await api("PATCH", "/api/config", { threadTitles: { model: { instanceId: "missing", model: "missing" } } })).status).toBe(400);
+ const model = { instanceId: "claude", model: "claude-sonnet-5" };
+ expect((await api("PATCH", "/api/config", { threadTitles: { model } })).status).toBe(200);
+ const configured = await api("PATCH", "/api/config", { threadTitles: { followUp: true } });
+ expect(configured.status).toBe(200);
+ expect(configured.body.threadTitles).toMatchObject({ model, followUp: true });
+ expect((await api("GET", "/api/config")).body.threadTitles).toMatchObject({ model, followUp: true });
+ expect((await api("PATCH", "/api/config", { threadTitles: { model: null } })).body.threadTitles).toMatchObject({ model: null, followUp: true });
+ } finally {
+ await api("PATCH", "/api/config", { threadTitles: { model: null, followUp: false } });
+ }
+ });
+
+ it("only updates a generated title on follow-up when enabled, and keeps a manual rename", async () => {
+ writeFileSync(oneShotTextFile, "Login | timeout fix\n");
+ const created = await api("POST", "/api/bots", { modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, requireAvailableModel: true });
+ expect(created.status).toBe(201);
+ const bot = created.body.bot;
+ const title = async () => (await api("GET", "/api/bots?messages=0")).body.bots.find((candidate: { id: string }) => candidate.id === bot.id)
+ .tasks.find((task: { threadId: string }) => task.threadId === bot.threadId).title;
+ try {
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Fix the login timeout" })).status).toBe(202);
+ await releaseTurn(bot.id);
+ await expect.poll(title, { timeout: 5_000 }).toBe("Login | timeout fix");
+ writeFileSync(oneShotTextFile, "Billing | tax export\n");
+ rmSync(oneShotTextDump, { force: true });
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Now fix the tax export" })).status).toBe(202);
+ await releaseTurn(bot.id);
+ expect(existsSync(oneShotTextDump)).toBe(false);
+ expect(await title()).toBe("Login | timeout fix");
+ expect((await api("PATCH", "/api/config", { threadTitles: { followUp: true } })).status).toBe(200);
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Now fix the tax export" })).status).toBe(202);
+ await releaseTurn(bot.id);
+ await expect.poll(title, { timeout: 5_000 }).toBe("Billing | tax export");
+ const generated = JSON.parse(readFileSync(oneShotTextDump, "utf8"));
+ expect(generated.prompt).toContain("Current title: Login | timeout fix");
+ expect(generated.prompt).toContain("Bot: released");
+ expect((await api("PATCH", `/api/bots/${bot.id}/tasks/${bot.threadId}`, { title: "Billing | tax export" })).status).toBe(200);
+ writeFileSync(oneShotTextFile, "Unwanted title\n");
+ rmSync(oneShotTextDump, { force: true });
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "Also check invoices" })).status).toBe(202);
+ await releaseTurn(bot.id);
+ expect(existsSync(oneShotTextDump)).toBe(false);
+ expect(await title()).toBe("Billing | tax export");
+ } finally {
+ await api("PATCH", "/api/config", { threadTitles: { followUp: false } }).catch(() => undefined);
+ await api("POST", `/api/bots/${bot.id}/interrupt`).catch(() => undefined);
+ await api("DELETE", `/api/bots/${bot.id}`);
+ rmSync(oneShotTextFile, { force: true });
+ }
+ });
+
it("keeps the snippet title when the one-shot fails", async () => {
rmSync(oneShotTextFile, { force: true });
const created = await api("POST", "/api/bots", {
@@ -2305,11 +2364,13 @@ describe("harness HTTP API", () => {
rmSync(oneShotTextDump, { force: true });
const sent = await api("POST", `/api/bots/${bot.id}/messages`, { text: firstMessage });
expect(sent.status).toBe(202);
+ await releaseTurn(bot.id);
await expect.poll(() => existsSync(oneShotTextDump), { timeout: 5_000 }).toBe(true);
const seen = JSON.parse(readFileSync(oneShotTextDump, "utf8"));
const outputAt = seen.argv.indexOf("--output-format");
expect(outputAt).toBeGreaterThan(-1);
- expect(seen.argv[outputAt + 1]).toBe("text");
+ expect(seen.argv[outputAt + 1]).toBe("json");
+ expect(seen.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS).toBe("512");
expect(seen.prompt).toContain("Name the conversation");
await new Promise((resolve) => setTimeout(resolve, 150));
const state = (await api("GET", "/api/bots?messages=0")).body.bots.find(
@@ -2341,6 +2402,7 @@ describe("harness HTTP API", () => {
text: "every login hangs after the session expires",
});
expect(sent.status).toBe(202);
+ writeFileSync(fakeClaudeRelease, "release");
await expect.poll(async () => {
const state = (await api("GET", "/api/bots?messages=0")).body.groups.find(
(candidate: { id: string }) => candidate.id === room.id,
@@ -2348,6 +2410,42 @@ describe("harness HTTP API", () => {
return state?.tasks?.find((task: { threadId: string }) => task.threadId === room.threadId)?.title;
}, { timeout: 5_000 }).toBe("Fix login timeout");
} finally {
+ rmSync(fakeClaudeRelease, { force: true });
+ await api("POST", `/api/groups/${room.id}/interrupt`, {}).catch(() => undefined);
+ await api("DELETE", `/api/groups/${room.id}`);
+ await api("DELETE", `/api/bots/${member.id}`);
+ rmSync(oneShotTextFile, { force: true });
+ }
+ });
+
+ it("keeps a room's manual title when follow-up renames are enabled", async () => {
+ writeFileSync(oneShotTextFile, "Login | timeout fix\n");
+ const created = await api("POST", "/api/bots", { modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, requireAvailableModel: true });
+ expect(created.status).toBe(201);
+ const member = created.body.bot;
+ const room = (await api("POST", "/api/groups", { name: "Titles", memberIds: [member.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: member.id } } })).body.group;
+ const title = async () => (await api("GET", "/api/bots?messages=0")).body.groups.find((candidate: { id: string }) => candidate.id === room.id)
+ .tasks.find((task: { threadId: string }) => task.threadId === room.threadId).title;
+ try {
+ expect((await api("PATCH", "/api/config", { threadTitles: { followUp: true } })).status).toBe(200);
+ expect((await api("POST", `/api/groups/${room.id}/messages`, { text: "Fix the login timeout" })).status).toBe(202);
+ writeFileSync(fakeClaudeRelease, "release");
+ await expect.poll(title, { timeout: 5_000 }).toBe("Login | timeout fix");
+ await expect.poll(async () => (await api("GET", "/api/bots?messages=0")).body.groups.find((candidate: { id: string }) => candidate.id === room.id)?.working, { timeout: 10_000 }).toBe(false);
+ rmSync(fakeClaudeRelease, { force: true });
+ const pinned = await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { pinned: true, title: "Fix the login timeout" });
+ expect(pinned.body.task).toMatchObject({ pinned: true, title: "Login | timeout fix" });
+ expect((await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { title: "My room title" })).status).toBe(200);
+ writeFileSync(oneShotTextFile, "Unwanted title\n");
+ rmSync(oneShotTextDump, { force: true });
+ expect((await api("POST", `/api/groups/${room.id}/messages`, { text: "Now check the tax export" })).status).toBe(202);
+ writeFileSync(fakeClaudeRelease, "release");
+ await expect.poll(async () => (await api("GET", "/api/bots?messages=0")).body.groups.find((candidate: { id: string }) => candidate.id === room.id)?.working, { timeout: 10_000 }).toBe(false);
+ expect(existsSync(oneShotTextDump)).toBe(false);
+ expect(await title()).toBe("My room title");
+ } finally {
+ rmSync(fakeClaudeRelease, { force: true });
+ await api("PATCH", "/api/config", { threadTitles: { followUp: false } }).catch(() => undefined);
await api("POST", `/api/groups/${room.id}/interrupt`, {}).catch(() => undefined);
await api("DELETE", `/api/groups/${room.id}`);
await api("DELETE", `/api/bots/${member.id}`);
@@ -2385,6 +2483,7 @@ describe("harness HTTP API", () => {
rmSync(oneShotTextDump, { force: true });
const sent = await api("POST", `/api/groups/${room.id}/messages`, { text });
expect(sent.status).toBe(202);
+ writeFileSync(fakeClaudeRelease, "release");
await expect.poll(() => existsSync(oneShotTextDump), { timeout: 5_000 }).toBe(true);
const seen = JSON.parse(readFileSync(oneShotTextDump, "utf8"));
expect(seen.prompt).toContain(firstMessage);
@@ -2396,6 +2495,7 @@ describe("harness HTTP API", () => {
expect(state.tasks.find((task: { threadId: string }) => task.threadId === room.threadId).title)
.toBe(firstMessage);
} finally {
+ rmSync(fakeClaudeRelease, { force: true });
await api("POST", `/api/groups/${room.id}/interrupt`, {}).catch(() => undefined);
await api("DELETE", `/api/groups/${room.id}`);
await api("DELETE", `/api/bots/${member.id}`);
diff --git a/server/index.ts b/server/index.ts
index 2d5930c9d1..6ade017175 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -333,7 +333,7 @@ import { buildRecoveryText, buildTurnContext, replaysNatively } from "./turn-con
import { Handoffs, isContextMessage, recordHanded, renderUnseen, sessionStart, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";
import { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";
import { callTitleExcerpt } from "./thread-title.ts";
-import { generateThreadTitle } from "./thread-title-generate.ts"; import { createHandedThreadTitle } from "./host/handed-thread-title.ts"; import { handedMainThread, postHandedLine, writeHandedLine, type HandedLineDeps } from "./host/handed-line.ts";
+import { generateThreadTitle } from "./thread-title-generate.ts"; import { createAutomaticThreadTitles, type ThreadTitleGate } from "./host/thread-titles.ts"; import { createHandedThreadTitle } from "./host/handed-thread-title.ts"; import { handedMainThread, postHandedLine, writeHandedLine, type HandedLineDeps } from "./host/handed-line.ts";
import { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts"; import { createDispatchClaims } from "./host/dispatch-claims.ts";
import { TurnResources, type TurnOwner } from "./turn-resources.ts";
import { createPhoneHold } from "./phone-screen/hold.ts"; import { createPhoneGate } from "./routes/phone-gate.ts";
@@ -573,7 +573,7 @@ import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret
// Keep these two last, so loading the route table leaves module start-up order as is.
import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";
import { holdBodyDeadline } from "./body-deadline.ts";
-import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { createLinkLimits, LINK_ACTION_DENIED, LINK_APP_WRITE_REFUSAL, LINK_COMMANDS_OFF, LINK_ENGINE_REFUSAL, LINK_ROUTE_REFUSAL, linkAppWriteRefused, linkHandOnRefusal, linkRouteRefused } from "./bot-link/far-side.ts"; import { followRoomMentions } from "./host/bot-link-rooms.ts"; import { standInAmong, standInWriteRefusal } from "./host/stand-in-guard.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage, pagesAccess, pagesNotOffered } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { arrivalsFile, desktopMainMover, mcpServersHere, staysOnCloud, thisComputerOwner } from "./move-back.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
+import { isLinkedId } from "./bot-link/protocol.ts"; import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createBotLinkHost } from "./host/bot-link-host.ts"; import { createLinkLimits, LINK_ACTION_DENIED, LINK_APP_WRITE_REFUSAL, LINK_COMMANDS_OFF, LINK_ENGINE_REFUSAL, LINK_ROUTE_REFUSAL, linkAppWriteRefused, linkHandOnRefusal, linkRouteRefused } from "./bot-link/far-side.ts"; import { followRoomMentions } from "./host/bot-link-rooms.ts"; import { standInAmong, standInWriteRefusal } from "./host/stand-in-guard.ts"; import { isBotLinkHeldPath, linkSessionRefusal } from "./routes/bot-link.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage, pagesAccess, pagesNotOffered } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, botMoveRefusal, createBotMoves } from "./bot-moves.ts"; import { arrivalsFile, desktopMainMover, mcpServersHere, staysOnCloud, thisComputerOwner } from "./move-back.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";
import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";
import { createBotMemoryRoutes } from "./routes/bot-memory.ts"; import { createBotLibraryRoutes } from "./routes/bot-library.ts";
@@ -3854,7 +3854,7 @@ const validateModelProposal = (selection: ModelSelection, current?: BotRecord):
}
return null;
}; const engineHints = createEngineHints({ registry, access: (id) => providerConfigs()[id]?.access ?? registry.access(id), managed: (id) => managedDesktop.owns(id), policy: policyModelRefusal, ...(hostedModels ? { offered: (selection) => hostedModels!.allows(selection) } : {}) }); const ownThreads = createOwnThreads({ store, registry, node: (id) => coordinator.node(id), current: turnSelection, proposalRefusal: validateModelProposal, givesWay: modelGivesWay, modelName, hint: engineHints.hint, broken: engineHints.broken, localOnce: (engines) => localModelsOnce(engines, directLocalModels(providerConfigs(), (id, saved) => { const engine = registry.get(id), live = threadEngine(id); if (!engine || !live || !readyToRun(live, selectionContext)) return null; return { name: engine.displayName || id, models: [...saved, ...engine.models.options.map((option) => option.id)].filter((model) => !hostedModels || hostedModels.allows({ instanceId: id, model })) }; })), sourceLevel: sourceApprovalMode, mayRaise: (threadId) => !outsideLineage.handsNoLevel(threadId) && (!CLOUD_HOME || cloudOwnerPerson(threadPersonKey(threadId))) && (!HOSTED_WORKSPACE || sharedWorkspaceFullAccessEnabled()) });
-const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
+const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => botMainThread(botId) ?? store.bot(botId)?.threadId) }; const automaticTitles = createAutomaticThreadTitles(); const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, start: automaticTitles.start }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),
now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },
log: line => console.error("coordinator:", line),
@@ -4109,7 +4109,7 @@ function beginGroupTurnOperation(
function finishGroupTurnOperation(groupId: string, operation: GroupTurnOperation) {
roomMemberLock.releaseThread(operation.threadId);
- roomTurnEnded(operation);
+ roomTurnEnded(operation); automaticTitles.turnEnded(operation.threadId);
if (operation.goalRun && !operation.goalRun.finished) {
finishGroupGoalRun(groupId, operation, "failed", "The team run ended before the lead reported an outcome.");
}
@@ -4473,7 +4473,7 @@ store.onChange((change) => {
for (const botId of computerControl.recheck([change.threadId])) announceControl(botId);
break;
case "thread.deleted":
- directRequestOwners.delete(change.threadId);
+ automaticTitles.drop(change.threadId); directRequestOwners.delete(change.threadId);
for (const botId of computerControl.forgetThread(change.threadId)) announceControl(botId);
stoppedTurns.delete(change.threadId); threadMaps.forget(change.threadId);
turnStops.forget(change.threadId);
@@ -5063,7 +5063,7 @@ const sideJobs = createSideJobs({
refusal: (instance) => policyModelRefusal(instance), smallModels: quickFallback,
helper: cacheUntilConfigChanges((config) => helperSelection(config)),
...(hostedModels ? { modelAllowed: (selection: ModelSelection) => hostedModels.allows(selection) } : {}),
- assertWithinBudget: () => { assertWithinBudget(cfg, DATA_DIR); usageCapGate.assertTurn(undefined, true); },
+ assertWithinBudget: (botId) => { assertWithinBudget(cfg, DATA_DIR); usageCapGate.assertTurn(botId, botId === undefined); },
book: bookTurnUsage, lightModel: lightModelFor,
log: (line) => console.log(line),
});
@@ -6367,7 +6367,7 @@ bus.subscribe((event: RuntimeEvent) => {
const liveTurnId = event.turnId ?? liveTurnByThread.get(event.threadId);
switch (event.type) {
case "turn.started":
- turnStartedAt.set(event.threadId, Date.now());
+ turnStartedAt.set(event.threadId, Date.now()); if (!replayed) automaticTitles.turnStarted(event.threadId, event.turnId, Boolean(group));
// A stop that never saw its turn.completed must not pass for this turn.
stoppedTurns.delete(event.threadId); personStops.turnStarted(event.threadId, event.turnId);
break;
@@ -6645,7 +6645,8 @@ bus.subscribe((event: RuntimeEvent) => {
.map((message) => message.text ?? "").join("\n"));
}
if (bot) void replyVoiceNotes.turnSettled({ bot, threadId: event.threadId, turnId: completedTurnId, stoppedByPerson: personStops.stopped(event.threadId, completedTurnId), internal, ...(event.ok ? {} : { ending: { stop: turnStops.read(event.threadId, completedTurnId), cause: turnStops.failureCause(event), interrupted: event.stopReason === "interrupted" } }) });
- const reply = lastReply.get(event.threadId) ?? "";
+ const reply = lastReply.get(event.threadId) ?? "", titleReply = event.ok && !stopped && !replayed ? reply.trim() : "";
+ if (!replayed && (bot || titleReply)) automaticTitles.turnEnded(event.threadId, completedTurnId, titleReply);
if (personStops.stopped(event.threadId, completedTurnId)) pushStoppedTurn(completedTurnId);
personStops.turnEnded(event.threadId, completedTurnId);
lastReply.delete(event.threadId);
@@ -7390,18 +7391,17 @@ async function finalScreenFrame(_botId: string, threadId: string): Promise<Frame
return frame;
}
-function threadTitleGate(bot: Pick<BotRecord, "modelSelection">): { ok: true; instance: ProviderInstance } | { ok: false; refusal: string } {
+function threadTitleGate(bot: BotRecord, ownOnly = false): ThreadTitleGate {
if (hostedModels && !hostedModels.allows(bot.modelSelection)) return { ok: false, refusal: hostedModels.error() };
- const instance = registry.get(bot.modelSelection.instanceId);
- if (!instance?.generateText) return { ok: false, refusal: "this bot's model can't generate a title — rename the thread instead" };
- const refusal = policyModelRefusal(instance);
+ const own = registry.get(bot.modelSelection.instanceId), refusal = own && policyModelRefusal(own);
if (refusal) return { ok: false, refusal };
- try {
- assertWithinBudget(cfg, DATA_DIR);
- } catch (error) {
- return { ok: false, refusal: error instanceof Error ? error.message : String(error) };
- }
- return { ok: true, instance };
+ try { assertWithinBudget(cfg, DATA_DIR); usageCapGate.assertTurn(bot.id, false, threadLanguage(bot.threadId)); }
+ catch (error) { return { ok: false, refusal: error instanceof Error ? error.message : String(error) }; }
+ const opener = store.taskByThread(bot.id, bot.threadId)?.openedBy?.botId;
+ const confined = cloudGuestDriven(bot.threadId) || botApiThread(bot.threadId) || linkLimits.held(bot.threadId) || (opener && isLinkedId(opener));
+ const instance = sideJobs.text("thread-title", bot.id, { instance: own ?? undefined, modelSelection: bot.modelSelection,
+ ...(ownOnly || confined ? { ownOnly: true } : { titleModel: cfg.threadTitles?.model }) });
+ return instance?.generateText ? { ok: true, instance } : { ok: false, refusal: "No available model can generate a title for this thread." };
}
const titleRegenerations = new Set<string>();
@@ -7525,22 +7525,22 @@ async function beginTurn(
else { clearInternalTurn(threadId); doneNotice.personTurnStarted(threadId); }
if (answer.quiet) quietTurnThreads.add(threadId);
else quietTurnThreads.delete(threadId);
+ const turnLineIds = new Set(opts?.excludeMessageIds ?? []);
+ const spoken = opts?.via === "call" || opts?.userMessage?.via === "call" ||
+ (turnLineIds.size > 0 && store.messagesFor(threadId).some((message) => turnLineIds.has(message.id) && message.via === "call"));
if (resolvedImages.text.trim() && !opts?.cardContinuation && !opts?.replyTo?.reactedWith) {
const titled = store.titleTaskFromFirstMessage(bot.id, resolvedImages.text, threadId);
- const snippet = titled?.title, titleGate = titled && snippet && !titled.openedBy?.botId ? threadTitleGate(bot) : null;
- if (snippet && titleGate?.ok) {
- void generateThreadTitle(titleGate.instance, resolvedImages.text)
- .then((title) => {
- if (title) store.retitleTask(bot.id, threadId, snippet, title);
- })
- .catch(() => undefined);
+ const task = () => store.taskByThread(bot.id, threadId), current = task();
+ if (current && !current.openedBy?.botId && !titleRegenerations.has(threadId) && (titled || (cfg.threadTitles?.followUp && current.titleMode === "automatic"))) {
+ const title = current.title;
+ automaticTitles.start(threadId, { request: resolvedImages.text, currentTitle: titled ? undefined : title,
+ stillCurrent: () => task()?.title === title && task()?.titleMode === "automatic" && !titleRegenerations.has(threadId),
+ model: () => threadTitleGate(store.projectBotForTask(bot.id, threadId) ?? bot, spoken || guestConfined || linkLimited),
+ apply: (next) => { store.retitleTask(bot.id, threadId, title, next); } });
}
}
// Spoken words never reach the log.
- const turnLineIds = new Set(opts?.excludeMessageIds ?? []);
- const spoken = opts?.via === "call" || opts?.userMessage?.via === "call" ||
- (turnLineIds.size > 0 && store.messagesFor(threadId).some((message) => turnLineIds.has(message.id) && message.via === "call"));
console.log(turnStartLogLine({
botId, text: resolvedImages.text, images: turnImages.length, depth: commsDepth, card: Boolean(opts?.cardContinuation), spoken,
}));
@@ -8409,6 +8409,7 @@ async function beginTurn(
turnContext.delete(threadId);
}
if (e instanceof DirectTurnSetupCancelled) {
+ if (ownsLatestGeneration) automaticTitles.turnEnded(threadId);
settleDirectFollowup(dispatchClaimId, { ok: false, text: e.message });
opts?.onDispatchError?.(e.message);
if (ownsLatestGeneration && threadBusy(bot.id, threadId)) {
@@ -8481,6 +8482,7 @@ async function beginTurn(
}
} else if (refusal) message = `Automatic recovery unavailable: ${refusal} Original error: ${message}`;
}
+ automaticTitles.turnEnded(threadId);
settleDirectFollowup(dispatchClaimId, { ok: false, text: message });
store.appendMessage(threadId, {
role: "bot",
@@ -10661,8 +10663,7 @@ function startGroupTurn(
sender: options.sender, ...(options.pointed ? { pointed: options.pointed.refs } : {}),
});
if (options.trigger) turnTriggers.set(threadId, options.trigger);
- const titled = group.dm ? null : store.titleGroupTaskFromFirstMessage(group.id, text, threadId);
- const snippet = titled?.title;
+ const titleText = extractTurnImages(text).text, titled = group.dm ? null : store.titleGroupTaskFromFirstMessage(group.id, titleText, threadId);
const archived = members.filter((member) => member.hidden);
const mentionedArchived = mentionedBots(text, archived.map(({ name }) => ({ name })))[0]; for (const line of placesElsewhere.missed(text, store.bots, botLink.reaches)) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line, ok: false } });
@@ -10717,19 +10718,15 @@ function startGroupTurn(
return message;
}
- const titleText = extractTurnImages(text).text;
- const startTitle = (titleBot: (typeof members)[number]) => {
- // An engine the organisation or the hosted plan disallows, or a workspace at its spend cap, never sends the text, even for a title.
- const titleGate = titled && snippet && titleText.trim() ? threadTitleGate(titleBot) : null;
- if (snippet && titleGate?.ok) {
- void generateThreadTitle(titleGate.instance, titleText)
- .then((title) => {
- if (title) store.retitleGroupTask(group.id, threadId, snippet, title);
- })
- .catch(() => undefined);
- }
- };
- if (!autoRoute) startTitle(goalCoordinator ?? responders[0]!);
+ let titleBot = goalCoordinator ?? responders[0];
+ const task = () => store.groupTaskByThread(groupId, threadId), current = task();
+ if (titleText.trim() && current && (titled || (cfg.threadTitles?.followUp && current.titleMode === "automatic"))) {
+ const title = current.title;
+ automaticTitles.start(threadId, { request: titleText, currentTitle: titled ? undefined : title,
+ stillCurrent: () => task()?.title === title && task()?.titleMode === "automatic",
+ model: () => titleBot ? threadTitleGate({ ...titleBot, threadId }, message.via === "call") : { ok: false, refusal: "The room has no responder." },
+ apply: (next) => { store.retitleGroupTask(groupId, threadId, title, next); } });
+ }
const operation = beginGroupTurnOperation(
groupId,
@@ -10778,7 +10775,7 @@ function startGroupTurn(
routedBy = { provider: route.provider, probability: Math.round(route.probability * 100) / 100 };
}
for (const responder of round) operation.botIds.add(responder.id);
- if (round[0]) startTitle(round[0]);
+ titleBot = round[0];
}
let spoken = new Set<string>(); const passes = roomRoundPasses(round, roomTurnsPerMember(store.group(groupId)), (next) => { spoken = next; if (round.length > 1) operation.line = { pending: round.map(responder => responder.id) }; advanceLine(undefined); });
const skillAuthoringClaim = { claimed: false };
@@ -11593,7 +11590,7 @@ function configStatus() {
language: appLanguage() ?? "", computerName: cfg.computerName ?? "", everyBotRules: cfg.everyBotRules ?? "",
rooms: { turnTimeoutMinutes: roomTurnTimeoutMinutes(cfg) },
mcp: { callTimeoutMinutes: mcpCallTimeoutMinutes(cfg) },
- automaticRecovery: cfg.automaticRecovery ?? { enabled: false },
+ automaticRecovery: cfg.automaticRecovery ?? { enabled: false }, threadTitles: { model: cfg.threadTitles?.model ?? null, followUp: cfg.threadTitles?.followUp ?? false, instances: registry.instances().filter((engine) => engine.enabled && engine.generateText && !policyModelRefusal(engine)).map((engine) => engine.instanceId) },
cacheKeepWarm: cacheKeepWarmSettings(cfg),
newBots: cfg.newBots?.effort ? { effort: cfg.newBots.effort } : {},
threads: {
@@ -12110,7 +12107,7 @@ const taskRoutes = createTaskRoutes({
skillReview,
threadStarters,
phoneSecretSubmissions,
- titleRegenerations,
+ titleRegenerations, automaticTitles,
directTurnGenerationByThread,
actorKey,
cloudOwnerSession,
@@ -12293,7 +12290,7 @@ function liveSignedIn(auth: RequestAuth): boolean {
function liveCallTitle(botId: string, threadId: string, excerpt: string): Promise<string | null> | null {
const bot = store.projectBotForTask(botId, threadId);
if (!bot) return null;
- const gate = threadTitleGate(bot);
+ const gate = threadTitleGate(bot, true);
return gate.ok ? generateThreadTitle(gate.instance, excerpt, "call") : null;
}
const liveWiring = liveSessionWiring({ bot: liveBotFor, history: liveHistoryFor, cloudHome: Boolean(CLOUD_HOME), othersOnLoopback: adminActivityRecording, saveAgent: (agent) => { saveConfig({ live: agent }); Object.assign(cfg, loadConfig()); }, language: appLanguage, fishAgentLanguage: () => cfg.live?.fishAgentLanguage });
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index de86be80b3..2aace55973 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -284,8 +284,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
}
const parsedLimit = limiting ? parseConversationTurnTimeout(body.turnTimeoutMinutes) : null;
if (parsedLimit && !parsedLimit.ok) return json(res, 400, { error: parsedLimit.error });
- // Echoing the current title is not a rename: newer clients send it so an older server keeps the title.
- const titleChange = renaming && body.title !== existing.title;
+ // Clients echo a cached title when pinning for compatibility with older servers.
+ const titleChange = !pinning && renaming && body.title !== existing.title;
const notYours = titleChange ? cloudThreadRefusal(auth, m[2]) : null;
if (notYours) return json(res, 403, { error: notYours });
if (titleChange && groupThreadIsWorking(group.id, m[2])) {
diff --git a/server/routes/config.ts b/server/routes/config.ts
index ad7287406c..19a3288ea2 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -152,6 +152,18 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
if (deps.cloudTeam && patch.browserEngine?.egress?.proxy !== undefined && !(auth.kind === "session" && auth.session.teamRole === "owner")) {
return json(res, 403, { error: "Only the Team Cloud owner can configure the browser proxy." });
}
+ if (patch.threadTitles?.model) {
+ const checked = checkedModelSelection(patch.threadTitles.model, undefined, true);
+ if (!checked.ok) return json(res, checked.status, refusalBody(checked));
+ const target = registry.get(checked.selection.instanceId);
+ if (!target?.enabled) return json(res, 400, { error: "Enable the engine before selecting it for thread titles." });
+ const refusal = policyModelRefusal(target);
+ if (refusal) return json(res, 403, { error: refusal, code: "managed_policy" });
+ if (!target.generateText) return json(res, 400, { error: "This engine cannot generate thread titles." });
+ const model = target.models.options.find((option) => option.id === checked.selection.model);
+ if (model?.orgBlocked || model?.needsCliUpdate) return json(res, 400, { error: "This model is unavailable for thread titles." });
+ patch.threadTitles.model = checked.selection;
+ }
if (patch.profile && ownProfile) {
// The address is the verified claim's; a profile names no other.
const { email: _email, ...own } = patch.profile;
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 38bb408a70..9d144f29c5 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -10,6 +10,7 @@ import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";
import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";
import type { RoutineManager } from "../routines.ts";
import type { SkillReview } from "../skill-review.ts";
+import type { ThreadTitleGate } from "../host/thread-titles.ts";
import { isProjectEmoji, type BotRecord, type Store, type TaskRecord } from "../store.ts";
import { parseSurface } from "../surface.ts";
import type { ThreadStarters } from "../thread-starters.ts";
@@ -28,7 +29,7 @@ type HostedModels = NonNullable<ReturnType<typeof hostedModelPolicy>>;
export interface TaskRouteDeps {
store: Pick<Store,
| "bot" | "bots" | "taskByThread" | "project" | "projectBotForTask" | "patchTask" | "patchProject" | "tasks"
- | "switchTaskModel" | "switchTask" | "retitleTask" | "reorderProjects" | "refreshTaskPermissions" | "messagesTail"
+ | "switchTaskModel" | "switchTask" | "retitleTask" | "taskTitleChanges" | "reorderProjects" | "refreshTaskPermissions" | "messagesTail"
| "messagesFor" | "deleteTasks" | "deleteProject" | "createTask" | "forkTask" | "createProject">;
/** On a Cloud home only the owner changes how a bot asks for approval. */
cloudHome: boolean;
@@ -45,6 +46,7 @@ export interface TaskRouteDeps {
threadStarters: Pick<ThreadStarters, "set">;
phoneSecretSubmissions: Pick<PhoneSecretSubmissionRegistry, "hasBot" | "hasThread">;
titleRegenerations: Pick<Set<string>, "has" | "add" | "delete">;
+ automaticTitles: Pick<ReturnType<typeof import("../host/thread-titles.ts").createAutomaticThreadTitles>, "generating" | "drop">;
directTurnGenerationByThread: ReadonlyMap<string, string>;
actorKey(auth: RequestAuth & { kind: "session" }): string;
cloudOwnerSession(auth: RequestAuth): boolean;
@@ -65,8 +67,8 @@ export interface TaskRouteDeps {
checkedTaskModelSwitch(current: BotRecord, raw: unknown, updateBotDefault: boolean, resetApprovalToAsk: boolean, requireAvailableModel?: boolean):
| { ok: true }
| ({ ok: false; status: number } & ServerErrorBody);
- threadTitleGate(bot: Pick<BotRecord, "modelSelection">): { ok: true; instance: ProviderInstance } | { ok: false; refusal: string };
- generateThreadTitle(provider: ProviderInstance, text: string, source: ThreadTitleSource): Promise<string | null>;
+ threadTitleGate(bot: BotRecord, ownOnly?: boolean): ThreadTitleGate;
+ generateThreadTitle(provider: Pick<ProviderInstance, "generateText">, text: string, source: ThreadTitleSource): Promise<string | null>;
settleDirectFollowup(generation: string | undefined): void;
clearTurnDigestState(threadId: string): void;
revokeInternalCapabilitiesForThread(threadId: string): void;
@@ -81,7 +83,7 @@ export interface TaskRouteDeps {
/** `deleteTasks`: the same deletion for the server's own use (a person leaving a Team Cloud, host/team-member-left.ts). */
export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTasks(botId: string, threadIds: string[]): ReturnType<TaskRouteDeps["store"]["deleteTasks"]> } {
const {
- store, hostedModels, coordinator, handoffs, skillReview, threadStarters, phoneSecretSubmissions, titleRegenerations,
+ store, hostedModels, coordinator, handoffs, skillReview, threadStarters, phoneSecretSubmissions, titleRegenerations, automaticTitles,
directTurnGenerationByThread, actorKey, cloudOwnerSession, cloudThreadRefusal, sharedWorkspaceFullAccessEnabled,
supportsApprovalMode, threadBusy, broadcast, notificationListed, publicBot, wireBot, wireTask, pageSize, messagePage, checkedModelSelection,
checkedTaskModelSwitch, threadTitleGate, generateThreadTitle, settleDirectFollowup, clearTurnDigestState,
@@ -428,17 +430,23 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
if (!current) return json(res, 404, { error: "no such task" });
const notYours = cloudThreadRefusal(auth, m[2]);
if (notYours) return json(res, 403, { error: notYours });
- const gate = threadTitleGate(current);
+ const messages = store.messagesTail(m[2], 200).messages;
+ const gate = threadTitleGate(current, messages.some((message) => message.via === "call"));
if (!gate.ok) return json(res, 409, { error: gate.refusal });
- if (titleRegenerations.has(m[2])) return json(res, 409, { error: "a new title is already being generated for this thread" });
- const excerpt = titleConversationExcerpt(store.messagesTail(m[2], 200).messages);
+ if (titleRegenerations.has(m[2]) || automaticTitles.generating(m[2])) return json(res, 409, { error: "a new title is already being generated for this thread" });
+ const excerpt = titleConversationExcerpt(messages);
if (!excerpt) return json(res, 409, { error: "this thread has no messages to take a title from yet" });
- const startedFrom = store.taskByThread(m[1], m[2])!.title;
+ const started = store.taskByThread(m[1], m[2])!, startedFrom = started.title;
+ const titleChange = store.taskTitleChanges.get(started);
+ automaticTitles.drop(m[2]);
titleRegenerations.add(m[2]);
try {
const title = await generateThreadTitle(gate.instance, excerpt, "conversation");
if (!title) return json(res, 502, { error: "couldn't generate a title — try again, or rename the thread" });
- const task = store.retitleTask(m[1], m[2], startedFrom, title) ?? store.taskByThread(m[1], m[2]);
+ let task = store.taskByThread(m[1], m[2]);
+ if (task === started && store.taskTitleChanges.get(task) === titleChange) {
+ task = store.retitleTask(m[1], m[2], startedFrom, title, true) ?? task;
+ }
if (!task) return json(res, 404, { error: "no such task" });
return json(res, 200, { task: wireTask(task, store.bot(m[1])!.modelSelection) });
} finally {
diff --git a/server/side-jobs.test.ts b/server/side-jobs.test.ts
index e5a09acd6c..bdc8059291 100644
--- a/server/side-jobs.test.ts
+++ b/server/side-jobs.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { DATA_DIR, loadConfig, parseConfigPatch, parseStoredConfig } from "./config.ts";
+import { DATA_DIR, loadConfig, parseConfigPatch, parseStoredConfig, saveConfig } from "./config.ts";
import type { TextGenerationOptions } from "./contracts.ts";
import { ChatHttpError } from "./drivers/openai-chat-refusals.ts";
import { createMemoryUpkeep, NO_TEXT_ENGINE, type UpkeepBot } from "./memory-upkeep.ts";
@@ -80,6 +80,7 @@ function setup(options: { helper?: { instanceId: string; model?: string } | null
bots: new Map<string, SideJobBot>(["claude", "openrouter", "grok", "codex", "pi", "muse"].map((id) => [id, bot(id, id)])),
refused: new Set<string>(),
overBudget: false,
+ cappedBots: new Set<string>(),
booked: [] as Booked[],
logs: [] as string[],
};
@@ -90,8 +91,9 @@ function setup(options: { helper?: { instanceId: string; model?: string } | null
helper: () => state.helper,
...(options.modelAllowed ? { modelAllowed: options.modelAllowed } : {}),
smallModels: options.smallModels ?? { refused: () => new Set(), remember: () => {} },
- assertWithinBudget: () => {
+ assertWithinBudget: (botId) => {
if (state.overBudget) throw new Error("this workspace has reached its monthly spend limit");
+ if (botId && state.cappedBots.has(botId)) throw new Error("this bot has reached its usage cap");
},
book: (row, tokensReported, notificationThreadId) => state.booked.push({ row, tokensReported, notificationThreadId }),
log: (line) => state.logs.push(line),
@@ -100,7 +102,7 @@ function setup(options: { helper?: { instanceId: string; model?: string } | null
return { jobs, state, claude, openrouter, acp, codex };
}
-describe("the helper setting", () => {
+describe("background model settings", () => {
const file = join(DATA_DIR, "config.json");
beforeEach(() => {
mkdirSync(DATA_DIR, { recursive: true });
@@ -154,6 +156,16 @@ describe("the helper setting", () => {
expect(parseStoredConfig({ helper: "claude", language: "en" })).toEqual({ language: "en" });
expect(parseStoredConfig({ helper: { instanceId: 7 }, language: "en" })).toEqual({ language: "en" });
});
+
+ it("merges partial thread-title settings and can explicitly clear the selected model", () => {
+ const model = { instanceId: "openrouter", model: "vendor/title-model" };
+ saveConfig(parseConfigPatch({ threadTitles: { model } }));
+ saveConfig(parseConfigPatch({ threadTitles: { followUp: true } }));
+ expect(loadConfig().threadTitles).toEqual({ model, followUp: true });
+ saveConfig(parseConfigPatch({ threadTitles: { model: null } }));
+ expect(loadConfig().threadTitles).toEqual({ model: null, followUp: true });
+ expect(() => parseConfigPatch({ threadTitles: { model: { ...model, model: "--print" } } })).toThrow();
+ });
});
describe("the setup card's answers", () => {
@@ -209,6 +221,60 @@ describe("the setup card's answers", () => {
});
});
+describe("who writes a thread title", () => {
+ const titleModel = { instanceId: "openrouter", model: "vendor/title-model" };
+
+ it("uses the configured provider and model with usage, without acquiring a second slot", async () => {
+ const slots = createJobSlots(1);
+ const run = vi.spyOn(slots, "run");
+ const { jobs, state, claude, openrouter } = setup({ slots });
+ const writer = jobs.text("thread-title", "claude", { titleModel });
+ const signal = new AbortController().signal;
+ expect(await writer!.generateText("title prompt", { signal, maxOutputTokens: 512 })).toBe("openrouter wrote this");
+ expect(openrouter.calls[0]?.options).toMatchObject({ model: titleModel.model, signal, maxOutputTokens: 512, finalTextOnly: true });
+ expect(state.booked[0]?.row).toMatchObject({ instanceId: "openrouter", model: titleModel.model, threadId: expect.stringMatching(/^thread-title-/) });
+ expect(claude.calls).toEqual([]);
+ expect(run).not.toHaveBeenCalled();
+ state.cappedBots.add("claude");
+ await expect(writer!.generateText("another title")).rejects.toThrow("this bot has reached its usage cap");
+ state.overBudget = true;
+ await expect(writer!.generateText("another title")).rejects.toThrow("monthly spend limit");
+ expect(openrouter.calls).toHaveLength(1);
+ });
+
+ it("keeps restricted titles on the conversation's model and forbids helper fallback", async () => {
+ const { jobs, claude, openrouter } = setup({ helper: titleModel });
+ const modelSelection = { instanceId: "claude", model: "conversation-sonnet" };
+ await jobs.text("thread-title", "claude", { titleModel, ownOnly: true, modelSelection })!.generateText("own title");
+ expect(claude.calls[0]?.options?.model).toBe(modelSelection.model);
+ expect(jobs.text("thread-title", "codex", { titleModel, ownOnly: true })).toBeNull();
+ expect(openrouter.calls).toEqual([]);
+ });
+
+ it("uses the conversation model or the permitted helper's one-off call", async () => {
+ const { jobs, state, claude, codex, openrouter } = setup({ helper: titleModel });
+ const modelSelection = { instanceId: "claude", model: "conversation-sonnet" };
+ await jobs.text("thread-title", "codex", { modelSelection })!.generateText("own title");
+ expect(claude.calls[0]?.options?.model).toBe(modelSelection.model);
+ expect(jobs.text("thread-title", "codex")?.via).toBe("helper");
+ await jobs.text("thread-title", "codex")!.generateText("helper title");
+ expect(openrouter.calls[0]?.options?.model).toBe(titleModel.model);
+ expect(codex.calls).toEqual([]);
+ state.bots.set("codex", { ...bot("codex", "codex"), helperModel: false });
+ expect(jobs.text("thread-title", "codex")).toBeNull();
+ });
+
+ it("keeps unavailable, policy-refused and unassigned selections from using another model", () => {
+ const modelSelection = { instanceId: "claude", model: "company-haiku" };
+ const { jobs, state } = setup({ modelAllowed: ({ model }) => [modelSelection.model, titleModel.model].includes(model) });
+ expect(jobs.text("thread-title", "claude", { modelSelection, titleModel })).toBeTruthy();
+ expect(jobs.text("thread-title", "claude", { modelSelection, titleModel: { instanceId: "codex", model: titleModel.model } })).toBeNull();
+ expect(jobs.text("thread-title", "claude", { modelSelection, titleModel: { ...titleModel, model: "unassigned" } })).toBeNull();
+ state.refused.add("openrouter");
+ expect(jobs.text("thread-title", "claude", { modelSelection, titleModel })).toBeNull();
+ });
+});
+
describe("who writes a small job", () => {
it("is the bot's own engine whenever it can: the helper is never called", async () => {
const { jobs, state, claude, openrouter } = setup({ helper: { instanceId: "openrouter" } });
diff --git a/server/side-jobs.ts b/server/side-jobs.ts
index 054d7faaa5..25ddde2332 100644
--- a/server/side-jobs.ts
+++ b/server/side-jobs.ts
@@ -8,7 +8,7 @@ import type { MemoryModelFailure, MemoryModelOutcome, MemoryModelRun, MemoryMode
import { ChatCompletionError, ChatHttpError } from "./drivers/openai-chat-refusals.ts";
import { openRouterModelUnavailable } from "./drivers/openrouter-free.ts";
import { backgroundTextSlots, type JobSlots } from "./job-slots.ts";
-import type { ProviderAdapter, ProviderInstance, SmallModelFallback, TextGenerationOptions } from "./contracts.ts";
+import type { ModelSelection, ProviderAdapter, ProviderInstance, SmallModelFallback, TextGenerationOptions } from "./contracts.ts";
import { refusesModel } from "./quick-model-fallback.ts";
import type { LightModel, LightModelEngine } from "./suggested-reply/light-model.ts";
import { fastModelFor } from "./turn-route.ts";
@@ -27,7 +27,7 @@ export interface HelperConfig {
}
/** Goes into a CLI's argv: never a leading dash, no space or control character. */
-const HELPER_MODEL_ID = /^[A-Za-z0-9][\x21-\x7e]*$/;
+export const ONE_OFF_MODEL_ID = /^[A-Za-z0-9][\x21-\x7e]*$/;
/** OMB_HELPER_INSTANCE / OMB_HELPER_MODEL win over the file; an empty OMB_HELPER_INSTANCE switches a saved helper off.
* An invalid model switches the helper off rather than writing with a model the person did not name. */
@@ -36,12 +36,12 @@ export function helperSelection(cfg: HelperConfig, env: Record<string, string |
if (!instanceId) return null;
const model = (env.OMB_HELPER_MODEL ?? cfg.helper?.model)?.trim();
if (!model) return { instanceId };
- return HELPER_MODEL_ID.test(model) ? { instanceId, model } : null;
+ return ONE_OFF_MODEL_ID.test(model) ? { instanceId, model } : null;
}
/** "representative": a person's assistant answering a teammate's question for them, which must never get tools. */
/** "suggested-reply": the composer's next-line suggestion, only ever on the bot's own engine's smallest model. */
-export type SideJob = "compaction" | "memory" | "skill-review" | "setup-suggestions" | "representative" | "status-reply" | "skill-burger" | "suggested-reply";
+export type SideJob = "compaction" | "memory" | "skill-review" | "setup-suggestions" | "representative" | "status-reply" | "skill-burger" | "suggested-reply" | "thread-title";
export type SideJobInstance = Pick<ProviderInstance, "instanceId" | "driverKind" | "enabled" | "generateText" | "generateMemoryText" | "models" | "quickModelsUsable" | "openRouter"> & {
adapter: { capabilities: Pick<ProviderAdapter["capabilities"], "agentsMcp"> };
@@ -65,7 +65,7 @@ export interface SideJobText {
/** `waiting`: the call has to wait for a free slot (other bots' background calls); `started`: it starts now, after waiting
* or at once. A call that is never queued calls neither. */
-export type SideJobTextOptions = Pick<TextGenerationOptions, "signal" | "timeoutMs"> & {
+export type SideJobTextOptions = Pick<TextGenerationOptions, "signal" | "timeoutMs" | "maxOutputTokens" | "finalTextOnly"> & {
waiting?(): void;
started?(): void;
onMemoryModel?(result: MemoryModelRun): void;
@@ -80,7 +80,7 @@ export interface SideJobsDeps {
smallModels: { refused(instanceId: string): ReadonlySet<string>; remember(instanceId: string, model: string): void };
/** Hosted workspaces only. */
modelAllowed?: (selection: { instanceId: string; model: string }) => boolean;
- assertWithinBudget: () => void;
+ assertWithinBudget: (botId?: string) => void;
book: (row: Omit<UsageRow, "at" | "costSource">, tokensReported: boolean, notificationThreadId: string) => void;
log?: (line: string) => void;
/** How many background jobs run at once, across bots. */
@@ -89,24 +89,31 @@ export interface SideJobsDeps {
lightModel?: (engine: LightModelEngine, refused: ReadonlySet<string>) => LightModel | null;
}
+interface SideJobContext {
+ instance?: SideJobInstance | null;
+ modelSelection?: SideJobBot["modelSelection"];
+ titleModel?: Pick<ModelSelection, "instanceId" | "model"> | null;
+ ownOnly?: boolean;
+}
+
export interface SideJobs {
- /** Null when nobody can write it and the job keeps its fallback. `at.instance`: the conversation's engine, for the summary. */
- text(job: SideJob, botId: string, at?: { instance?: SideJobInstance }): SideJobText | null;
+ /** Null when nobody can write it. `at.instance` and `at.modelSelection` identify the conversation's engine and model. */
+ text(job: SideJob, botId: string, at?: SideJobContext): SideJobText | null;
}
type TextCall = (prompt: string, options?: TextGenerationOptions) => Promise<string>;
/** Jobs someone is waiting on, and the representative, which must never get tools, run only on a one-off text call:
* generateMemoryText starts a whole agent process. */
-const ONE_OFF_ONLY: ReadonlySet<SideJob> = new Set(["compaction", "setup-suggestions", "representative", "status-reply", "skill-burger"]);
+const ONE_OFF_ONLY: ReadonlySet<SideJob> = new Set(["compaction", "setup-suggestions", "representative", "status-reply", "skill-burger", "thread-title"]);
function ownCall(job: SideJob, instance: SideJobInstance): TextCall | undefined {
const call = ONE_OFF_ONLY.has(job) ? instance.generateText : instance.generateText ?? instance.generateMemoryText;
return call?.bind(instance);
}
-/** A turn or a person is waiting on these, so they start at once. */
-const NEVER_QUEUED: ReadonlySet<SideJob> = new Set(["compaction", "representative", "status-reply"]);
+/** A turn or a person is waiting on these, or the caller already holds a slot. */
+const NEVER_QUEUED: ReadonlySet<SideJob> = new Set(["compaction", "representative", "status-reply", "thread-title"]);
/** A person sees these soon (a new bot's suggestions card): they wait ahead of memory upkeep and skill review. */
const SEEN_SOON: ReadonlySet<SideJob> = new Set(["setup-suggestions", "skill-burger", "suggested-reply"]);
@@ -166,14 +173,16 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
const booked = (job: SideJob, bot: SideJobBot, instance: SideJobInstance, call: TextCall, trigger: UsageTrigger, fixed: () => TextGenerationOptions): SideJobText["generateText"] =>
async (prompt, options) => {
const { checkModel, ...generation } = fixed();
- if (!checkModel) deps.assertWithinBudget();
+ const budgetBot = job === "thread-title" ? bot.id : undefined;
+ if (!checkModel) deps.assertWithinBudget(budgetBot);
const threadId = `${job}-${randomUUID()}`;
return call(prompt, {
...options,
...generation,
+ ...(job === "thread-title" ? { finalTextOnly: true } : {}),
...(checkModel ? { checkModel: (model: string) => {
checkModel(model);
- deps.assertWithinBudget();
+ deps.assertWithinBudget(budgetBot);
} } : {}),
onUsage: (usage) => {
deps.book({
@@ -293,10 +302,25 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
}, { signal: options.signal, interactive: SEEN_SOON.has(job), onWait: waiting }) }
: found;
- function find(job: SideJob, botId: string, at: { instance?: SideJobInstance }): SideJobText | null {
+ function find(job: SideJob, botId: string, at: SideJobContext): SideJobText | null {
const bot = deps.bot(botId);
- const own = at.instance ?? (bot ? deps.instance(bot.modelSelection.instanceId) : null);
- if (!bot || !own || deps.refusal(own)) return null;
+ if (!bot) return null;
+ const selection = (job === "thread-title" ? at.modelSelection : undefined) ?? bot.modelSelection;
+ const own = at.instance ?? deps.instance(selection.instanceId);
+ if (!own || deps.refusal(own)) return null;
+ const ownTitleModel = selection.instanceId === own.instanceId ? selection.model : undefined;
+ if (job === "thread-title") {
+ if (!own.enabled || (deps.modelAllowed && (!ownTitleModel || !deps.modelAllowed({ instanceId: own.instanceId, model: ownTitleModel })))) return null;
+ if (at.titleModel && !at.ownOnly) {
+ const { instanceId, model } = at.titleModel;
+ const target = deps.instance(instanceId);
+ if (!target?.enabled || !target.generateText || deps.refusal(target) || deps.modelAllowed?.(at.titleModel) === false) return null;
+ const option = target.models.options.find(({ id }) => id === model);
+ if (option?.orgBlocked || option?.needsCliUpdate) return null;
+ return { via: "engine", generateText: booked(job, bot, target, target.generateText.bind(target), { kind: "bot", botId: bot.id }, () => ({ model })) };
+ }
+ if (own.driverKind === "claudeAgent" && ownTitleModel && !ONE_OFF_MODEL_ID.test(ownTitleModel)) return null;
+ }
if (job === "suggested-reply") return lightText(bot, own);
const selectedMemory = job === "memory" && bot.memoryModel?.instanceId === own.instanceId ? bot.memoryModel : undefined;
if (selectedMemory && (!own.openRouter || !own.enabled || !own.generateText)) return null;
@@ -318,12 +342,14 @@ export function createSideJobs(deps: SideJobsDeps): SideJobs {
generateText: selectedMemory ? writeMemory(bot, own, call, selectedMemory) : booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({})),
};
}
- return { via: "engine", generateText: booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => ({ fallback: ownFallback(bot, own) })) };
+ return { via: "engine", generateText: booked(job, bot, own, call, { kind: "bot", botId: bot.id }, () => job === "thread-title" ? { model: ownTitleModel } : { fallback: ownFallback(bot, own) }) };
}
- if (!helperModelAllowed(bot)) return null;
+ if (at.ownOnly || !helperModelAllowed(bot)) return null;
const helper = usableHelper();
if (!helper) return null;
- return { via: "helper", generateText: booked(job, bot, helper.instance, helper.call, { kind: "helper", botId: bot.id, job }, () => (helper.model ? { model: helper.model } : {})) };
+ const model = helper.model ?? (job === "thread-title" && deps.modelAllowed ? helper.instance.models.default : undefined);
+ if (job === "thread-title" && deps.modelAllowed && (!model || !deps.modelAllowed({ instanceId: helper.instance.instanceId, model }))) return null;
+ return { via: "helper", generateText: booked(job, bot, helper.instance, helper.call, { kind: "helper", botId: bot.id, job }, () => (model ? { model } : {})) };
}
return {
text: (job, botId, at = {}) => queued(job, find(job, botId, at)),
diff --git a/server/store.ts b/server/store.ts
index f8b33688d9..2fef5c3d5e 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -112,13 +112,13 @@ export function toWireTask(task: TaskRecord, botModel: ModelSelection): WireTask
const ASK_NOW = { approvalMode: "ask" as const, autoApprove: false, alwaysAllow: [] as string[] };
const TASK_PATCH_FIELDS = [
- "title", "projectId", "modelSelection", "approvalMode", "autoApprove", "alwaysAllow",
+ "title", "titleMode", "projectId", "modelSelection", "approvalMode", "autoApprove", "alwaysAllow",
"unread", "heldUnread", "lastReadMessageId", "rewound", "archivedAt", "pinned", "pinnedMessageId", "resumeCursors", "lastInstanceId", "cwd",
"routineRunId", "surface", "surfaceSource", "snoozedUntil", "link", "linkAuto", "appliedCompactionId", "contextFloor", "lastContextModel", "usage", "setupRequest", "botApi", "botApiAsOwner", "outside",
] as const satisfies readonly (keyof TaskRecord)[];
export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number]>>;
-export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null; closed?: { at: number; by: NonNullable<GroupTaskRecord["closedBy"]> } | null };
+export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "titleMode" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null; activity?: "waiting-on-you" | null; closed?: { at: number; by: NonNullable<GroupTaskRecord["closedBy"]> } | null };
export const ACTIVITY_BUSY: ReadonlySet<BotActivity> = new Set(["working", "waiting-on-you", "no-signal"]);
@@ -272,6 +272,7 @@ export class Store {
/** How a new bot is shared; a Team Cloud sets its own rule. */
newBotSharing: NewBotSharingRule = sharedUnlessRestricted;
private listeners = new Set<(change: StoreChange) => void>();
+ readonly taskTitleChanges = new WeakMap<TaskRecord, symbol>();
private registeringInitialSections = true;
/** Where bots, rooms and their threads are saved (server/registry-store.ts). */
private readonly registry: RegistryStore = new JsonRegistry();
@@ -993,7 +994,7 @@ export class Store {
const task = this.groupTaskByThread(groupId, threadId);
if (!group || !task) return null;
this.commitGroupChange(group, "the thread change", () => {
- if (patch.title !== undefined) task.title = patch.title.trim().slice(0, 80) || UNTITLED_TASK;
+ if (patch.title !== undefined) Object.assign(task, { title: patch.title.trim().slice(0, 80) || UNTITLED_TASK, titleMode: patch.titleMode ?? "manual" });
if (patch.pinned) task.pinned = true; else if (patch.pinned === false) delete task.pinned; if (patch.activity) task.activity = patch.activity; else if (patch.activity === null) delete task.activity;
for (const key of ["turnTimeoutMinutes", "archivedAt"] as const) if (patch[key] === null) delete task[key]; else if (patch[key] !== undefined) task[key] = patch[key];
if (patch.closed) Object.assign(task, { closedAt: patch.closed.at, closedBy: structuredClone(patch.closed.by) }); else if (patch.closed === null) { delete task.closedAt; delete task.closedBy; }
@@ -1005,10 +1006,10 @@ export class Store {
titleGroupTaskFromFirstMessage(groupId: string, text: string, threadId?: string): GroupTaskRecord | null {
const group = this.group(groupId), title = titleFromMessage(text);
const task = threadId ? this.groupTaskByThread(groupId, threadId) : this.activeGroupTask(groupId);
- if (!group || !task || task.titleFromFirstMessage || task.title !== UNTITLED_TASK || title === UNTITLED_TASK) return null;
+ if (!group || !task || task.titleMode === "manual" || task.titleFromFirstMessage || task.title !== UNTITLED_TASK || title === UNTITLED_TASK) return null;
this.commitGroupChange(group, "the thread's title", () => {
task.title = title;
- task.titleFromFirstMessage = true;
+ Object.assign(task, { titleFromFirstMessage: true, titleMode: "automatic" });
});
this.emit({ type: "group", groupId });
return task;
@@ -1016,8 +1017,8 @@ export class Store {
retitleGroupTask(groupId: string, threadId: string, machineTitle: string, title: string): GroupTaskRecord | null {
const task = this.groupTaskByThread(groupId, threadId);
- if (!task || task.title !== machineTitle) return null;
- return this.patchGroupTask(groupId, threadId, { title: threadTitleFrom(title) });
+ if (!task || task.titleMode === "manual" || task.title !== machineTitle) return null;
+ return this.patchGroupTask(groupId, threadId, { title: threadTitleFrom(title), titleMode: "automatic" });
}
deleteGroupTask(groupId: string, threadId: string): GroupRecord | null {
@@ -2010,9 +2011,8 @@ export class Store {
if (patch.projectId !== undefined && !this.project(botId, patch.projectId)) return null;
const revocation = keptRevocation(threadApproval(task, bot), threadApproval({ ...task, ...patch }, bot), patch);
this.commitBotChange(bot, "the thread change", () => {
- for (const key of TASK_PATCH_FIELDS) {
- if (Object.prototype.hasOwnProperty.call(patch, key)) Object.assign(task, { [key]: structuredClone(patch[key]) });
- }
+ for (const key of TASK_PATCH_FIELDS) if (Object.hasOwn(patch, key)) Object.assign(task, { [key]: structuredClone(patch[key]) });
+ if (patch.title !== undefined) { task.titleMode = patch.titleMode ?? "manual"; this.taskTitleChanges.set(task, Symbol()); }
if (patch.unread !== undefined && !Object.prototype.hasOwnProperty.call(patch, "heldUnread")) delete task.heldUnread;
if (task.snoozedUntil === 0 && patch.unread === true) task.snoozedUntil = undefined;
if (typeof patch.title === "string") task.title = patch.title.trim().slice(0, 80) || UNTITLED_THREAD;
@@ -2055,11 +2055,11 @@ export class Store {
const approval = resetApprovalToAsk ? structuredClone(ASK_NOW) : {};
const own = sameModelSelection(selection, updateBotDefault ? selection : bot.modelSelection) ? undefined : structuredClone(selection);
const nextTask = persistedPin({ ...task, ...taskPatch, modelSelection: own, ...approval,
- ...(typeof taskPatch.title === "string" ? { title: taskPatch.title.trim().slice(0, 80) || UNTITLED_THREAD } : {}) });
+ ...(typeof taskPatch.title === "string" ? { title: taskPatch.title.trim().slice(0, 80) || UNTITLED_THREAD, titleMode: taskPatch.titleMode ?? "manual" } : {}) });
const others = updateBotDefault ? this.withDefaultModel(bot, selection)! : bot.tasks!;
const nextTasks = bot.tasks!.map((candidate, index) => candidate === task ? nextTask : others[index]!);
const botPatch = updateBotDefault ? { modelSelection: structuredClone(selection), ...approval } : {};
- this.saveBots(this.bots.map((candidate) => candidate === bot ? { ...bot, ...botPatch, tasks: nextTasks } : candidate));
+ this.saveBots(this.bots.map((candidate) => candidate === bot ? { ...bot, ...botPatch, tasks: nextTasks } : candidate)); if (taskPatch.title !== undefined) this.taskTitleChanges.set(task, Symbol());
bot.tasks!.forEach((candidate, index) => Object.assign(candidate, nextTasks[index]));
Object.assign(bot, botPatch);
this.emit({ type: "bot", botId });
@@ -2201,19 +2201,19 @@ export class Store {
titleTaskFromFirstMessage(botId: string, text: string, threadId?: string): TaskRecord | null {
const bot = this.own(botId), title = titleFromMessage(text);
const task = threadId ? this.taskByThread(botId, threadId) : this.activeTask(botId);
- if (!bot || !task || task.titleFromFirstMessage || (task.title !== UNTITLED_TASK && task.title !== UNTITLED_THREAD) || title === UNTITLED_TASK) return null;
+ if (!bot || !task || task.titleMode === "manual" || task.titleFromFirstMessage || (task.title !== UNTITLED_TASK && task.title !== UNTITLED_THREAD) || title === UNTITLED_TASK) return null;
this.commitBotChange(bot, "the thread's title", () => {
task.title = title;
- task.titleFromFirstMessage = true;
+ Object.assign(task, { titleFromFirstMessage: true, titleMode: "automatic" });
}, undefined, true);
this.emit({ type: "bot", botId });
return task;
}
- retitleTask(botId: string, threadId: string, machineTitle: string, title: string): TaskRecord | null {
+ retitleTask(botId: string, threadId: string, machineTitle: string, title: string, explicit = false): TaskRecord | null {
const task = this.taskByThread(botId, threadId);
- if (!task || task.title !== machineTitle) return null;
- return this.renameTask(botId, threadId, threadTitleFrom(title));
+ if (!task || task.title !== machineTitle || (!explicit && task.titleMode === "manual")) return null;
+ return this.patchTask(botId, threadId, { title: threadTitleFrom(title), titleMode: explicit ? "manual" : "automatic" });
}
deleteTask(botId: string, threadId: string): BotRecord | null {
diff --git a/server/tasks.test.ts b/server/tasks.test.ts
index 72e4930198..c2610b4503 100644
--- a/server/tasks.test.ts
+++ b/server/tasks.test.ts
@@ -155,7 +155,11 @@ describe("tasks", () => {
const bot = store.createBot();
const task = store.createTask(bot.id)!;
store.renameTask(bot.id, task.threadId, "Payroll audit");
- expect(store.retitleTask(bot.id, task.threadId, "Payroll audit", "Quarterly payroll export")).toMatchObject({ title: "Quarterly payroll export" });
+ expect(store.retitleTask(bot.id, task.threadId, "Payroll audit", "Automatic rename")).toBeNull();
+ expect(store.retitleTask(bot.id, task.threadId, "Payroll audit", "Quarterly payroll export", true)).toMatchObject({ title: "Quarterly payroll export", titleMode: "manual" });
+ const startedFrom = store.taskTitleChanges.get(task);
+ store.renameTask(bot.id, task.threadId, "Quarterly payroll export");
+ expect(store.taskTitleChanges.get(task)).not.toBe(startedFrom);
store.renameTask(bot.id, task.threadId, "Export checks");
expect(store.retitleTask(bot.id, task.threadId, "Quarterly payroll export", "Payroll export review")).toBeNull();
expect(store.taskByThread(bot.id, task.threadId)!.title).toBe("Export checks");
diff --git a/server/team-backup.test.ts b/server/team-backup.test.ts
index 039aee5f61..e3d3e3b9c0 100644
--- a/server/team-backup.test.ts
+++ b/server/team-backup.test.ts
@@ -410,12 +410,16 @@ describe("additive portable team backups", () => {
const restoredBot = result.bots.find((bot) => bot.name === "Mira 2")!;
const restored = restoredBot.tasks!.find((task) => task.title === "Audit the payroll export")!;
expect(restored.titleFromFirstMessage).toBe(true);
+ expect(restored.titleMode).toBe("automatic");
store.renameTask(restoredBot.id, restored.threadId, UNTITLED_TASK);
+ expect(restored.titleMode).toBe("manual");
expect(store.titleTaskFromFirstMessage(restoredBot.id, "A later message", restored.threadId)).toBeNull();
const restoredGroup = result.groups[0];
const restoredChannel = restoredGroup.tasks!.find((task) => task.title === "Plan the launch review")!;
expect(restoredChannel.titleFromFirstMessage).toBe(true);
+ expect(restoredChannel.titleMode).toBe("automatic");
store.patchGroupTask(restoredGroup.id, restoredChannel.threadId, { title: UNTITLED_TASK });
+ expect(restoredChannel.titleMode).toBe("manual");
expect(store.titleGroupTaskFromFirstMessage(restoredGroup.id, "A later message", restoredChannel.threadId)).toBeNull();
expect(restoredBot.tasks!.find((task) => task.title === "First conversation")).not.toHaveProperty("titleFromFirstMessage");
});
diff --git a/server/team-backup.ts b/server/team-backup.ts
index a68f45e479..845053cf3c 100644
--- a/server/team-backup.ts
+++ b/server/team-backup.ts
@@ -60,6 +60,7 @@ export function createTeamBackup(store: Store, routines: Routine[], name: string
return tasks.filter((task) => shown(task.threadId)).map((task) => ({
key: task.threadId, title: task.title, createdAt: task.createdAt,
titleFromFirstMessage: "titleFromFirstMessage" in task && task.titleFromFirstMessage || undefined,
+ titleMode: "titleMode" in task ? task.titleMode : undefined,
outside: "outside" in task && task.outside || undefined,
openedBy: "openedBy" in task && task.openedBy
? { botId: task.openedBy.botId, name: task.openedBy.name, at: task.openedBy.at,
@@ -204,7 +205,7 @@ export function importTeamBackup(store: Store, routines: RoutineManager, input:
const record: TaskRecord = {
threadId: i === 0 ? bot.threadId : newId(), title: task.title, createdAt: task.createdAt, resumeCursors: {},
activity: "idle" as const, busy: false, unread: false,
- ...(task.titleFromFirstMessage ? { titleFromFirstMessage: true } : {}), ...(task.outside ? { outside: true } : {}),
+ ...(task.titleFromFirstMessage ? { titleFromFirstMessage: true } : {}), ...(task.titleMode ? { titleMode: task.titleMode } : {}), ...(task.outside ? { outside: true } : {}),
};
const opener = task.openedBy && botIds.get(task.openedBy.botId);
if (task.openedBy && opener) record.openedBy = { botId: opener, name: task.openedBy.name, at: task.openedBy.at, ...(task.openedBy.kind ? { kind: task.openedBy.kind } : {}) };
@@ -247,7 +248,7 @@ export function importTeamBackup(store: Store, routines: RoutineManager, input:
threadId: threads[i], title: task.title, createdAt: task.createdAt,
updatedAt: task.messages.reduce((max, message) => Math.max(max, message.at), task.createdAt),
...(task.pinned === true ? { pinned: true as const } : {}),
- ...(task.titleFromFirstMessage ? { titleFromFirstMessage: true } : {}),
+ ...(task.titleFromFirstMessage ? { titleFromFirstMessage: true } : {}), ...(task.titleMode ? { titleMode: task.titleMode } : {}),
...(task.turnTimeoutMinutes != null ? { turnTimeoutMinutes: task.turnTimeoutMinutes } : {}),
}));
store.switchGroupTask(group.id, threads[source.tasks.findIndex((task) => task.key === source.activeTask)]);
diff --git a/server/thread-title-auto.e2e.test.ts b/server/thread-title-auto.e2e.test.ts
new file mode 100644
index 0000000000..febb748dd0
--- /dev/null
+++ b/server/thread-title-auto.e2e.test.ts
@@ -0,0 +1,30 @@
+import { mkdtempSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+
+it("names a real fixture conversation from both its request and reply", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-title-e2e-"));
+ const title = join(dir, "title.txt"), dump = join(dir, "title-dump.json");
+ writeFileSync(title, "Payroll | export fix");
+ const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_TEXT_FILE: title, FAKE_CLAUDE_TEXT_DUMP: dump });
+ const control = (...args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
+ try {
+ const { bot } = await control("new-bot", "--name", "Title fixture");
+ await control("send", "--bot", bot.id, "--text", "Fix payroll export");
+ expect((await control("wait", "--bot", bot.id, "--timeout", "30")).status).toBe("settled");
+ await expect.poll(async () => {
+ const result = await control("bots");
+ return result.bots.find((candidate: any) => candidate.id === bot.id)?.tasks.find((task: any) => task.taskId === bot.activeTaskId)?.title;
+ }, { timeout: 15_000 }).toBe("Payroll | export fix");
+ const { prompt } = JSON.parse(readFileSync(dump, "utf8"));
+ expect(prompt).toContain("User: Fix payroll export");
+ expect(prompt).toContain("Bot:");
+ } finally {
+ await fixture.close();
+ rmSync(title, { force: true });
+ rmSync(dump, { force: true });
+ rmdirSync(dir);
+ }
+}, 120_000);
diff --git a/server/thread-title-generate.test.ts b/server/thread-title-generate.test.ts
index a3021a5bc5..1f95da7e3c 100644
--- a/server/thread-title-generate.test.ts
+++ b/server/thread-title-generate.test.ts
@@ -7,6 +7,31 @@ const titleWarnings = (spy: { mock: { calls: unknown[][] } }): string[] =>
spy.mock.calls.map(([line]) => String(line)).filter((line) => line.startsWith("title generation:"));
describe("generateThreadTitle deadlines", () => {
+ it("times out while waiting for a slot and never calls the provider after expiry", async () => {
+ vi.useFakeTimers();
+ const warnings = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const slots = createJobSlots(1);
+ let free!: () => void;
+ const busy = slots.run(() => new Promise<void>((resolve) => { free = resolve; }));
+ await vi.advanceTimersByTimeAsync(0);
+ const provider = { generateText: vi.fn(async () => "Title") };
+ const result = generateThreadTitle(provider, "request", "first-message", slots);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(await result).toBeNull();
+ expect(slots.waiting).toBe(0);
+ free();
+ await busy;
+ expect(provider.generateText).not.toHaveBeenCalled();
+ } finally {
+ warnings.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps the current title on a KEEP reply", async () => {
+ expect(await generateThreadTitle({ generateText: async () => "KEEP" }, "request", "follow-up", createJobSlots(1))).toBeNull();
+ });
it("keeps an explicit regeneration alive at 10000 ms and returns a title that arrives at 12000 ms", async () => {
vi.useFakeTimers();
const warnings = vi.spyOn(console, "warn").mockImplementation(() => {});
@@ -63,7 +88,7 @@ describe("generateThreadTitle deadlines", () => {
}
});
- it.each(["first-message", "call"] as const)("answers null after 10000 ms for %s and holds the slot until the engine call ends", async (source) => {
+ it.each([["first-message", 30_000], ["call", 10_000]] as const)("bounds %s at %i ms and holds the slot until the call ends", async (source, timeoutMs) => {
vi.useFakeTimers();
const warnings = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
@@ -75,15 +100,15 @@ describe("generateThreadTitle deadlines", () => {
return new Promise<string>((resolve) => { end = resolve; });
} };
const title = generateThreadTitle(provider, "plan the trip", source, slots);
- await vi.advanceTimersByTimeAsync(10_000);
+ await vi.advanceTimersByTimeAsync(timeoutMs);
expect(await title).toBeNull();
expect(aborted).toBe(true);
expect(slots.running).toBe(1);
- expect(titleWarnings(warnings)).toEqual([]);
+ expect(titleWarnings(warnings)).toEqual(source === "call" ? [] : ["title generation: timeout budgetMs=30000"]);
end("Trip plan");
await vi.advanceTimersByTimeAsync(0);
expect(slots.running).toBe(0);
- expect(titleWarnings(warnings)).toEqual([]);
+ expect(titleWarnings(warnings)).toEqual(source === "call" ? [] : ["title generation: timeout budgetMs=30000"]);
} finally {
warnings.mockRestore();
vi.useRealTimers();
diff --git a/server/thread-title-generate.ts b/server/thread-title-generate.ts
index fc0c88f8d6..9362c06e71 100644
--- a/server/thread-title-generate.ts
+++ b/server/thread-title-generate.ts
@@ -1,46 +1,38 @@
+import type { TextGenerationOptions } from "./contracts.ts";
import { backgroundTextSlots, type JobSlots } from "./job-slots.ts";
import { titleFromLlm } from "./store.ts";
import { threadTitlePrompt, type ThreadTitleSource } from "./thread-title.ts";
-export const THREAD_TITLE_TIMEOUT_MS = 10_000;
-const THREAD_TITLE_REGENERATE_TIMEOUT_MS = 30_000;
+export const THREAD_TITLE_TIMEOUT_MS = 30_000;
-function warnRegeneratedTitle(reason: "timeout" | "provider-error" | "rejected-output", detail?: string): void {
- console.warn(detail === undefined ? `title generation: ${reason}` : `title generation: ${reason} ${detail}`);
-}
-
-/** A person sees the title soon, so the call waits ahead of background upkeep for a free slot. Past its deadline the
- * answer is null at once, but the slot is held until the engine call has really ended: its process still counts until then. */
+/** The slot is held until the provider settles, even if the caller has already timed out. */
export async function generateThreadTitle(
- provider: { generateText?: (prompt: string, options?: { signal?: AbortSignal }) => Promise<string> },
+ provider: { generateText?: (prompt: string, options?: TextGenerationOptions) => Promise<string> },
text: string,
source: ThreadTitleSource = "first-message",
slots: JobSlots = backgroundTextSlots,
): Promise<string | null> {
const prompt = threadTitlePrompt(text, source);
- const regenerate = source === "conversation";
- const timeoutMs = regenerate ? THREAD_TITLE_REGENERATE_TIMEOUT_MS : THREAD_TITLE_TIMEOUT_MS;
+ const timeoutMs = source === "call" ? 10_000 : THREAD_TITLE_TIMEOUT_MS;
+ const expiry = new AbortController();
+ const warn = (reason: string) => { if (source !== "call") console.warn(`title generation: ${reason}`); };
return new Promise<string | null>((answer) => {
+ const timer = setTimeout(() => {
+ warn(`timeout budgetMs=${timeoutMs}`);
+ expiry.abort();
+ answer(null);
+ }, timeoutMs);
void slots.run(async () => {
- const expiry = new AbortController();
- const timer = setTimeout(() => {
- if (regenerate) warnRegeneratedTitle("timeout", `budgetMs=${timeoutMs}`);
- expiry.abort();
- answer(null);
- }, timeoutMs);
- try {
- const reply = await provider.generateText!(prompt, { signal: expiry.signal });
- if (expiry.signal.aborted) return;
- const title = titleFromLlm(reply);
- if (title === null && regenerate) warnRegeneratedTitle("rejected-output");
- answer(title);
- } catch (error) {
- if (expiry.signal.aborted) return;
- if (regenerate) warnRegeneratedTitle("provider-error", error instanceof Error ? error.name : "error");
- answer(null);
- } finally {
- clearTimeout(timer);
- }
- }, { interactive: true }).catch(() => answer(null));
+ expiry.signal.throwIfAborted();
+ const reply = await provider.generateText!(prompt, source === "call" ? { signal: expiry.signal }
+ : { signal: expiry.signal, timeoutMs, maxOutputTokens: 512, finalTextOnly: true });
+ if (expiry.signal.aborted) return;
+ const title = titleFromLlm(reply);
+ if (title === null) warn("rejected-output");
+ answer(source === "follow-up" && title?.toUpperCase() === "KEEP" ? null : title);
+ }, { interactive: true, signal: expiry.signal }).catch((error: unknown) => {
+ if (!expiry.signal.aborted) warn(`provider-error ${error instanceof Error ? error.name : "error"}`);
+ answer(null);
+ }).finally(() => clearTimeout(timer));
});
}
diff --git a/server/thread-title.test.ts b/server/thread-title.test.ts
index 4d9e5e63e5..45142a1179 100644
--- a/server/thread-title.test.ts
+++ b/server/thread-title.test.ts
@@ -8,7 +8,7 @@ import { AUTHORITY, botWho, fromNote, fromNoteWith, routineWho } from "./provena
import { generateThreadTitle, THREAD_TITLE_TIMEOUT_MS } from "./thread-title-generate.ts";
describe("a generated title and the background slots", () => {
- it("answers null after 10 s, but keeps its slot until the engine call has really ended", async () => {
+ it("answers null at the deadline and keeps its slot until the engine call ends", async () => {
vi.useFakeTimers();
try {
const slots = createJobSlots(1);
@@ -110,7 +110,7 @@ describe("threadTitlePrompt", () => {
const prompt = threadTitlePrompt(`User: fix the login\n${"x".repeat(5_000)}`, "conversation");
expect(prompt).toContain("what it is about now");
expect(prompt).toContain("Conversation:\nUser: fix the login");
- expect(prompt.length).toBeLessThan(TITLE_INPUT_MAX_CHARS + 300);
+ expect(prompt.length).toBeLessThan(TITLE_INPUT_MAX_CHARS + 400);
});
it.each<[ThreadTitleSource, string]>([
diff --git a/server/thread-title.ts b/server/thread-title.ts
index ba08a3c0bc..c9886ab8a7 100644
--- a/server/thread-title.ts
+++ b/server/thread-title.ts
@@ -34,10 +34,12 @@ const EXCERPT_MAX_MESSAGES = 12;
const EXCERPT_LINE_MAX_CHARS = 300;
const ATTACHMENT_TAG = /<attached-(?:image|file)\b[^>]*\/>/g;
-export type ThreadTitleSource = "first-message" | "conversation" | "call";
+export type ThreadTitleSource = "first-message" | "first-reply" | "follow-up" | "conversation" | "call";
const TITLE_PROMPT: Record<ThreadTitleSource, { ask: string; label: string }> = {
"first-message": { ask: "Name the conversation that begins with the message below.", label: "Message:" },
+ "first-reply": { ask: "Name the conversation using the person's request and the bot's reply below.", label: "Conversation:" },
+ "follow-up": { ask: "Name the conversation below if its topic has changed. Reply KEEP if the current title still fits.", label: "Conversation:" },
conversation: { ask: "Name the conversation below by what it is about now.", label: "Conversation:" },
call: { ask: "Name the voice call below by what was asked on it.", label: "Requests:" },
};
@@ -47,6 +49,7 @@ export function threadTitlePrompt(text: string, source: ThreadTitleSource = "fir
return [
ask,
"Reply with only a short title in the same language as the user's request. Use a concise phrase of at most 48 characters, in plain text, with no quotes or trailing period.",
+ ...(source === "call" ? [] : ["Use project | concrete task if a project or module is clear. Avoid filler such as help, question, chat, 问题, or 会话."]),
label,
text.trim().slice(0, TITLE_INPUT_MAX_CHARS),
].join("\n");
@@ -74,6 +77,14 @@ function excerptLines(candidates: Iterable<ExcerptCandidate>, maxLines = Infinit
return lines;
}
+export function titleTurnExcerpt(request: string, reply?: string, currentTitle?: string): string {
+ return excerptLines([
+ ...(currentTitle ? [{ label: "Current title", text: currentTitle }] : []),
+ { label: "User", text: request },
+ ...(reply ? [{ label: "Bot", text: reply }] : []),
+ ]).join("\n");
+}
+
export function titleConversationExcerpt(messages: readonly Message[]): string {
function* newestFirst(): Generator<ExcerptCandidate> {
for (let index = messages.length - 1; index >= 0; index--) {
diff --git a/server/workspace-backup-policy.test.ts b/server/workspace-backup-policy.test.ts
index d01eebb528..e47beae6cc 100644
--- a/server/workspace-backup-policy.test.ts
+++ b/server/workspace-backup-policy.test.ts
@@ -33,6 +33,17 @@ describe("workspace backup data boundary", () => {
expect(restoredWorkspaceConfig(portable, { helper: { instanceId: "openrouter" } }).helper).toEqual({ instanceId: "openrouter" });
});
+ it("carries the follow-up title preference and keeps the destination's provider selection", () => {
+ const source = { instanceId: "anthropic", model: "source-sonnet" };
+ const destination = { instanceId: "anthropic", model: "destination-sonnet" };
+ const portable = portableWorkspaceConfig({ threadTitles: { model: source, followUp: true } });
+ expect(portable).toEqual({ threadTitles: { followUp: true } });
+ expect(restoredWorkspaceConfig(portable, {}).threadTitles).toEqual({ followUp: true });
+ expect(restoredWorkspaceConfig(portable, { threadTitles: { model: destination, followUp: false } }).threadTitles)
+ .toEqual({ model: destination, followUp: true });
+ expect(restoredWorkspaceConfig({}, { threadTitles: { followUp: true } })).not.toHaveProperty("threadTitles");
+ });
+
it("keeps the destination's own computer-sharing switch, whatever the backup says", () => {
const portable = portableWorkspaceConfig({ features: { browser: true, sharedComputers: true } });
expect(restoredWorkspaceConfig(portable, { features: { sharedComputers: false } }).features).toEqual({ browser: true, sharedComputers: false });
diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.ts
index 94a3cd2e13..137351b1b4 100644
--- a/server/workspace-backup-policy.ts
+++ b/server/workspace-backup-policy.ts
@@ -12,7 +12,10 @@ const PORTABLE_CONFIG_KEYS = [
export function portableWorkspaceConfig(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid workspace configuration in backup.");
const config = parseStoredConfig(value as Parameters<typeof parseStoredConfig>[0]);
- return Object.fromEntries(PORTABLE_CONFIG_KEYS.filter((key) => config[key] !== undefined).map((key) => [key, config[key]]));
+ return {
+ ...Object.fromEntries(PORTABLE_CONFIG_KEYS.filter((key) => config[key] !== undefined).map((key) => [key, config[key]])),
+ ...(config.threadTitles?.followUp === undefined ? {} : { threadTitles: { followUp: config.threadTitles.followUp } }),
+ };
}
// Computer sharing opens routes and a desktop connector here: a restore never turns it on or off.
@@ -22,7 +25,10 @@ export function restoredWorkspaceConfig(portable: unknown, destination: unknown)
if (!destination || typeof destination !== "object" || Array.isArray(destination)) throw new Error("Invalid destination workspace configuration; connections were not changed.");
const merged = { ...destination } as Record<string, unknown>;
for (const key of PORTABLE_CONFIG_KEYS) delete merged[key];
+ delete merged.threadTitles;
const restored = { ...merged, ...portableWorkspaceConfig(portable) };
+ const model = (destination as { threadTitles?: { model?: unknown } }).threadTitles?.model;
+ if (model !== undefined) restored.threadTitles = { ...(restored.threadTitles as object | undefined), model };
const own = (destination as { features?: Record<string, unknown> }).features ?? {};
const features: Record<string, unknown> = { ...(restored.features as Record<string, unknown> | undefined) };
for (const key of DESTINATION_FEATURES) {
diff --git a/shared/team-backup.ts b/shared/team-backup.ts
index 46a5a5ee38..d5978f243e 100644
--- a/shared/team-backup.ts
+++ b/shared/team-backup.ts
@@ -47,6 +47,7 @@ const task = z.object({
// Travels only when the first message already named this task, so a
// restore cannot re-arm one generated title on a row that used it.
titleFromFirstMessage: z.literal(true).optional(),
+ titleMode: z.enum(["automatic", "manual"]).optional(),
/** Work from outside reached this conversation: it stays confined after a restore. */
outside: z.literal(true).optional(),
openedBy: z.object({ botId: key, name, at: timestamp, kind: z.enum(["pair", "work"]).optional() }).optional(),
diff --git a/src/components/settings/pages/FeaturesPage.test.ts b/src/components/settings/pages/FeaturesPage.test.ts
new file mode 100644
index 0000000000..e02cbe11da
--- /dev/null
+++ b/src/components/settings/pages/FeaturesPage.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({
+ state: {
+ config: { features: {}, threadTitles: { model: null as { instanceId: string; model: string } | null, followUp: false, instances: ["claude"] } },
+ instances: [{ instanceId: "claude", displayName: "Claude", snapshot: { state: "available", authenticated: true },
+ models: { options: [{ id: "sonnet", label: "Sonnet" }] } }],
+ },
+ api: vi.fn(), dispatch: vi.fn(),
+}));
+vi.mock("@/state/store", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/state/store")>()), api: fixture.api }));
+vi.mock("@/state/store-select", () => ({ useStoreDispatch: () => fixture.dispatch, useStoreSelector: (select: (state: typeof fixture.state) => unknown) => select(fixture.state) }));
+const { FeaturesPage } = await import("./FeaturesPage");
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ fixture.api.mockReset(); fixture.dispatch.mockReset();
+ fixture.state.config.threadTitles = { model: null, followUp: false, instances: ["claude"] };
+ host = document.createElement("div"); document.body.append(host); root = createRoot(host);
+});
+afterEach(() => { act(() => root.unmount()); host.remove(); });
+
+it("saves the chosen title model and the follow-up switch independently", async () => {
+ fixture.api.mockResolvedValue(fixture.state.config);
+ await act(async () => root.render(createElement(FeaturesPage)));
+ const select = host.querySelector("select")!;
+ expect([...select.options].map((option) => option.textContent)).toEqual(expect.arrayContaining(["Automatic", "Claude · Sonnet"]));
+ await act(async () => { select.value = JSON.stringify(["claude", "sonnet"]); select.dispatchEvent(new Event("change", { bubbles: true })); });
+ expect(fixture.api).toHaveBeenLastCalledWith("/api/config", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ threadTitles: { model: { instanceId: "claude", model: "sonnet" } } }) }));
+ await act(async () => { (host.querySelector('[role="switch"]') as HTMLButtonElement).click(); });
+ expect(fixture.api).toHaveBeenLastCalledWith("/api/config", expect.objectContaining({ method: "PATCH", body: JSON.stringify({ threadTitles: { followUp: true } }) }));
+});
+
+it("reports a failed setting change", async () => {
+ fixture.api.mockRejectedValue(new Error("offline"));
+ await act(async () => root.render(createElement(FeaturesPage)));
+ await act(async () => { (host.querySelector('[role="switch"]') as HTMLButtonElement).click(); });
+ expect(host.querySelector('[role="alert"]')?.textContent).toBeTruthy();
+});
diff --git a/src/components/settings/pages/FeaturesPage.tsx b/src/components/settings/pages/FeaturesPage.tsx
index 26e73f370f..582b70d1c2 100644
--- a/src/components/settings/pages/FeaturesPage.tsx
+++ b/src/components/settings/pages/FeaturesPage.tsx
@@ -1,9 +1,10 @@
-import { useState } from "react";
+import { useId, useState } from "react";
import type { LocaleKey } from "@/locales";
import { t } from "@/lib/i18n";
import { useFeature, type Feature } from "@/lib/use-feature";
import { api, type ConfigStatus } from "@/state/store";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { Select } from "../../Select";
import { SettingRow, SettingsGroup, SettingsRows, Switch } from "../../SettingsPrimitives";
const COPY: Record<Feature, { title: LocaleKey; line: LocaleKey }> = {
@@ -42,6 +43,90 @@ function FeatureRow({ name }: { name: Feature }) {
);
}
+type ThreadTitles = NonNullable<ConfigStatus["threadTitles"]>;
+type TitleModel = NonNullable<ThreadTitles["model"]>;
+type ThreadTitlesPatch = Pick<ThreadTitles, "model"> | Pick<ThreadTitles, "followUp">;
+
+function titleModelKey({ instanceId, model }: TitleModel) {
+ return JSON.stringify([instanceId, model]);
+}
+
+function ThreadTitleRows() {
+ const titles = useStoreSelector((state) => state.config?.threadTitles);
+ const instances = useStoreSelector((state) => state.instances);
+ const dispatch = useStoreDispatch();
+ const id = useId();
+ const [feedback, setFeedback] = useState<{ field: "model" | "followUp"; saving: boolean } | null>(null);
+ if (!titles) return null;
+
+ const saving = feedback?.saving === true;
+ const choices = instances
+ .filter((instance) => titles.instances.includes(instance.instanceId) && instance.snapshot.state === "available" && !instance.policy)
+ .flatMap((instance) => instance.models.options
+ .filter((model) => !model.orgBlocked && !model.needsCliUpdate && (instance.snapshot.authenticated !== false || model.custom))
+ .map((model) => {
+ const selection = { instanceId: instance.instanceId, model: model.id };
+ return {
+ key: titleModelKey(selection),
+ label: t("settings.features.titleModelChoice", { provider: instance.displayName, model: model.label }),
+ selection,
+ };
+ }));
+ const selected = titles.model ? titleModelKey(titles.model) : "";
+ const currentChoice = choices.find((choice) => choice.key === selected);
+ const unavailable = titles.model && !currentChoice
+ ? t("settings.features.titleModelUnavailable", { model: titles.model.model })
+ : undefined;
+ const automatic = t("settings.features.titleModelAutomatic");
+ const modelLabel = t("settings.features.titleModel");
+ const followUpLabel = t("settings.features.titleFollowUp");
+ const noChoices = !titles.model && choices.length === 0;
+
+ const save = async (threadTitles: ThreadTitlesPatch) => {
+ if (saving) return;
+ const field = "model" in threadTitles ? "model" : "followUp";
+ setFeedback({ field, saving: true });
+ try {
+ const config = await api<ConfigStatus>("/api/config", { method: "PATCH", body: JSON.stringify({ threadTitles }) });
+ dispatch({ type: "configStatus", config });
+ setFeedback(null);
+ } catch {
+ setFeedback({ field, saving: false });
+ }
+ };
+ const status = (field: "model" | "followUp") => {
+ if (feedback?.field !== field) return undefined;
+ return saving ? <span role="status">{t("settings.threads.saving")}</span>
+ : <span role="alert" className="text-danger">{t("settings.features.error")}</span>;
+ };
+
+ return (
+ <>
+ <SettingRow title={modelLabel} message={status("model")}
+ subtitle={noChoices ? <span id={`${id}-model`}>{t("settings.features.titleModelConnect")}</span> : undefined}>
+ <Select aria-label={modelLabel} aria-describedby={noChoices ? `${id}-model` : undefined}
+ title={currentChoice?.label ?? unavailable ?? automatic} value={selected} disabled={saving || noChoices}
+ onChange={(event) => {
+ const key = event.target.value;
+ if (key === "") void save({ model: null });
+ else {
+ const choice = choices.find((option) => option.key === key);
+ if (choice) void save({ model: choice.selection });
+ }
+ }}>
+ <option value="">{automatic}</option>
+ {unavailable && <option value={selected} disabled>{unavailable}</option>}
+ {choices.map((choice) => <option key={choice.key} value={choice.key}>{choice.label}</option>)}
+ </Select>
+ </SettingRow>
+ <SettingRow title={followUpLabel} subtitle={<span id={`${id}-follow-up`}>{t("settings.features.titleFollowUpLine")}</span>} message={status("followUp")}>
+ <Switch checked={titles.followUp} aria-label={followUpLabel} aria-describedby={`${id}-follow-up`}
+ disabled={saving} onClick={() => void save({ followUp: !titles.followUp })} />
+ </SettingRow>
+ </>
+ );
+}
+
export function FeaturesPage() {
return (
<SettingsGroup block="features">
@@ -49,6 +134,7 @@ export function FeaturesPage() {
<FeatureRow name="skillBurger" />
<FeatureRow name="threadTabs" />
<FeatureRow name="suggestedReplies" />
+ <ThreadTitleRows />
</SettingsRows>
</SettingsGroup>
);
diff --git a/src/lib/config-status-frame.ts b/src/lib/config-status-frame.ts
index a5d88e9f5b..63ce34279d 100644
--- a/src/lib/config-status-frame.ts
+++ b/src/lib/config-status-frame.ts
@@ -3,7 +3,7 @@ import type { ConfigStatus } from "@/state/config-status";
// A setting left out here is wiped from state.config whenever a config frame lands.
export type ConfigStatusFrame = Pick<
ConfigStatus,
- "awakeLimit" | "pausedBots" | "pausedByPerson" | "heldBots" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "xResearch" | "treg" | "postiz" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "everyBotRules" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team" | "workspaceBanner" | "toolGroups"
+ "awakeLimit" | "pausedBots" | "pausedByPerson" | "heldBots" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "modelgo" | "meta" | "deepseek" | "xResearch" | "treg" | "postiz" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "threadTitles" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "everyBotRules" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team" | "workspaceBanner" | "toolGroups"
>;
/** What the server says about the place itself. Its frames carry them as GET /api/config does, one left out meaning
@@ -37,6 +37,7 @@ export function configStatusFromFrame(frame: ConfigStatusFrame, held?: ConfigSta
rooms: frame.rooms,
mcp: frame.mcp,
threads: frame.threads,
+ threadTitles: frame.threadTitles ?? held?.threadTitles,
automaticRecovery: frame.automaticRecovery,
cacheKeepWarm: frame.cacheKeepWarm,
localVm: frame.localVm,
diff --git a/src/locales/en.json b/src/locales/en.json
index cf38252006..fd07417c7d 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -12196,6 +12196,13 @@
"settings.features.threadTabsLine": "Show a bot's threads as tabs above the chat",
"settings.features.suggestedReplies": "Suggested replies",
"settings.features.suggestedRepliesLine": "After a bot replies, suggest what you might say next. The bot's own AI writes it with its smallest model, which uses a little of your plan or API credit.",
+ "settings.features.titleModel": "Thread title model",
+ "settings.features.titleModelAutomatic": "Automatic",
+ "settings.features.titleModelChoice": "{provider} · {model}",
+ "settings.features.titleModelUnavailable": "{model} (unavailable)",
+ "settings.features.titleModelConnect": "Connect a compatible AI to choose a title model.",
+ "settings.features.titleFollowUp": "Update thread titles",
+ "settings.features.titleFollowUpLine": "Refresh automatic titles when a conversation changes direction. Titles you set stay as they are.",
"composer.placeholder.newThread": "Start a thread in {name}",
"room.feed.aria": "Threads in {name}",
"room.feed.replyOne": "1 reply",
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index d2375d98f5..efbc842849 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -80,6 +80,7 @@ export interface ConfigStatus {
/** The server cannot read its saved routines, so none runs until it can. */
routinesUnreadable?: true;
threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number };
+ threadTitles?: { model: Pick<ModelSelection, "instanceId" | "model"> | null; followUp: boolean; instances: string[] };
automaticRecovery?: { enabled: boolean; backup?: ModelSelection };
/** Prompt-cache keep-warm for idle Claude threads. Absent from older servers. */
cacheKeepWarm?: { enabled: boolean; windowMinutes: number };