Open History to see the last commit
1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 type ChatAttachment,
5 type MessageId,
6 type ServerSettingsError,
7 type ThreadId,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Schedule from "effect/Schedule";
15
16import * as ServerSettings from "../serverSettings.ts";
17import * as TextGeneration from "../textGeneration/TextGeneration.ts";
18import type { OrchestratorV2Error } from "./Orchestrator.ts";
19import * as ProjectStore from "./ProjectStore.ts";
20import * as ThreadManagementService from "./ThreadManagementService.ts";
21
22import { formatThreadTitleContext } from "../textGeneration/ThreadTitleContext.ts";
23export { formatThreadTitleContext } from "../textGeneration/ThreadTitleContext.ts";
24
25export class ThreadTitleRegenerationService extends Context.Service<
26 ThreadTitleRegenerationService,
27 {
28 readonly execute: (input: {
29 readonly threadId: ThreadId;
30 readonly requestId: CommandId;
31 readonly kind:
32 | { readonly type: "initial"; readonly messageId: MessageId }
33 | { readonly type: "regenerate" };
34 }) => Effect.Effect<
35 void,
36 OrchestratorV2Error | ProjectStore.ProjectStoreV2Error | ServerSettingsError
37 >;
38 }
39>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
40
41const make = Effect.gen(function* () {
42 const threads = yield* ThreadManagementService.ThreadManagementService;
43 const projects = yield* ProjectStore.ProjectStoreV2;
44 const serverSettings = yield* ServerSettings.ServerSettingsService;
45 const textGeneration = yield* TextGeneration.TextGeneration;
46
47 const complete = (input: {
48 readonly threadId: ThreadId;
49 readonly requestId: CommandId;
50 readonly title?: string;
51 }) =>
52 threads
53 .dispatch({
54 type: "thread.title.regeneration.complete",
55 commandId: CommandId.make(`${input.requestId}:title-complete`),
56 threadId: input.threadId,
57 requestId: input.requestId,
58 ...(input.title === undefined ? {} : { title: input.title }),
59 })
60 .pipe(Effect.asVoid);
61
62 const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
63 "ThreadTitleRegenerationService.execute",
64 )(function* (input) {
65 const outcome:
66 | { readonly type: "stale" }
67 | { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
68 const projection = yield* threads.getThreadRecords(
69 input.threadId,
70 ["messages"],
71 input.kind.type === "initial"
72 ? { messageIds: [input.kind.messageId] }
73 : { messageRoles: ["user", "assistant"] },
74 );
75 if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
76 return { type: "stale" as const };
77 }
78
79 const project = yield* projects.get(projection.thread.projectId);
80 if (Option.isNone(project)) {
81 return { type: "complete" as const };
82 }
83
84 let context: {
85 readonly message: string;
86 readonly attachments: ReadonlyArray<ChatAttachment>;
87 };
88 if (input.kind.type === "initial") {
89 const messageId = input.kind.messageId;
90 const message = projection.messages.find(
91 (candidate) => candidate.id === messageId && !candidate.streaming,
92 );
93 context =
94 message === undefined
95 ? { message: "", attachments: [] }
96 : { message: message.text, attachments: message.attachments };
97 } else {
98 context = formatThreadTitleContext(
99 projection.messages.filter((message) => !message.streaming),
100 );
101 }
102 if (context.message.length === 0 && context.attachments.length === 0) {
103 return { type: "complete" as const };
104 }
105
106 const settings = resolveProjectSettings(
107 yield* serverSettings.getSettings,
108 projection.thread.projectId,
109 ).settings;
110 const result = yield* textGeneration.generateThreadTitle({
111 cwd: projection.thread.worktreePath ?? project.value.workspaceRoot,
112 message: context.message,
113 attachments: context.attachments,
114 ...(input.kind.type === "regenerate" ? { previousTitle: projection.thread.title } : {}),
115 modelSelection: settings.textGenerationModelSelection,
116 });
117 const generatedTitle = result.title.trim();
118 return generatedTitle === "New thread" ||
119 (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
120 ? { type: "complete" as const }
121 : { type: "complete" as const, title: result.title };
122 }).pipe(
123 Effect.retry({
124 times: input.kind.type === "initial" ? 2 : 0,
125 schedule: Schedule.exponential("2 seconds"),
126 }),
127 Effect.catchCause((cause) =>
128 Cause.hasInterruptsOnly(cause)
129 ? Effect.interrupt
130 : Effect.logWarning("Thread title generation failed", {
131 threadId: input.threadId,
132 requestId: input.requestId,
133 cause,
134 }).pipe(Effect.as({ type: "complete" as const })),
135 ),
136 );
137
138 if (outcome.type === "stale") {
139 return;
140 }
141 yield* complete({
142 ...input,
143 ...(outcome.title === undefined ? {} : { title: outcome.title }),
144 });
145 });
146
147 return ThreadTitleRegenerationService.of({ execute });
148});
149
150export const layer = Layer.effect(ThreadTitleRegenerationService, make);