Skip to content

Commit 53d6ba2

Browse files
committed
fix: Regenerate title always says what happened
1 parent 337c585 commit 53d6ba2

17 files changed

Lines changed: 506 additions & 63 deletions

‎apps/mobile/src/features/home/useThreadListActions.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ vi.mock("../../state/threads", () => ({
138138
"reorderPin",
139139
"reorderActive",
140140
"updateMetadata",
141+
"regenerateTitle",
141142
].map((action) => [
142143
action,
143144
async (request: {
@@ -182,7 +183,7 @@ const mutationCases = [
182183
["unsnoozeThread", "unsnooze"],
183184
["pinThread", "pin"],
184185
["unpinThread", "unpin"],
185-
["regenerateThreadTitle", "updateMetadata"],
186+
["regenerateThreadTitle", "regenerateTitle"],
186187
] as const;
187188

188189
beforeEach(() => {

‎apps/mobile/src/features/home/useThreadListActions.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,9 @@ export function useThreadListActions(): {
220220
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
221221
reportFailure: false,
222222
});
223+
const regenerateTitle = useAtomCommand(threadEnvironment.regenerateTitle, {
224+
reportFailure: false,
225+
});
223226
const snoozeInFlightThreadKeys = useRef(new Set<string>());
224227
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
225228

@@ -511,9 +514,9 @@ export function useThreadListActions(): {
511514
titleRegenerationInFlightThreadKeys.current.add(key);
512515
selectionHaptic();
513516
const succeeded = await (async () => {
514-
const result = await updateThreadMetadata({
517+
const result = await regenerateTitle({
515518
environmentId: thread.environmentId,
516-
input: { threadId: thread.id, regenerateTitle: true },
519+
input: { threadId: thread.id },
517520
});
518521
if (result._tag === "Failure") {
519522
const error = Cause.squash(result.cause);
@@ -525,6 +528,14 @@ export function useThreadListActions(): {
525528
);
526529
return false;
527530
}
531+
if (result.value?.status === "failed") {
532+
Dialog.alert(
533+
"Could not regenerate title",
534+
result.value.message ?? "The thread title could not be regenerated.",
535+
);
536+
} else if (result.value?.status === "unchanged") {
537+
Dialog.alert("Title kept", "The current title already fits this thread.");
538+
}
528539
return true;
529540
})();
530541
titleRegenerationInFlightThreadKeys.current.delete(key);

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,13 @@ function threadDetail(
856856
requestId: projection.thread.titleRegeneration.requestId,
857857
startedAt: DateTime.formatIso(projection.thread.titleRegeneration.startedAt),
858858
},
859+
lastTitleRegeneration:
860+
projection.thread.lastTitleRegeneration == null
861+
? null
862+
: {
863+
...projection.thread.lastTitleRegeneration,
864+
completedAt: DateTime.formatIso(projection.thread.lastTitleRegeneration.completedAt),
865+
},
859866
branch: projection.thread.branch,
860867
worktreePath: projection.thread.worktreePath,
861868
parentThreadId: projection.thread.lineage.parentThreadId,

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4010,6 +4010,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
40104010
? {
40114011
...thread,
40124012
...(command.title === undefined ? {} : { title: command.title }),
4013+
...(command.outcome === undefined
4014+
? {}
4015+
: {
4016+
lastTitleRegeneration: {
4017+
...command.outcome,
4018+
requestId: command.requestId,
4019+
completedAt: now,
4020+
},
4021+
}),
40134022
titleRegeneration: null,
40144023
updatedAt: now,
40154024
}

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1684,6 +1684,7 @@ export function threadShellFromProjection(
16841684
lastVisitedAt: projection.thread.lastVisitedAt,
16851685
opens: projection.thread.opens ?? null,
16861686
titleRegeneration: projection.thread.titleRegeneration ?? null,
1687+
lastTitleRegeneration: projection.thread.lastTitleRegeneration ?? null,
16871688
limitRecovery: projection.thread.limitRecovery ?? null,
16881689
deletedAt: projection.thread.deletedAt,
16891690
};
@@ -1950,6 +1951,7 @@ function shellFromState(input: {
19501951
lastVisitedAt: input.state.thread.lastVisitedAt,
19511952
opens: input.state.thread.opens ?? null,
19521953
titleRegeneration: input.state.thread.titleRegeneration ?? null,
1954+
lastTitleRegeneration: input.state.thread.lastTitleRegeneration ?? null,
19531955
limitRecovery: input.state.thread.limitRecovery ?? null,
19541956
deletedAt: input.state.thread.deletedAt,
19551957
};

‎apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
ProviderInstanceId,
1212
ProviderThreadId,
1313
RunId,
14+
TextGenerationError,
1415
ThreadId,
1516
} from "@t3tools/contracts";
1617
import * as DateTime from "effect/DateTime";
@@ -432,6 +433,10 @@ describe("ThreadTitleRegenerationService", () => {
432433
const projection = yield* threads.getThreadProjection(threadId);
433434
assert.equal(projection.thread.title, "Fresh title");
434435
assert.isNotOk(projection.thread.titleRegeneration);
436+
assert.deepInclude(projection.thread.lastTitleRegeneration, {
437+
requestId,
438+
status: "renamed",
439+
});
435440
}
436441
}).pipe(Effect.provide(harness.layer));
437442
}).pipe(Effect.provide(NodeServices.layer)),
@@ -518,7 +523,14 @@ describe("ThreadTitleRegenerationService", () => {
518523
it.effect("clears the marker and keeps the title when generation fails", () =>
519524
Effect.gen(function* () {
520525
const harness = makeHarness({
521-
generateTitle: () => Effect.die(new Error("model unavailable")),
526+
generateTitle: () =>
527+
Effect.fail(
528+
new TextGenerationError({
529+
operation: "generateThreadTitle",
530+
detail:
531+
"Codex CLI command failed: OpenAI Codex\nuser\nConversation text\nmodel unavailable\n",
532+
}),
533+
),
522534
});
523535
yield* Effect.gen(function* () {
524536
const threads = yield* ThreadManagement.ThreadManagementService;
@@ -540,6 +552,44 @@ describe("ThreadTitleRegenerationService", () => {
540552
const projection = yield* threads.getThreadProjection(threadId);
541553
assert.equal(projection.thread.title, "Seed title");
542554
assert.isNotOk(projection.thread.titleRegeneration);
555+
assert.deepInclude(projection.thread.lastTitleRegeneration, {
556+
requestId,
557+
status: "failed",
558+
message: "model unavailable",
559+
});
560+
}).pipe(Effect.provide(harness.layer));
561+
}),
562+
);
563+
564+
it.effect("records an unchanged outcome when the model keeps the current title", () =>
565+
Effect.gen(function* () {
566+
const harness = makeHarness({
567+
generateTitle: () => Effect.succeed({ title: "Seed title" }),
568+
});
569+
yield* Effect.gen(function* () {
570+
const threads = yield* ThreadManagement.ThreadManagementService;
571+
const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
572+
const threadId = yield* createThread({
573+
command: "command:title:unchanged:create",
574+
thread: "thread:title:unchanged",
575+
});
576+
yield* dispatchUserMessage({
577+
command: "command:title:unchanged:message",
578+
threadId,
579+
text: "Some conversation",
580+
});
581+
const requestId = yield* armRegeneration({
582+
command: "command:title:unchanged:1",
583+
threadId,
584+
});
585+
586+
yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
587+
588+
const projection = yield* threads.getThreadProjection(threadId);
589+
assert.deepInclude(projection.thread.lastTitleRegeneration, {
590+
requestId,
591+
status: "unchanged",
592+
});
543593
}).pipe(Effect.provide(harness.layer));
544594
}),
545595
);

‎apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts‎

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
type OrchestrationV2ConversationMessage,
99
type RunId,
1010
type ServerSettingsError,
11+
TextGenerationError,
1112
type ThreadId,
1213
} from "@t3tools/contracts";
1314
import * as Cause from "effect/Cause";
@@ -17,6 +18,7 @@ import * as FileSystem from "effect/FileSystem";
1718
import * as Layer from "effect/Layer";
1819
import * as Option from "effect/Option";
1920
import * as Schedule from "effect/Schedule";
21+
import * as Schema from "effect/Schema";
2022

2123
import * as ServerSettings from "../serverSettings.ts";
2224
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
@@ -46,6 +48,29 @@ export class ThreadTitleRegenerationService extends Context.Service<
4648
}
4749
>()("t3/orchestration-v2/ThreadTitleRegenerationService") {}
4850

51+
type Outcome =
52+
| { readonly status: "renamed"; readonly title: string }
53+
| { readonly status: "unchanged" }
54+
| { readonly status: "failed"; readonly message: string };
55+
56+
const MAX_FAILURE_MESSAGE_LENGTH = 300;
57+
const isTextGenerationError = Schema.is(TextGenerationError);
58+
59+
function failureMessage(cause: Cause.Cause<unknown>): string {
60+
const error = Cause.squash(cause);
61+
const lines = isTextGenerationError(error)
62+
? error.detail
63+
.split("\n")
64+
.map((line) => line.trim())
65+
.filter((line) => line.length > 0)
66+
: [];
67+
const detail = lines.at(-1);
68+
if (detail === undefined) return "Title generation failed.";
69+
return detail.length > MAX_FAILURE_MESSAGE_LENGTH
70+
? `${detail.slice(0, MAX_FAILURE_MESSAGE_LENGTH - 1)}…`
71+
: detail;
72+
}
73+
4974
const make = Effect.gen(function* () {
5075
const threads = yield* ThreadManagementService.ThreadManagementService;
5176
const projects = yield* ProjectStore.ProjectStoreV2;
@@ -56,15 +81,24 @@ const make = Effect.gen(function* () {
5681
const complete = (input: {
5782
readonly threadId: ThreadId;
5883
readonly requestId: CommandId;
59-
readonly title?: string;
84+
readonly kind: { readonly type: "initial" | "regenerate" };
85+
readonly outcome: Outcome;
6086
}) =>
6187
threads
6288
.dispatch({
6389
type: "thread.title.regeneration.complete",
6490
commandId: CommandId.make(`${input.requestId}:title-complete`),
6591
threadId: input.threadId,
6692
requestId: input.requestId,
67-
...(input.title === undefined ? {} : { title: input.title }),
93+
...(input.outcome.status === "renamed" ? { title: input.outcome.title } : {}),
94+
...(input.kind.type === "regenerate"
95+
? {
96+
outcome: {
97+
status: input.outcome.status,
98+
...(input.outcome.status === "failed" ? { message: input.outcome.message } : {}),
99+
},
100+
}
101+
: {}),
68102
})
69103
.pipe(Effect.asVoid);
70104

@@ -110,9 +144,7 @@ const make = Effect.gen(function* () {
110144
const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn(
111145
"ThreadTitleRegenerationService.execute",
112146
)(function* (input) {
113-
const outcome:
114-
| { readonly type: "stale" }
115-
| { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () {
147+
const outcome: Outcome | { readonly status: "stale" } = yield* Effect.gen(function* () {
116148
const projection = yield* threads.getThreadRecords(
117149
input.threadId,
118150
["messages"],
@@ -121,12 +153,12 @@ const make = Effect.gen(function* () {
121153
: { messageRoles: ["user", "assistant"] },
122154
);
123155
if (projection.thread.titleRegeneration?.requestId !== input.requestId) {
124-
return { type: "stale" as const };
156+
return { status: "stale" as const };
125157
}
126158

127159
const project = yield* projects.get(projection.thread.projectId);
128160
if (Option.isNone(project)) {
129-
return { type: "complete" as const };
161+
return { status: "failed" as const, message: "This thread's project no longer exists." };
130162
}
131163

132164
let context: {
@@ -151,7 +183,10 @@ const make = Effect.gen(function* () {
151183
);
152184
}
153185
if (context.message.length === 0 && context.attachments.length === 0) {
154-
return { type: "complete" as const };
186+
return {
187+
status: "failed" as const,
188+
message: "This thread has no messages to title yet.",
189+
};
155190
}
156191

157192
// A deleted source should not cost the fork its title.
@@ -179,8 +214,8 @@ const make = Effect.gen(function* () {
179214
const generatedTitle = result.title.trim();
180215
return generatedTitle === "New thread" ||
181216
(input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim())
182-
? { type: "complete" as const }
183-
: { type: "complete" as const, title: result.title };
217+
? { status: "unchanged" as const }
218+
: { status: "renamed" as const, title: result.title };
184219
}).pipe(
185220
Effect.retry({
186221
times: input.kind.type === "initial" ? 2 : 0,
@@ -193,17 +228,14 @@ const make = Effect.gen(function* () {
193228
threadId: input.threadId,
194229
requestId: input.requestId,
195230
cause,
196-
}).pipe(Effect.as({ type: "complete" as const })),
231+
}).pipe(Effect.as({ status: "failed" as const, message: failureMessage(cause) })),
197232
),
198233
);
199234

200-
if (outcome.type === "stale") {
235+
if (outcome.status === "stale") {
201236
return;
202237
}
203-
yield* complete({
204-
...input,
205-
...(outcome.title === undefined ? {} : { title: outcome.title }),
206-
});
238+
yield* complete({ ...input, outcome });
207239
});
208240

209241
return ThreadTitleRegenerationService.of({ execute });

0 commit comments

Comments
 (0)