Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadTitle.ts

67 lines2.2 KB

1import type { ChatAttachment } from "@t3tools/contracts";
2import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
3import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
4import { truncate } from "@t3tools/shared/String";
5​
6import { collectComposerModelMentions } from "../composerModelMentions.ts";
7​
8export interface ThreadTitleSeedInput {
9 readonly text: string;
10 readonly attachments: ReadonlyArray<Pick<ChatAttachment, "type" | "name">>;
11 readonly fallbackLabels?: ReadonlyArray<string | null | undefined>;
13​
14function normalizeTitleSeed(value: string): string {
15 return assistantCitationsToPlainText(value).trim().replace(/\s+/gu, " ");
17​
18function modelMentionsAsSlugs(value: string): string {
19 let result = "";
20 let cursor = 0;
21 for (const mention of collectComposerModelMentions(value)) {
22 result += value.slice(cursor, mention.start) + mention.model;
23 cursor = mention.end;
24 }
25 return result + value.slice(cursor);
27​
28export function threadTitleTextFromPrompt(value: string): string {
29 const imageIds = new Set<string>();
30 const prose = replaceComposerContextReferences(value, (reference) => {
31 if (reference.kind === "image") {
32 imageIds.add(reference.contextId);
33 return "";
34 }
35 return reference.label;
36 });
37 return (
38 normalizeTitleSeed(modelMentionsAsSlugs(prose)) ||
39 (imageIds.size > 0 ? (imageIds.size === 1 ? "Attached image" : "Attached images") : "")
40 );
42​
43export function deriveThreadTitleSeed(input: ThreadTitleSeedInput): string {
44 const text = threadTitleTextFromPrompt(input.text);
45 if (text.length > 0) {
46 return truncate(text);
47 }
48​
49 const images = input.attachments.filter((attachment) => attachment.type === "image");
50 if (images.length > 0) {
51 return images.length === 1 ? "Attached image" : "Attached images";
52 }
53​
54 const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");
55 if (attachmentName.length > 0) {
56 return truncate(`File: ${attachmentName}`);
57 }
58​
59 for (const label of input.fallbackLabels ?? []) {
60 const normalized = normalizeTitleSeed(label ?? "");
61 if (normalized.length > 0) {
62 return truncate(normalized);
63 }
64 }
65​
66 return "New thread";