TypeScript
fix(clients): image threads use readable titles (#19822)
Alex Southwellb20f55248df3
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex 3908d7ad923..39f412684ff 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -816,6 +816,7 @@ function ThreadRouteContent(projectId: selectedThread.projectId,projectCwd: selectedThreadProject.workspaceRoot,text: setupMessage.text,+ titleText: selectedThread.title,...(setupMessage.context ? { context: setupMessage.context } : {}),uploadedAttachments: setupMessage.attachments,modelSelection: selectedThread.modelSelection,diff --git a/apps/mobile/src/lib/projectThreadStartTurn.test.ts b/apps/mobile/src/lib/projectThreadStartTurn.test.tsindex f67a4649fac..c71e3f7f4f8 100644--- a/apps/mobile/src/lib/projectThreadStartTurn.test.ts+++ b/apps/mobile/src/lib/projectThreadStartTurn.test.ts@@ -8,35 +8,62 @@ import {import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";import { describe, expect, it } from "vite-plus/test";+import { serializeComposerMessageForServer } from "./composerContext";+import {buildProjectThreadStartTurnInput,deriveThreadTitleFromPrompt,+ type ProjectThreadStartTurnSpec,} from "./projectThreadStartTurn";describe("project thread title", () => {+ it("normalizes draft and queued titles while keeping the mobile length limit", () => {+ expect(+ deriveThreadTitleFromPrompt(+ " Fix [src/app.ts](t3-context://v1/mention/source) so the sidebar remains readable when a thread starts with an image",+ ),+ ).toBe("Fix src/app.ts so the sidebar remains readable when a thread starts w...");+ });+it("keeps ordinary titles and the empty-prompt fallback", () => {expect(deriveThreadTitleFromPrompt(" Fix\n the parser ")).toBe("Fix the parser");expect(deriveThreadTitleFromPrompt(" \n ")).toBe("New thread");});- it("derives attachment-only titles from prepared image metadata", () => {- const uploadedAttachments = [- {- type: "image" as const,- id: "prepared-photo",- name: "photo.png",- mimeType: "image/png",- sizeBytes: 3,- },- ];- const input = buildProjectThreadStartTurnInput({+ it.each([+ {+ type: "image" as const,+ name: "photo.png",+ mimeType: "image/png",+ text: "",+ title: "Attached image",+ },+ {+ type: "file" as const,+ name: "report.pdf",+ mimeType: "application/pdf",+ text: "",+ title: "File: report.pdf",+ },+ {+ type: "file" as const,+ name: "report.pdf",+ mimeType: "application/pdf",+ text: "[report.pdf](t3-context://v1/file/report)",+ title: "report.pdf",+ },+ ])("titles a $type-only message without changing its data", ({ text, title, ...attachment }) => {+ const uploadedAttachments = [{ ...attachment, id: "prepared-attachment", sizeBytes: 3 }];+ const wire = serializeComposerMessageForServer(text, undefined, true);+ const spec = {projectId: ProjectId.make("project"),projectCwd: "/workspace",threadId: "image-thread",commandId: "image-command",messageId: "image-message",createdAt: "2026-09-04T00:00:00Z",- text: "",+ ...wire,+ titleText: text,uploadedAttachments,modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" },runtimeMode: "full-access",@@ -46,11 +73,22 @@ describe("project thread title", () => {worktreePath: null,startFromOrigin: false,worktreeBranchName: "unused",- });+ } satisfies ProjectThreadStartTurnSpec;+ const input = buildProjectThreadStartTurnInput(spec);- expect(input.titleSeed).toBe("Image: photo.png");+ expect(input.titleSeed).toBe(title);expect(input.bootstrap.createThread.title).toBe(input.titleSeed);expect(input.message.attachments).toEqual(uploadedAttachments);+ expect(input.message.text).toBe(wire.text);+ const relaunched = buildProjectThreadStartTurnInput({+ ...spec,+ threadId: "local-relaunch",+ text: input.message.text,+ titleText: input.bootstrap.createThread.title,+ });+ expect(relaunched.titleSeed).toBe(title);+ expect(relaunched.message.text).toBe(wire.text);+ expect(relaunched.message.attachments).toEqual(uploadedAttachments);});it.each([diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.tsindex 030f8bee6f6..1e677d232b8 100644--- a/apps/mobile/src/lib/projectThreadStartTurn.ts+++ b/apps/mobile/src/lib/projectThreadStartTurn.ts@@ -9,8 +9,10 @@ import {type ProviderInteractionMode,type RuntimeMode,} from "@t3tools/contracts";-import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";-import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";+import {+ deriveThreadTitleSeed,+ threadTitleTextFromPrompt,+} from "@t3tools/client-runtime/operations";import type { UploadedMobileAttachment } from "./attachmentUpload";@@ -22,6 +24,7 @@ export interface ProjectThreadStartTurnSpec {readonly messageId: string;readonly createdAt: string;readonly text: string;+ readonly titleText?: string;readonly context?: OrchestrationMessageContext;readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment | ChatAttachment>;readonly modelSelection: ModelSelection;@@ -35,7 +38,10 @@ export interface ProjectThreadStartTurnSpec {}export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) {- const title = deriveThreadTitleSeed({ text: spec.text, attachments: spec.uploadedAttachments });+ const title = deriveThreadTitleSeed({+ text: spec.titleText ?? spec.text,+ attachments: spec.uploadedAttachments,+ });const isWorktree = spec.workspaceMode === "worktree";return {commandId: CommandId.make(spec.commandId),@@ -80,11 +86,6 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe}export function deriveThreadTitleFromPrompt(value: string): string {- const trimmed = assistantCitationsToPlainText(value).trim();- if (trimmed.length === 0) {- return "New thread";- }-- const compact = trimmed.replace(/\s+/g, " ");- return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;+ const title = threadTitleTextFromPrompt(value) || "New thread";+ return title.length <= 72 ? title : `${title.slice(0, 69).trimEnd()}...`;}diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.tsindex 5ef3d6b16ce..a9796320294 100644--- a/apps/mobile/src/state/use-thread-outbox-drain.ts+++ b/apps/mobile/src/state/use-thread-outbox-drain.ts@@ -1019,6 +1019,7 @@ export function useThreadOutboxDrain(): void {commandId: queuedMessage.commandId,messageId: queuedMessage.messageId,createdAt: queuedMessage.createdAt,+ titleText: queuedMessage.text,...serializeComposerMessageForServer(queuedMessage.text.trim(),uploadedComposerContext(diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex fd28d2dd095..694e9cf3290 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -10,7 +10,6 @@ import {} from "./ChatView.logic";import * as DateTime from "effect/DateTime";import { restorePlanFollowUpComposer } from "./ChatView.logic";-import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";import {isPaintOnlyThreadTimeline,@@ -81,6 +80,7 @@ import {RuntimeMode,} from "@t3tools/contracts";import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";+import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";import {wasBootstrapThreadDeleted,wasBootstrapThreadNotCreated,@@ -341,7 +341,6 @@ import {import {ensureInlineContextReferences,removeInlineContextReference,- stripInlineContextReferences,} from "../lib/composerContextReferences";import { serializeLegacyContextMessage } from "@t3tools/shared/composerContextLegacySend";import {@@ -6598,11 +6597,10 @@ export default function ChatView(props: ChatViewProps) {: composerAttachmentsSnapshot[index]!.id,),);- const title = truncate(- assistantCitationsToPlainText(stripInlineContextReferences(trimmed)).trim() ||- composerAttachmentsSnapshot[0]?.name ||- "New thread",- );+ const title = deriveThreadTitleSeed({+ text: messageTextForSend,+ attachments: composerAttachmentsSnapshot,+ });promptRef.current = "";clearComposerDraftContent(composerDraftTarget);composerRef.current?.resetCursorState();@@ -6851,30 +6849,21 @@ export default function ChatView(props: ChatViewProps) {clearComposerDraftContent(composerDraftTarget);composerRef.current?.resetCursorState();- let firstComposerImageName: string | null = null;- if (composerImagesSnapshot.length > 0) {- const firstComposerImage = composerImagesSnapshot[0];- if (firstComposerImage) {- firstComposerImageName = firstComposerImage.name;- }- }- let titleSeed = assistantCitationsToPlainText(stripInlineContextReferences(trimmed)).trim();- if (!titleSeed) {- if (firstComposerImageName) {- titleSeed = `Image: ${firstComposerImageName}`;- } else if (composerFilesSnapshot[0]) {- titleSeed = `File: ${composerFilesSnapshot[0].name}`;- } else if (composerTerminalContextsSnapshot.length > 0) {- titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);- } else if (composerReviewCommentsSnapshot.length > 0) {- titleSeed = `Review: ${reviewCommentContextLabel(composerReviewCommentsSnapshot[0]!)}`;- } else if (composerPreviewAnnotationsSnapshot.length > 0) {- titleSeed = previewAnnotationContextLabel(composerPreviewAnnotationsSnapshot[0]!);- } else {- titleSeed = "New thread";- }- }- const title = truncate(titleSeed);+ const title = deriveThreadTitleSeed({+ text: messageTextForSend,+ attachments: composerAttachmentsSnapshot,+ fallbackLabels: [+ composerTerminalContextsSnapshot[0]+ ? formatTerminalContextLabel(composerTerminalContextsSnapshot[0])+ : undefined,+ composerReviewCommentsSnapshot[0]+ ? `Review: ${reviewCommentContextLabel(composerReviewCommentsSnapshot[0])}`+ : undefined,+ composerPreviewAnnotationsSnapshot[0]+ ? previewAnnotationContextLabel(composerPreviewAnnotationsSnapshot[0])+ : undefined,+ ],+ });const threadCreateModelSelection = createModelSelection(ctxSelectedModelSelection.instanceId,ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL,diff --git a/packages/client-runtime/src/operations/threadTitle.test.ts b/packages/client-runtime/src/operations/threadTitle.test.tsindex ab7aaff7ff4..7a785b0cba1 100644--- a/packages/client-runtime/src/operations/threadTitle.test.ts+++ b/packages/client-runtime/src/operations/threadTitle.test.ts@@ -3,23 +3,41 @@ import { describe, expect, it } from "@effect/vitest";import { deriveThreadTitleSeed } from "./threadTitle.ts";describe("deriveThreadTitleSeed", () => {- it("prefers normalized message text", () => {+ const image = "";++ it.each([+ [image, "Attached image"],+ [`${image}\n`, "Attached images"],+ ])("uses a readable image-only title for %s", (text, title) => {+ expect(deriveThreadTitleSeed({ text, attachments: [] })).toBe(title);+ });++ it("prefers a source label when an image prompt has no prose", () => {+ expect(+ deriveThreadTitleSeed({+ text: `${image}\n[src/app.ts](t3-context://v1/mention/source)`,+ attachments: [{ type: "image", name: "pasted-image.png" }],+ }),+ ).toBe("src/app.ts");+ });++ it("prefers normalized request text and context labels over attachments", () => {expect(deriveThreadTitleSeed({- text: " Investigate\n login failures ",- attachments: [{ name: "login-error.png" }],+ text: ` Fix ${image} [src/app.ts](t3-context://v1/mention/source)\n using [Build output](t3-context://v1/terminal/build) `,+ attachments: [{ type: "image", name: "login-error.png" }],fallbackLabels: ["Terminal 1"],}),- ).toBe("Investigate login failures");+ ).toBe("Fix src/app.ts using Build output");});- it("uses the first attachment name when text is empty", () => {+ it("uses an image placeholder when text is empty", () => {expect(deriveThreadTitleSeed({text: " \n ",- attachments: [{ name: "login-error.png" }, { name: "other.png" }],+ attachments: [{ type: "image", name: "login-error.png" }],}),- ).toBe("Image: login-error.png");+ ).toBe("Attached image");});it("uses the first non-empty fallback label after text and attachments", () => {diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.tsindex 49b7b72dcaf..2fc2da25e4f 100644--- a/packages/client-runtime/src/operations/threadTitle.ts+++ b/packages/client-runtime/src/operations/threadTitle.ts@@ -1,9 +1,11 @@+import type { ChatAttachment } from "@t3tools/contracts";import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";+import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";import { truncate } from "@t3tools/shared/String";export interface ThreadTitleSeedInput {readonly text: string;- readonly attachments: ReadonlyArray<{ readonly name: string }>;+ readonly attachments: ReadonlyArray<Pick<ChatAttachment, "type" | "name">>;readonly fallbackLabels?: ReadonlyArray<string | null | undefined>;}@@ -11,15 +13,35 @@ function normalizeTitleSeed(value: string): string {return assistantCitationsToPlainText(value).trim().replace(/\s+/gu, " ");}+export function threadTitleTextFromPrompt(value: string): string {+ const imageIds = new Set<string>();+ const prose = replaceComposerContextReferences(value, (reference) => {+ if (reference.kind === "image") {+ imageIds.add(reference.contextId);+ return "";+ }+ return reference.label;+ });+ return (+ normalizeTitleSeed(prose) ||+ (imageIds.size > 0 ? (imageIds.size === 1 ? "Attached image" : "Attached images") : "")+ );+}+export function deriveThreadTitleSeed(input: ThreadTitleSeedInput): string {- const text = normalizeTitleSeed(input.text);+ const text = threadTitleTextFromPrompt(input.text);if (text.length > 0) {return truncate(text);}+ const images = input.attachments.filter((attachment) => attachment.type === "image");+ if (images.length > 0) {+ return images.length === 1 ? "Attached image" : "Attached images";+ }+const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");if (attachmentName.length > 0) {- return truncate(`Image: ${attachmentName}`);+ return truncate(`File: ${attachmentName}`);}for (const label of input.fallbackLabels ?? []) {