@devries-cameron20 / t3code Mirror · read-only / commits / c5f842d4c7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 16:00 UTC

fix(server): regenerate titles on fresh run forks (#36637)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 14, 2026 at 11:36 UTC c5f842d4c7d70f483a99de77301e25566eb6bad8
4 files changed +334 -73
apps/server/src/orchestration-v2/ProjectionStore.ts
+1 -1
@@ -1531,7 +1531,7 @@ function isRolledBackBeforeFork(
1531 return rolledBackAt !== null && DateTime.isLessThan(rolledBackAt, forkCreatedAt);
1532 }
1533
1534 -function forkInheritedRunOrdinals(
1534 +export function forkInheritedRunOrdinals(
1535 runs: ReadonlyArray<OrchestrationV2Run>,
1536 forkCreatedAt: DateTime.Utc,
1537 ): Map<RunId, number> {
apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
+274 -55
@@ -19,6 +19,7 @@ import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Layer from "effect/Layer";
21 import * as Option from "effect/Option";
22 +import * as TestClock from "effect/testing/TestClock";
23 import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
24
25 import * as SqlitePersistence from "../persistence/Sqlite.ts";
@@ -271,6 +272,53 @@ function armRegeneration(input: { readonly command: string; readonly threadId: T
272 });
273 }
274
275 +/** Forks a source thread at its middle run, between a rolled-back run and later work. */
276 +function forkSeededSource(prefix: string, sideChat = false, rollbackPriorRun = true) {
277 + return Effect.gen(function* () {
278 + const threads = yield* ThreadManagement.ThreadManagementService;
279 + const sourceThreadId = yield* createThread({
280 + command: `${prefix}:create`,
281 + thread: `${prefix}:source`,
282 + });
283 + yield* recordRun({
284 + threadId: sourceThreadId,
285 + runId: RunId.make(`${prefix}:run:0`),
286 + ordinal: 1,
287 + user: "Rolled back attempt",
288 + assistant: "Discarded.",
289 + status: rollbackPriorRun ? "rolled_back" : "completed",
290 + });
291 + yield* TestClock.adjust(1);
292 + const forkRunId = RunId.make(`${prefix}:run:1`);
293 + yield* recordRun({
294 + threadId: sourceThreadId,
295 + runId: forkRunId,
296 + ordinal: 2,
297 + user: "Move session storage from Redis to Postgres",
298 + assistant: "Sessions now persist in the Postgres sessions table.",
299 + });
300 + yield* recordRun({
301 + threadId: sourceThreadId,
302 + runId: RunId.make(`${prefix}:run:2`),
303 + ordinal: 3,
304 + user: "Later work the fork never saw",
305 + assistant: "Done.",
306 + });
307 + const forkThreadId = ThreadId.make(`${prefix}:target`);
308 + yield* threads.dispatch({
309 + type: "thread.fork",
310 + commandId: CommandId.make(`${prefix}:fork`),
311 + sourceThreadId,
312 + targetThreadId: forkThreadId,
313 + sourcePoint: { type: "run", runId: forkRunId },
314 + sideChat,
315 + createdBy: "user",
316 + creationSource: "web",
317 + });
318 + return { sourceThreadId, forkRunId, forkThreadId };
319 + });
320 +}
321 +
322 describe("formatThreadTitleContext", () => {
323 it("pins the first user message ahead of the retained tail once content stops fitting", () => {
324 const context = ThreadTitleRegeneration.formatThreadTitleContext([
@@ -443,80 +491,251 @@ describe("ThreadTitleRegenerationService", () => {
491 }).pipe(Effect.provide(NodeServices.layer)),
492 );
493
446 - it.effect("titles a fork's first message with the source history up to the fork point", () =>
494 + it.effect.each([
495 + { name: "its first message", followUp: true },
496 + { name: "no message of its own yet", followUp: false },
497 + ])("titles a fork with $name from the source history up to the fork point", ({ followUp }) =>
498 Effect.gen(function* () {
499 const harness = makeHarness();
500 yield* Effect.gen(function* () {
501 const threads = yield* ThreadManagement.ThreadManagementService;
502 const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
452 - const sourceThreadId = yield* createThread({
453 - command: "command:title:fork:create",
454 - thread: "thread:title:fork:source",
503 + const { forkThreadId } = yield* forkSeededSource("thread:title:fork");
504 + const requestId = CommandId.make("command:title:fork:request");
505 + const messageId = MessageId.make("command:title:fork:request:message");
506 + if (followUp) {
507 + yield* threads.dispatch({
508 + type: "message.dispatch",
509 + commandId: requestId,
510 + threadId: forkThreadId,
511 + messageId,
512 + text: "Try SQLite instead",
513 + titleSeed: "Try SQLite instead",
514 + attachments: [],
515 + modelSelection,
516 + dispatchMode: { type: "defer_start" },
517 + createdBy: "user",
518 + creationSource: "web",
519 + });
520 + } else {
521 + yield* armRegeneration({ command: requestId, threadId: forkThreadId });
522 + }
523 +
524 + yield* titleRegeneration.execute({
525 + threadId: forkThreadId,
526 + requestId,
527 + kind: followUp ? { type: "initial", messageId } : { type: "regenerate" },
528 });
456 - yield* recordRun({
457 - threadId: sourceThreadId,
458 - runId: RunId.make("run:title:fork:0"),
459 - ordinal: 1,
460 - user: "Rolled back attempt",
461 - assistant: "Discarded.",
462 - status: "rolled_back",
529 +
530 + const call = harness.generateThreadTitle.mock.calls[0]?.[0];
531 + assert.equal(call?.message, followUp ? "Try SQLite instead" : "");
532 + assert.equal(call?.forkSource?.title, "Seed title");
533 + assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
534 + assert.include(call?.forkSource?.history, "Sessions now persist in the Postgres");
535 + assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
536 + assert.notInclude(call?.forkSource?.history, "Rolled back attempt");
537 + const fork = yield* threads.getThreadRecords(forkThreadId, []);
538 + assert.equal(fork.thread.title, "Generated title");
539 + }).pipe(Effect.provide(harness.layer));
540 + }),
541 + );
542 +
543 + it.effect.each(["plain", "deleted source"] as const)(
544 + "refuses to title an empty thread with %s history",
545 + (history) =>
546 + Effect.gen(function* () {
547 + const harness = makeHarness();
548 + yield* Effect.gen(function* () {
549 + const threads = yield* ThreadManagement.ThreadManagementService;
550 + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
551 + const { forkThreadId } = yield* forkSeededSource("thread:title:empty");
552 + const { thread } = yield* threads.getThreadProjection(forkThreadId);
553 + const eventSink = yield* EventSink.EventSinkV2;
554 + yield* eventSink.write({
555 + events: [
556 + {
557 + id: EventId.make("empty:lineage"),
558 + type: "thread.metadata-updated",
559 + threadId: forkThreadId,
560 + occurredAt: yield* DateTime.now,
561 + payload: {
562 + ...thread,
563 + forkedFrom:
564 + history === "plain"
565 + ? null
566 + : {
567 + type: "run",
568 + threadId: ThreadId.make("absent"),
569 + runId: RunId.make("absent"),
570 + },
571 + },
572 + },
573 + ],
574 + });
575 + const requestId = yield* armRegeneration({
576 + command: "empty:request",
577 + threadId: forkThreadId,
578 + });
579 + yield* titleRegeneration.execute({
580 + threadId: forkThreadId,
581 + requestId,
582 + kind: { type: "regenerate" },
583 + });
584 + assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
585 + const fork = yield* threads.getThreadRecords(forkThreadId, []);
586 + assert.deepInclude(fork.thread.lastTitleRegeneration, {
587 + requestId,
588 + status: "failed",
589 + message: "This thread has no messages to title yet.",
590 + });
591 + }).pipe(Effect.provide(harness.layer));
592 + }),
593 + );
594 +
595 + it.effect("keeps the fork point when the source rolls it back after forking", () =>
596 + Effect.gen(function* () {
597 + const harness = makeHarness();
598 + yield* Effect.gen(function* () {
599 + const threads = yield* ThreadManagement.ThreadManagementService;
600 + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
601 + const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(
602 + "thread:title:rollback",
603 + false,
604 + false,
605 + );
606 + yield* TestClock.adjust(1);
607 + const source = yield* threads.getThreadRecords(sourceThreadId, ["runs"]);
608 + const run = source.runs.find((run) => run.id === forkRunId);
609 + assert.isDefined(run);
610 + const now = yield* DateTime.now;
611 + const eventSink = yield* EventSink.EventSinkV2;
612 + yield* eventSink.write({
613 + events: [
614 + {
615 + id: EventId.make("source:rollback"),
616 + type: "run.updated",
617 + threadId: sourceThreadId,
618 + runId: run.id,
619 + occurredAt: now,
620 + payload: { ...run, status: "rolled_back", completedAt: now },
621 + },
622 + ],
623 });
464 - const forkRunId = RunId.make("run:title:fork:1");
465 - yield* recordRun({
466 - threadId: sourceThreadId,
467 - runId: forkRunId,
468 - ordinal: 2,
469 - user: "Move session storage from Redis to Postgres",
470 - assistant: "Sessions now persist in the Postgres sessions table.",
624 + const requestId = yield* armRegeneration({
625 + command: "rollback:request",
626 + threadId: forkThreadId,
627 });
472 - yield* recordRun({
628 + yield* titleRegeneration.execute({
629 + threadId: forkThreadId,
630 + requestId,
631 + kind: { type: "regenerate" },
632 + });
633 + const call = harness.generateThreadTitle.mock.calls[0]?.[0];
634 + assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
635 + assert.include(call?.forkSource?.history, "Rolled back attempt");
636 + assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
637 + const fork = yield* threads.getThreadRecords(forkThreadId, []);
638 + assert.equal(fork.thread.title, "Generated title");
639 + }).pipe(Effect.provide(harness.layer));
640 + }),
641 + );
642 +
643 + it.effect("does not inherit imported history when the fork point is missing", () =>
644 + Effect.gen(function* () {
645 + const harness = makeHarness();
646 + yield* Effect.gen(function* () {
647 + const threads = yield* ThreadManagement.ThreadManagementService;
648 + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
649 + const { sourceThreadId, forkThreadId } = yield* forkSeededSource("thread:title:invalid");
650 + yield* dispatchUserMessage({
651 + command: "imported:message",
652 threadId: sourceThreadId,
474 - runId: RunId.make("run:title:fork:2"),
475 - ordinal: 3,
476 - user: "Later work the fork never saw",
477 - assistant: "Done.",
653 + text: "Imported history",
654 });
479 - const forkThreadId = ThreadId.make("thread:title:fork:target");
480 - yield* threads.dispatch({
481 - type: "thread.fork",
482 - commandId: CommandId.make("command:title:fork:fork"),
483 - sourceThreadId,
484 - targetThreadId: forkThreadId,
485 - sourcePoint: { type: "run", runId: forkRunId },
486 - createdBy: "user",
487 - creationSource: "web",
655 + const source = yield* threads.getThreadRecords(sourceThreadId, []);
656 + const fork = yield* threads.getThreadRecords(forkThreadId, []);
657 + const eventSink = yield* EventSink.EventSinkV2;
658 + yield* eventSink.write({
659 + events: [
660 + {
661 + id: EventId.make("source:imported"),
662 + type: "thread.metadata-updated",
663 + threadId: sourceThreadId,
664 + occurredAt: yield* DateTime.now,
665 + payload: { ...source.thread, historyOrigin: "v1_import" },
666 + },
667 + {
668 + id: EventId.make("fork:missing-run"),
669 + type: "thread.metadata-updated",
670 + threadId: forkThreadId,
671 + occurredAt: yield* DateTime.now,
672 + payload: {
673 + ...fork.thread,
674 + forkedFrom: {
675 + type: "run",
676 + threadId: sourceThreadId,
677 + runId: RunId.make("absent:run"),
678 + },
679 + },
680 + },
681 + ],
682 });
489 - const requestId = CommandId.make("command:title:fork:message");
490 - const messageId = MessageId.make("command:title:fork:message:message");
491 - yield* threads.dispatch({
492 - type: "message.dispatch",
493 - commandId: requestId,
683 + const requestId = yield* armRegeneration({
684 + command: "invalid:request",
685 threadId: forkThreadId,
495 - messageId,
496 - text: "Try SQLite instead",
497 - titleSeed: "Try SQLite instead",
498 - attachments: [],
499 - modelSelection,
500 - dispatchMode: { type: "defer_start" },
501 - createdBy: "user",
502 - creationSource: "web",
686 });
504 -
687 yield* titleRegeneration.execute({
688 threadId: forkThreadId,
689 requestId,
508 - kind: { type: "initial", messageId },
690 + kind: { type: "regenerate" },
691 + });
692 + assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
693 + const updated = yield* threads.getThreadRecords(forkThreadId, []);
694 + assert.deepInclude(updated.thread.lastTitleRegeneration, {
695 + requestId,
696 + status: "failed",
697 + message: "This thread has no messages to title yet.",
698 });
699 + }).pipe(Effect.provide(harness.layer));
700 + }),
701 + );
702
703 + it.effect("inherits a side chat's own exchange without its parent's history", () =>
704 + Effect.gen(function* () {
705 + const harness = makeHarness();
706 + yield* Effect.gen(function* () {
707 + const threads = yield* ThreadManagement.ThreadManagementService;
708 + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
709 + const { forkThreadId: sideChatId } = yield* forkSeededSource(
710 + "thread:title:side-ancestor",
711 + true,
712 + );
713 + const runId = RunId.make("side:run");
714 + yield* recordRun({
715 + threadId: sideChatId,
716 + runId,
717 + ordinal: 1,
718 + user: "Side topic",
719 + assistant: "Side answer",
720 + });
721 + const threadId = ThreadId.make("side:fork");
722 + yield* threads.dispatch({
723 + type: "thread.fork",
724 + commandId: CommandId.make("side:fork"),
725 + sourceThreadId: sideChatId,
726 + targetThreadId: threadId,
727 + sourcePoint: { type: "run", runId },
728 + title: "Side fork",
729 + createdBy: "user",
730 + creationSource: "web",
731 + });
732 + const requestId = yield* armRegeneration({ command: "side:request", threadId });
733 + yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
734 const call = harness.generateThreadTitle.mock.calls[0]?.[0];
512 - assert.equal(call?.message, "Try SQLite instead");
513 - assert.equal(call?.forkSource?.title, "Seed title");
514 - assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres");
515 - assert.include(call?.forkSource?.history, "Sessions now persist in the Postgres");
516 - assert.notInclude(call?.forkSource?.history, "Later work the fork never saw");
517 - assert.notInclude(call?.forkSource?.history, "Rolled back attempt");
518 - const fork = yield* threads.getThreadProjection(forkThreadId);
519 - assert.equal(fork.thread.title, "Generated title");
735 + assert.equal(call?.forkSource?.title, "Seed title fork");
736 + assert.include(call?.forkSource?.history, "Side topic");
737 + assert.include(call?.forkSource?.history, "Side answer");
738 + assert.notInclude(call?.forkSource?.history, "Move session storage");
739 }).pipe(Effect.provide(harness.layer));
740 }),
741 );
apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts
+33 -17
@@ -14,6 +14,7 @@ import {
14 import * as Cause from "effect/Cause";
15 import * as Context from "effect/Context";
16 import * as Effect from "effect/Effect";
17 +import type * as DateTime from "effect/DateTime";
18 import * as FileSystem from "effect/FileSystem";
19 import * as Layer from "effect/Layer";
20 import * as Option from "effect/Option";
@@ -24,6 +25,7 @@ import * as ServerSettings from "../serverSettings.ts";
25 import * as TextGeneration from "../textGeneration/TextGeneration.ts";
26 import type { OrchestratorV2Error } from "./Orchestrator.ts";
27 import * as ProjectStore from "./ProjectStore.ts";
28 +import { forkInheritedRunOrdinals, ProjectionStoreThreadNotFoundError } from "./ProjectionStore.ts";
29 import * as ThreadManagementService from "./ThreadManagementService.ts";
30
31 import { formatThreadTitleContext } from "@t3tools/provider-core/server/threadTitleContext";
@@ -55,6 +57,7 @@ type Outcome =
57
58 const MAX_FAILURE_MESSAGE_LENGTH = 300;
59 const isTextGenerationError = Schema.is(TextGenerationError);
60 +const isProjectionStoreThreadNotFoundError = Schema.is(ProjectionStoreThreadNotFoundError);
61
62 function failureMessage(cause: Cause.Cause<unknown>): string {
63 const error = Cause.squash(cause);
@@ -103,16 +106,13 @@ const make = Effect.gen(function* () {
106 .pipe(Effect.asVoid);
107
108 const messagesThroughRun = Effect.fn("ThreadTitleRegenerationService.messagesThroughRun")(
106 - function* (threadId: ThreadId, runId: RunId) {
109 + function* (threadId: ThreadId, runId: RunId, forkCreatedAt: DateTime.Utc) {
110 const source = yield* threads.getThreadRecords(threadId, ["messages", "runs"], {
111 messageRoles: ["user", "assistant"],
112 });
110 - const ordinals = new Map(
111 - source.runs
112 - .filter((run) => run.status !== "rolled_back")
113 - .map((run) => [run.id, run.ordinal]),
114 - );
115 - const forkOrdinal = ordinals.get(runId) ?? -1;
113 + const ordinals = forkInheritedRunOrdinals(source.runs, forkCreatedAt);
114 + const forkOrdinal = ordinals.get(runId);
115 + if (forkOrdinal === undefined) return undefined;
116 const messages = source.messages.filter((message) => {
117 if (message.streaming) return false;
118 if (message.runId === null) return source.thread.historyOrigin === "v1_import";
@@ -128,12 +128,20 @@ const make = Effect.gen(function* () {
128 ) {
129 let title: string | undefined;
130 const history: Array<ReadonlyArray<OrchestrationV2ConversationMessage>> = [];
131 - let forkedFrom = thread.forkedFrom;
132 - while (forkedFrom?.type === "run") {
133 - const source = yield* messagesThroughRun(forkedFrom.threadId, forkedFrom.runId);
131 + const seen = new Set([thread.id]);
132 + let current = thread;
133 + while (
134 + current.forkedFrom?.type === "run" &&
135 + current.lineage.sideChat !== true &&
136 + !seen.has(current.forkedFrom.threadId)
137 + ) {
138 + const { threadId, runId } = current.forkedFrom;
139 + seen.add(threadId);
140 + const source = yield* messagesThroughRun(threadId, runId, current.createdAt);
141 + if (source === undefined) break;
142 history.push(source.messages);
143 title ??= source.thread.title;
136 - forkedFrom = source.thread.forkedFrom;
144 + current = source.thread;
145 }
146 const context = formatThreadTitleContext(history.reverse().flat());
147 return title === undefined || context.message.length === 0
@@ -182,17 +190,25 @@ const make = Effect.gen(function* () {
190 projection.messages.filter((message) => !message.streaming),
191 );
192 }
185 - if (context.message.length === 0 && context.attachments.length === 0) {
193 + // A deleted source should not cost the fork its title.
194 + const inherited = yield* forkSource(projection.thread).pipe(
195 + Effect.catchTags({
196 + OrchestratorProjectionError: (error) =>
197 + isProjectionStoreThreadNotFoundError(error.cause)
198 + ? Effect.undefined
199 + : Effect.fail(error),
200 + }),
201 + );
202 + if (
203 + context.message.length === 0 &&
204 + context.attachments.length === 0 &&
205 + inherited === undefined
206 + ) {
207 return {
208 status: "failed" as const,
209 message: "This thread has no messages to title yet.",
210 };
211 }
191 -
192 - // A deleted source should not cost the fork its title.
193 - const inherited = yield* forkSource(projection.thread).pipe(
194 - Effect.orElseSucceed(() => undefined),
195 - );
212 const settings = resolveProjectSettings(
213 yield* serverSettings.getSettings,
214 projection.thread.projectId,
scripts/scenarios/fork-title-regenerates-from-inherited-history.e2e.ts new
+26
@@ -0,0 +1,26 @@
1 +import { expect } from "e2e";
2 +
3 +import { test, WEB } from "./t3.ts";
4 +
5 +// Scenarios title with a Codex command that always fails, so reaching it is the fixed behavior;
6 +// the bug refused first with "This thread has no messages to title yet."
7 +test(
8 + "Regenerate title on a fresh fork reaches the title model with the inherited history",
9 + WEB,
10 + async ({ t3, app, screen }) => {
11 + const project = await t3.project("demo");
12 + const thread = await t3.thread({ project, title: "Earlier work", messages: ["first"] });
13 + await t3.open(thread);
14 +
15 + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
16 + await screen.getByRole("button", "Fork from this response").first().tap();
17 + const forkActions = screen.getByRole("button", "Thread actions for Earlier work fork");
18 + await expect(forkActions).toBeVisible();
19 +
20 + await forkActions.tap();
21 + await screen.getByRole("menuitem", "Regenerate title").tap();
22 + await expect(screen.getByText("Failed to regenerate thread title")).toBeVisible();
23 + await app.screenshot("regenerate-result");
24 + await expect(screen.getByText("Codex CLI command", { exact: false })).toBeVisible();
25 + },
26 +);