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

threadTitle.ts

80 lines2.6 KB

1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import type { ChatAttachment } from "@t3tools/contracts";
4import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
5import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6import { truncate } from "@t3tools/shared/String";
7​
8import { collectComposerModelMentions } from "../composerModelMentions.ts";
9​
10export interface ThreadTitleSeedInput {
11 readonly text: string;
12 readonly attachments: ReadonlyArray<Pick<ChatAttachment, "type" | "name">>;
13 readonly fallbackLabels?: ReadonlyArray<string | null | undefined>;
15​
16function normalizeTitleSeed(value: string): string {
17 // Mentioned macOS paths can be NFD; titles show them composed.
18 return assistantCitationsToPlainText(value).trim().replace(/\s+/gu, " ").normalize("NFC");
20​
21function modelMentionsAsSlugs(value: string): string {
22 let result = "";
23 let cursor = 0;
24 for (const mention of collectComposerModelMentions(value)) {
25 result += value.slice(cursor, mention.start) + mention.model;
26 cursor = mention.end;
27 }
28 return result + value.slice(cursor);
30​
31function attachedImagesTitle(count: number, resolve: MFunctionType): string {
32 return count === 1 ? resolve(msg("Attached image")) : resolve(msg("Attached images"));
34​
35export function threadTitleTextFromPrompt(
36 value: string,
37 resolve: MFunctionType = mFallback,
38): string {
39 const imageIds = new Set<string>();
40 const prose = replaceComposerContextReferences(value, (reference) => {
41 if (reference.kind === "image") {
42 imageIds.add(reference.contextId);
43 return "";
44 }
45 return reference.label;
46 });
47 return (
48 normalizeTitleSeed(modelMentionsAsSlugs(prose)) ||
49 (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "")
50 );
52​
53export function deriveThreadTitleSeed(
54 input: ThreadTitleSeedInput,
55 resolve: MFunctionType = mFallback,
56): string {
57 const text = threadTitleTextFromPrompt(input.text, resolve);
58 if (text.length > 0) {
59 return truncate(text);
60 }
61​
62 const images = input.attachments.filter((attachment) => attachment.type === "image");
63 if (images.length > 0) {
64 return attachedImagesTitle(images.length, resolve);
65 }
66​
67 const attachmentName = normalizeTitleSeed(input.attachments[0]?.name ?? "");
68 if (attachmentName.length > 0) {
69 return truncate(resolve(msg("File: {name}", { name: attachmentName })));
70 }
71​
72 for (const label of input.fallbackLabels ?? []) {
73 const normalized = normalizeTitleSeed(label ?? "");
74 if (normalized.length > 0) {
75 return truncate(normalized);
76 }
77 }
78​
79 return resolve(msg("New thread"));