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, 03:37 UTC
| 1 | import { assert, describe, it, vi } from "@effect/vitest"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { |
| 4 | CommandId, |
| 5 | ChatAttachmentId, |
| 6 | type ChatAttachment, |
| 7 | EventId, |
| 8 | MessageId, |
| 9 | ProjectId, |
| 10 | ProviderDriverKind, |
| 11 | ProviderInstanceId, |
| 12 | ProviderThreadId, |
| 13 | RunId, |
| 14 | TextGenerationError, |
| 15 | ThreadId, |
| 16 | } from "@t3tools/contracts"; |
| 17 | import * as DateTime from "effect/DateTime"; |
| 18 | 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"; |
| 26 | import * as ProjectStore from "./ProjectStore.ts"; |
| 27 | import * as ServerSettings from "../serverSettings.ts"; |
| 28 | import * as TextGeneration from "../textGeneration/TextGeneration.ts"; |
| 29 | import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; |
| 30 | import * as CommandReceiptStore from "./CommandReceiptStore.ts"; |
| 31 | import * as EffectOutbox from "./EffectOutbox.ts"; |
| 32 | import * as EventSink from "./EventSink.ts"; |
| 33 | import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; |
| 34 | import * as ThreadManagement from "./ThreadManagementService.ts"; |
| 35 | import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts"; |
| 36 | import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; |
| 37 | import { placeholderThreadTitle } from "./placeholderThreadTitle.ts"; |
| 38 | import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 39 | |
| 40 | const projectId = ProjectId.make("project:title-regeneration"); |
| 41 | const modelSelection = { |
| 42 | instanceId: ProviderInstanceId.make("codex"), |
| 43 | model: "gpt-5.1-codex", |
| 44 | } as const; |
| 45 | |
| 46 | const adapter = { |
| 47 | instanceId: modelSelection.instanceId, |
| 48 | driver: ProviderDriverKind.make("codex"), |
| 49 | getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), |
| 50 | planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), |
| 51 | openSession: () => Effect.die("provider execution is disabled in title regeneration tests"), |
| 52 | } as ProviderAdapter.ProviderAdapterV2["Service"]; |
| 53 | |
| 54 | function makeHarness( |
| 55 | options: { |
| 56 | readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"]; |
| 57 | } = {}, |
| 58 | ) { |
| 59 | const layerDatabase = SqlitePersistence.layerMemory; |
| 60 | const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([adapter]); |
| 61 | const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( |
| 62 | { name: "thread-title-regeneration" }, |
| 63 | layerRegistry, |
| 64 | { databaseLayer: layerDatabase, runEffectWorker: false }, |
| 65 | ); |
| 66 | const layerServerSettings = ServerSettings.layerTest({}); |
| 67 | const layerThreadManagement = ThreadManagement.layer.pipe( |
| 68 | Layer.provide(layerOrchestrator), |
| 69 | Layer.provide(layerServerSettings), |
| 70 | Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), |
| 71 | ); |
| 72 | const layerOutbox = EffectOutbox.layer.pipe(Layer.provide(layerDatabase)); |
| 73 | const generateThreadTitle = vi.fn( |
| 74 | options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })), |
| 75 | ); |
| 76 | const layerProjectedProjects = Layer.mock(ProjectStore.ProjectStoreV2)({ |
| 77 | get: (requestedProjectId) => |
| 78 | Effect.succeed( |
| 79 | requestedProjectId === projectId |
| 80 | ? Option.some({ |
| 81 | projectId, |
| 82 | title: "Project", |
| 83 | workspaceRoot: "/repo", |
| 84 | defaultModelSelection: modelSelection, |
| 85 | defaultThreadEnvMode: null, |
| 86 | hasCustomTitle: false, |
| 87 | autoPull: false, |
| 88 | faviconPath: null, |
| 89 | projectIcon: null, |
| 90 | scripts: [], |
| 91 | pinnedAt: null, |
| 92 | archivedAt: null, |
| 93 | createdAt: "2026-06-20T00:00:00.000Z", |
| 94 | updatedAt: "2026-06-20T00:00:00.000Z", |
| 95 | deletedAt: null, |
| 96 | }) |
| 97 | : Option.none(), |
| 98 | ), |
| 99 | }); |
| 100 | const layerTitleRegeneration = ThreadTitleRegeneration.layer.pipe( |
| 101 | Layer.provide( |
| 102 | Layer.mergeAll( |
| 103 | layerThreadManagement, |
| 104 | layerProjectedProjects, |
| 105 | Layer.mock(TextGeneration.TextGeneration)({ generateThreadTitle }), |
| 106 | layerServerSettings, |
| 107 | NodeServices.layer, |
| 108 | ), |
| 109 | ), |
| 110 | ); |
| 111 | return { |
| 112 | layer: Layer.mergeAll( |
| 113 | layerOrchestrator, |
| 114 | layerThreadManagement, |
| 115 | layerTitleRegeneration, |
| 116 | layerOutbox, |
| 117 | layerDatabase, |
| 118 | ), |
| 119 | generateThreadTitle, |
| 120 | }; |
| 121 | } |
| 122 | |
| 123 | function createThread(input: { |
| 124 | readonly command: string; |
| 125 | readonly thread: string; |
| 126 | readonly worktreePath?: string; |
| 127 | }) { |
| 128 | return Effect.gen(function* () { |
| 129 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 130 | const threadId = ThreadId.make(input.thread); |
| 131 | yield* threads.dispatch({ |
| 132 | type: "thread.create", |
| 133 | commandId: CommandId.make(input.command), |
| 134 | threadId, |
| 135 | projectId, |
| 136 | title: "Seed title", |
| 137 | modelSelection, |
| 138 | runtimeMode: "full-access", |
| 139 | interactionMode: "default", |
| 140 | branch: null, |
| 141 | worktreePath: input.worktreePath ?? null, |
| 142 | createdBy: "user", |
| 143 | creationSource: "web", |
| 144 | }); |
| 145 | return threadId; |
| 146 | }); |
| 147 | } |
| 148 | |
| 149 | function dispatchUserMessage(input: { |
| 150 | readonly command: string; |
| 151 | readonly threadId: ThreadId; |
| 152 | readonly text: string; |
| 153 | readonly attachments?: ReadonlyArray<ChatAttachment>; |
| 154 | }) { |
| 155 | return Effect.gen(function* () { |
| 156 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 157 | yield* threads.dispatch({ |
| 158 | type: "message.dispatch", |
| 159 | commandId: CommandId.make(input.command), |
| 160 | threadId: input.threadId, |
| 161 | messageId: MessageId.make(`${input.command}:message`), |
| 162 | text: input.text, |
| 163 | attachments: input.attachments ?? [], |
| 164 | modelSelection, |
| 165 | dispatchMode: { type: "defer_start" }, |
| 166 | createdBy: "user", |
| 167 | creationSource: "web", |
| 168 | }); |
| 169 | }); |
| 170 | } |
| 171 | |
| 172 | /** Records a settled source run with one exchange, as a provider turn would. */ |
| 173 | function recordRun(input: { |
| 174 | readonly threadId: ThreadId; |
| 175 | readonly runId: RunId; |
| 176 | readonly ordinal: number; |
| 177 | readonly user: string; |
| 178 | readonly assistant: string; |
| 179 | readonly status?: "completed" | "rolled_back"; |
| 180 | }) { |
| 181 | return Effect.gen(function* () { |
| 182 | const eventSink = yield* EventSink.EventSinkV2; |
| 183 | const now = yield* DateTime.now; |
| 184 | const providerThreadId = ProviderThreadId.make(`${input.threadId}:provider`); |
| 185 | const message = (role: "user" | "assistant", text: string) => ({ |
| 186 | id: EventId.make(`${input.runId}:${role}`), |
| 187 | type: "message.updated" as const, |
| 188 | threadId: input.threadId, |
| 189 | runId: input.runId, |
| 190 | occurredAt: now, |
| 191 | payload: { |
| 192 | id: MessageId.make(`${input.runId}:${role}`), |
| 193 | threadId: input.threadId, |
| 194 | runId: input.runId, |
| 195 | nodeId: null, |
| 196 | role, |
| 197 | text, |
| 198 | attachments: [], |
| 199 | streaming: false, |
| 200 | createdBy: "user" as const, |
| 201 | creationSource: "web" as const, |
| 202 | createdAt: now, |
| 203 | updatedAt: now, |
| 204 | }, |
| 205 | }); |
| 206 | yield* eventSink.write({ |
| 207 | events: [ |
| 208 | { |
| 209 | id: EventId.make(`${input.runId}:created`), |
| 210 | type: "run.created", |
| 211 | threadId: input.threadId, |
| 212 | runId: input.runId, |
| 213 | occurredAt: now, |
| 214 | payload: { |
| 215 | id: input.runId, |
| 216 | threadId: input.threadId, |
| 217 | ordinal: input.ordinal, |
| 218 | providerInstanceId: modelSelection.instanceId, |
| 219 | modelSelection, |
| 220 | providerThreadId, |
| 221 | userMessageId: MessageId.make(`${input.runId}:user`), |
| 222 | rootNodeId: null, |
| 223 | activeAttemptId: null, |
| 224 | status: input.status ?? "completed", |
| 225 | requestedAt: now, |
| 226 | startedAt: now, |
| 227 | completedAt: now, |
| 228 | checkpointId: null, |
| 229 | contextHandoffId: null, |
| 230 | }, |
| 231 | }, |
| 232 | { |
| 233 | id: EventId.make(`${input.runId}:provider-thread`), |
| 234 | type: "provider-thread.updated", |
| 235 | threadId: input.threadId, |
| 236 | occurredAt: now, |
| 237 | payload: { |
| 238 | id: providerThreadId, |
| 239 | driver: adapter.driver, |
| 240 | providerInstanceId: modelSelection.instanceId, |
| 241 | providerSessionId: null, |
| 242 | appThreadId: input.threadId, |
| 243 | ownerNodeId: null, |
| 244 | nativeThreadRef: { driver: adapter.driver, nativeId: "native", strength: "strong" }, |
| 245 | nativeConversationHeadRef: null, |
| 246 | status: "idle", |
| 247 | firstRunOrdinal: 1, |
| 248 | lastRunOrdinal: input.ordinal, |
| 249 | handoffIds: [], |
| 250 | forkedFrom: null, |
| 251 | createdAt: now, |
| 252 | updatedAt: now, |
| 253 | }, |
| 254 | }, |
| 255 | message("user", input.user), |
| 256 | message("assistant", input.assistant), |
| 257 | ], |
| 258 | }); |
| 259 | }); |
| 260 | } |
| 261 | |
| 262 | function armRegeneration(input: { readonly command: string; readonly threadId: ThreadId }) { |
| 263 | return Effect.gen(function* () { |
| 264 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 265 | const requestId = CommandId.make(input.command); |
| 266 | yield* threads.dispatch({ |
| 267 | type: "thread.metadata.update", |
| 268 | commandId: requestId, |
| 269 | threadId: input.threadId, |
| 270 | regenerateTitle: true, |
| 271 | }); |
| 272 | return requestId; |
| 273 | }); |
| 274 | } |
| 275 | |
| 276 | /** Forks a source thread at its middle run, between a rolled-back run and later work. */ |
| 277 | function forkSeededSource(prefix: string, sideChat = false, rollbackPriorRun = true) { |
| 278 | return Effect.gen(function* () { |
| 279 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 280 | const sourceThreadId = yield* createThread({ |
| 281 | command: `${prefix}:create`, |
| 282 | thread: `${prefix}:source`, |
| 283 | }); |
| 284 | yield* recordRun({ |
| 285 | threadId: sourceThreadId, |
| 286 | runId: RunId.make(`${prefix}:run:0`), |
| 287 | ordinal: 1, |
| 288 | user: "Rolled back attempt", |
| 289 | assistant: "Discarded.", |
| 290 | status: rollbackPriorRun ? "rolled_back" : "completed", |
| 291 | }); |
| 292 | yield* TestClock.adjust(1); |
| 293 | const forkRunId = RunId.make(`${prefix}:run:1`); |
| 294 | yield* recordRun({ |
| 295 | threadId: sourceThreadId, |
| 296 | runId: forkRunId, |
| 297 | ordinal: 2, |
| 298 | user: "Move session storage from Redis to Postgres", |
| 299 | assistant: "Sessions now persist in the Postgres sessions table.", |
| 300 | }); |
| 301 | yield* recordRun({ |
| 302 | threadId: sourceThreadId, |
| 303 | runId: RunId.make(`${prefix}:run:2`), |
| 304 | ordinal: 3, |
| 305 | user: "Later work the fork never saw", |
| 306 | assistant: "Done.", |
| 307 | }); |
| 308 | const forkThreadId = ThreadId.make(`${prefix}:target`); |
| 309 | yield* threads.dispatch({ |
| 310 | type: "thread.fork", |
| 311 | commandId: CommandId.make(`${prefix}:fork`), |
| 312 | sourceThreadId, |
| 313 | targetThreadId: forkThreadId, |
| 314 | sourcePoint: { type: "run", runId: forkRunId }, |
| 315 | sideChat, |
| 316 | createdBy: "user", |
| 317 | creationSource: "web", |
| 318 | }); |
| 319 | return { sourceThreadId, forkRunId, forkThreadId }; |
| 320 | }); |
| 321 | } |
| 322 | |
| 323 | describe("formatThreadTitleContext", () => { |
| 324 | it("pins the first user message ahead of the retained tail once content stops fitting", () => { |
| 325 | const context = ThreadTitleRegeneration.formatThreadTitleContext([ |
| 326 | { role: "user", text: `Ancient context that anchors the topic ${"x".repeat(600)}` }, |
| 327 | { role: "assistant", text: "y".repeat(6_000) }, |
| 328 | { role: "user", text: "z".repeat(1_500) }, |
| 329 | ]); |
| 330 | assert.isTrue(context.message.includes("USER:\nAncient context that anchors the topic")); |
| 331 | assert.isTrue(context.message.includes("[Earlier content truncated]\n\n")); |
| 332 | assert.isTrue(context.message.includes("y".repeat(100))); |
| 333 | }); |
| 334 | }); |
| 335 | |
| 336 | describe("ThreadTitleRegenerationService", () => { |
| 337 | it.effect("keeps a title set before the first message unless it is a placeholder", () => |
| 338 | Effect.gen(function* () { |
| 339 | const seed = "work on this and pr to dev"; |
| 340 | const harness = makeHarness(); |
| 341 | yield* Effect.gen(function* () { |
| 342 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 343 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 344 | // An MCP launch names the thread, or leaves a placeholder, and sends no message. |
| 345 | for (const [key, title, expectedTitle, generates] of [ |
| 346 | ["preset", "[API] #4821 — retry webhook deliveries after a timeout", undefined, false], |
| 347 | ["placeholder", placeholderThreadTitle("Parent", 0), seed, true], |
| 348 | ] as const) { |
| 349 | const threadId = ThreadId.make(`thread:title:${key}`); |
| 350 | yield* threads.dispatch({ |
| 351 | type: "thread.create", |
| 352 | commandId: CommandId.make(`command:title:${key}:create`), |
| 353 | threadId, |
| 354 | projectId, |
| 355 | title, |
| 356 | modelSelection, |
| 357 | runtimeMode: "full-access", |
| 358 | interactionMode: "default", |
| 359 | branch: null, |
| 360 | worktreePath: null, |
| 361 | createdBy: "agent", |
| 362 | creationSource: "mcp", |
| 363 | }); |
| 364 | const requestId = CommandId.make(`command:title:${key}:message`); |
| 365 | yield* threads.dispatch({ |
| 366 | type: "message.dispatch", |
| 367 | commandId: requestId, |
| 368 | threadId, |
| 369 | messageId: MessageId.make(`command:title:${key}:message:message`), |
| 370 | text: seed, |
| 371 | titleSeed: seed, |
| 372 | attachments: [], |
| 373 | modelSelection, |
| 374 | dispatchMode: { type: "defer_start" }, |
| 375 | createdBy: "user", |
| 376 | creationSource: "web", |
| 377 | }); |
| 378 | |
| 379 | const settled = yield* threads.getThreadProjection(threadId); |
| 380 | assert.equal(settled.thread.title, expectedTitle ?? title, key); |
| 381 | assert.equal( |
| 382 | (yield* outbox.listByCommandId(requestId)).some( |
| 383 | (effect) => effect.request.type === "thread-title.generate", |
| 384 | ), |
| 385 | generates, |
| 386 | key, |
| 387 | ); |
| 388 | } |
| 389 | }).pipe(Effect.provide(harness.layer)); |
| 390 | }), |
| 391 | ); |
| 392 | |
| 393 | it.effect("keeps a fork's own rename when its first message arrives", () => |
| 394 | Effect.gen(function* () { |
| 395 | const seed = "Try SQLite instead"; |
| 396 | const harness = makeHarness(); |
| 397 | yield* Effect.gen(function* () { |
| 398 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 399 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 400 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 401 | const prefix = "thread:title:renamed-fork"; |
| 402 | const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource(prefix); |
| 403 | const rename = (key: string, threadId: ThreadId, title: string) => |
| 404 | threads.dispatch({ |
| 405 | type: "thread.metadata.update", |
| 406 | commandId: CommandId.make(`${prefix}:${key}:rename`), |
| 407 | threadId, |
| 408 | title, |
| 409 | }); |
| 410 | const fork = (key: string) => |
| 411 | Effect.gen(function* () { |
| 412 | const targetThreadId = ThreadId.make(`${prefix}:${key}`); |
| 413 | yield* threads.dispatch({ |
| 414 | type: "thread.fork", |
| 415 | commandId: CommandId.make(`${prefix}:${key}:fork`), |
| 416 | sourceThreadId, |
| 417 | targetThreadId, |
| 418 | sourcePoint: { type: "run", runId: forkRunId }, |
| 419 | createdBy: "user", |
| 420 | creationSource: "web", |
| 421 | }); |
| 422 | return targetThreadId; |
| 423 | }); |
| 424 | yield* rename("renamed", forkThreadId, "Storage migration notes"); |
| 425 | yield* rename("source", sourceThreadId, "Renamed source"); |
| 426 | const forkOfRenamedSource = yield* fork("fork-of-renamed-source"); |
| 427 | const regenerated = yield* fork("regenerated"); |
| 428 | yield* rename("regenerated", regenerated, "Scratch name"); |
| 429 | yield* titleRegeneration.execute({ |
| 430 | threadId: regenerated, |
| 431 | requestId: yield* armRegeneration({ |
| 432 | command: `${prefix}:regenerated:regenerate`, |
| 433 | threadId: regenerated, |
| 434 | }), |
| 435 | kind: { type: "regenerate" }, |
| 436 | }); |
| 437 | |
| 438 | for (const [key, threadId, expectedTitle, generates] of [ |
| 439 | ["renamed", forkThreadId, "Storage migration notes", false], |
| 440 | ["fork of a renamed source", forkOfRenamedSource, seed, true], |
| 441 | ["renamed, then regenerated", regenerated, seed, true], |
| 442 | ] as const) { |
| 443 | const requestId = CommandId.make(`${prefix}:${key}:message`); |
| 444 | yield* threads.dispatch({ |
| 445 | type: "message.dispatch", |
| 446 | commandId: requestId, |
| 447 | threadId, |
| 448 | messageId: MessageId.make(`${prefix}:${key}:message:message`), |
| 449 | text: seed, |
| 450 | titleSeed: seed, |
| 451 | attachments: [], |
| 452 | modelSelection, |
| 453 | dispatchMode: { type: "defer_start" }, |
| 454 | createdBy: "user", |
| 455 | creationSource: "web", |
| 456 | }); |
| 457 | |
| 458 | const settled = yield* threads.getThreadProjection(threadId); |
| 459 | assert.equal(settled.thread.title, expectedTitle, key); |
| 460 | assert.equal( |
| 461 | (yield* outbox.listByCommandId(requestId)).some( |
| 462 | (effect) => effect.request.type === "thread-title.generate", |
| 463 | ), |
| 464 | generates, |
| 465 | key, |
| 466 | ); |
| 467 | } |
| 468 | }).pipe(Effect.provide(harness.layer)); |
| 469 | }), |
| 470 | ); |
| 471 | |
| 472 | it.effect( |
| 473 | "titles an image-only first message without sending bootstrap text to the title model", |
| 474 | () => |
| 475 | Effect.gen(function* () { |
| 476 | for (const prefix of ["", "Ultrathink:\n"]) { |
| 477 | const harness = makeHarness(); |
| 478 | yield* Effect.gen(function* () { |
| 479 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 480 | const service = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 481 | const threadId = yield* createThread({ |
| 482 | command: "image:create", |
| 483 | thread: "image:thread", |
| 484 | }); |
| 485 | const text = prefix + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT; |
| 486 | const attachments = [ |
| 487 | { |
| 488 | type: "image" as const, |
| 489 | id: ChatAttachmentId.make("diagram"), |
| 490 | name: "diagram.png", |
| 491 | mimeType: "image/png", |
| 492 | sizeBytes: 10, |
| 493 | }, |
| 494 | ]; |
| 495 | yield* dispatchUserMessage({ command: "image:message", threadId, text, attachments }); |
| 496 | const requestId = yield* armRegeneration({ command: "image:title", threadId }); |
| 497 | const messageId = MessageId.make("image:message:message"); |
| 498 | yield* service.execute({ threadId, requestId, kind: { type: "initial", messageId } }); |
| 499 | const call = harness.generateThreadTitle.mock.calls[0]?.[0]; |
| 500 | assert.equal(call?.message, ""); |
| 501 | assert.deepEqual(call?.attachments, attachments); |
| 502 | const projection = yield* threads.getThreadProjection(threadId); |
| 503 | assert.equal(projection.messages[0]?.text, text); |
| 504 | assert.equal(projection.thread.title, "Generated title"); |
| 505 | }).pipe(Effect.provide(harness.layer)); |
| 506 | } |
| 507 | }), |
| 508 | ); |
| 509 | |
| 510 | it.effect("arms and clears the regeneration marker through metadata commands", () => |
| 511 | Effect.gen(function* () { |
| 512 | const harness = makeHarness(); |
| 513 | yield* Effect.gen(function* () { |
| 514 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 515 | const outbox = yield* EffectOutbox.EffectOutboxV2; |
| 516 | const threadId = yield* createThread({ |
| 517 | command: "command:title:arm:create", |
| 518 | thread: "thread:title:arm", |
| 519 | }); |
| 520 | |
| 521 | const firstRequest = yield* armRegeneration({ command: "command:title:arm:1", threadId }); |
| 522 | const armed = yield* threads.getThreadProjection(threadId); |
| 523 | assert.equal(armed.thread.titleRegeneration?.requestId, firstRequest); |
| 524 | assert.deepEqual( |
| 525 | (yield* outbox.listByCommandId(firstRequest)).map((effect) => effect.request), |
| 526 | [{ type: "thread-title.generate", kind: { type: "regenerate" } }], |
| 527 | ); |
| 528 | |
| 529 | yield* threads.dispatch({ |
| 530 | type: "thread.metadata.update", |
| 531 | commandId: CommandId.make("command:title:arm:abandon"), |
| 532 | threadId, |
| 533 | regenerateTitle: false, |
| 534 | }); |
| 535 | const abandoned = yield* threads.getThreadProjection(threadId); |
| 536 | assert.isNotOk(abandoned.thread.titleRegeneration); |
| 537 | |
| 538 | yield* armRegeneration({ command: "command:title:arm:2", threadId }); |
| 539 | yield* threads.dispatch({ |
| 540 | type: "thread.metadata.update", |
| 541 | commandId: CommandId.make("command:title:arm:rename"), |
| 542 | threadId, |
| 543 | title: "Manual title", |
| 544 | }); |
| 545 | const renamed = yield* threads.getThreadProjection(threadId); |
| 546 | assert.equal(renamed.thread.title, "Manual title"); |
| 547 | assert.isNotOk(renamed.thread.titleRegeneration); |
| 548 | }).pipe(Effect.provide(harness.layer)); |
| 549 | }), |
| 550 | ); |
| 551 | |
| 552 | it.effect("skips execution when the marker was superseded by a newer request", () => |
| 553 | Effect.gen(function* () { |
| 554 | const harness = makeHarness(); |
| 555 | yield* Effect.gen(function* () { |
| 556 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 557 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 558 | const threadId = yield* createThread({ |
| 559 | command: "command:title:stale:create", |
| 560 | thread: "thread:title:stale", |
| 561 | }); |
| 562 | const staleRequest = yield* armRegeneration({ command: "command:title:stale:1", threadId }); |
| 563 | const currentRequest = yield* armRegeneration({ |
| 564 | command: "command:title:stale:2", |
| 565 | threadId, |
| 566 | }); |
| 567 | |
| 568 | yield* titleRegeneration.execute({ |
| 569 | threadId, |
| 570 | requestId: staleRequest, |
| 571 | kind: { type: "regenerate" }, |
| 572 | }); |
| 573 | |
| 574 | assert.equal(harness.generateThreadTitle.mock.calls.length, 0); |
| 575 | const projection = yield* threads.getThreadProjection(threadId); |
| 576 | assert.equal(projection.thread.title, "Seed title"); |
| 577 | assert.equal(projection.thread.titleRegeneration?.requestId, currentRequest); |
| 578 | }).pipe(Effect.provide(harness.layer)); |
| 579 | }), |
| 580 | ); |
| 581 | |
| 582 | it.effect("lands the regenerated title from the conversation digest", () => |
| 583 | Effect.gen(function* () { |
| 584 | const harness = makeHarness({ |
| 585 | generateTitle: () => Effect.succeed({ title: "Fresh title" }), |
| 586 | }); |
| 587 | const fs = yield* FileSystem.FileSystem; |
| 588 | const existingWorktree = yield* fs.makeTempDirectoryScoped({ prefix: "title-worktree-" }); |
| 589 | yield* Effect.gen(function* () { |
| 590 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 591 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 592 | const cases = [ |
| 593 | { name: "removed", worktreePath: "/repo-worktrees/removed-by-cleanup", cwd: "/repo" }, |
| 594 | { name: "existing", worktreePath: existingWorktree, cwd: existingWorktree }, |
| 595 | ]; |
| 596 | for (const [index, testCase] of cases.entries()) { |
| 597 | const threadId = yield* createThread({ |
| 598 | command: `command:title:landing:${testCase.name}:create`, |
| 599 | thread: `thread:title:landing:${testCase.name}`, |
| 600 | worktreePath: testCase.worktreePath, |
| 601 | }); |
| 602 | yield* dispatchUserMessage({ |
| 603 | command: `command:title:landing:${testCase.name}:message`, |
| 604 | threadId, |
| 605 | text: "Investigate the flaky login test", |
| 606 | }); |
| 607 | const requestId = yield* armRegeneration({ |
| 608 | command: `command:title:landing:${testCase.name}:1`, |
| 609 | threadId, |
| 610 | }); |
| 611 | |
| 612 | yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } }); |
| 613 | |
| 614 | const call = harness.generateThreadTitle.mock.calls[index]?.[0]; |
| 615 | assert.equal(call?.previousTitle, "Seed title"); |
| 616 | assert.equal(call?.cwd, testCase.cwd); |
| 617 | assert.include(call?.message, "USER:\nInvestigate the flaky login test"); |
| 618 | const projection = yield* threads.getThreadProjection(threadId); |
| 619 | assert.equal(projection.thread.title, "Fresh title"); |
| 620 | assert.isNotOk(projection.thread.titleRegeneration); |
| 621 | assert.deepInclude(projection.thread.lastTitleRegeneration, { |
| 622 | requestId, |
| 623 | status: "renamed", |
| 624 | }); |
| 625 | } |
| 626 | }).pipe(Effect.provide(harness.layer)); |
| 627 | }).pipe(Effect.provide(NodeServices.layer)), |
| 628 | ); |
| 629 | |
| 630 | it.effect.each([ |
| 631 | { name: "its first message", followUp: true }, |
| 632 | { name: "no message of its own yet", followUp: false }, |
| 633 | ])("titles a fork with $name from the source history up to the fork point", ({ followUp }) => |
| 634 | Effect.gen(function* () { |
| 635 | const harness = makeHarness(); |
| 636 | yield* Effect.gen(function* () { |
| 637 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 638 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 639 | const { forkThreadId } = yield* forkSeededSource("thread:title:fork"); |
| 640 | const requestId = CommandId.make("command:title:fork:request"); |
| 641 | const messageId = MessageId.make("command:title:fork:request:message"); |
| 642 | if (followUp) { |
| 643 | yield* threads.dispatch({ |
| 644 | type: "message.dispatch", |
| 645 | commandId: requestId, |
| 646 | threadId: forkThreadId, |
| 647 | messageId, |
| 648 | text: "Try SQLite instead", |
| 649 | titleSeed: "Try SQLite instead", |
| 650 | attachments: [], |
| 651 | modelSelection, |
| 652 | dispatchMode: { type: "defer_start" }, |
| 653 | createdBy: "user", |
| 654 | creationSource: "web", |
| 655 | }); |
| 656 | } else { |
| 657 | yield* armRegeneration({ command: requestId, threadId: forkThreadId }); |
| 658 | } |
| 659 | |
| 660 | yield* titleRegeneration.execute({ |
| 661 | threadId: forkThreadId, |
| 662 | requestId, |
| 663 | kind: followUp ? { type: "initial", messageId } : { type: "regenerate" }, |
| 664 | }); |
| 665 | |
| 666 | const call = harness.generateThreadTitle.mock.calls[0]?.[0]; |
| 667 | assert.equal(call?.message, followUp ? "Try SQLite instead" : ""); |
| 668 | assert.equal(call?.forkSource?.title, "Seed title"); |
| 669 | assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres"); |
| 670 | assert.include(call?.forkSource?.history, "Sessions now persist in the Postgres"); |
| 671 | assert.notInclude(call?.forkSource?.history, "Later work the fork never saw"); |
| 672 | assert.notInclude(call?.forkSource?.history, "Rolled back attempt"); |
| 673 | const fork = yield* threads.getThreadRecords(forkThreadId, []); |
| 674 | assert.equal(fork.thread.title, "Generated title"); |
| 675 | }).pipe(Effect.provide(harness.layer)); |
| 676 | }), |
| 677 | ); |
| 678 | |
| 679 | it.effect.each(["plain", "deleted source"] as const)( |
| 680 | "refuses to title an empty thread with %s history", |
| 681 | (history) => |
| 682 | Effect.gen(function* () { |
| 683 | const harness = makeHarness(); |
| 684 | yield* Effect.gen(function* () { |
| 685 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 686 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 687 | const { forkThreadId } = yield* forkSeededSource("thread:title:empty"); |
| 688 | const { thread } = yield* threads.getThreadProjection(forkThreadId); |
| 689 | const eventSink = yield* EventSink.EventSinkV2; |
| 690 | yield* eventSink.write({ |
| 691 | events: [ |
| 692 | { |
| 693 | id: EventId.make("empty:lineage"), |
| 694 | type: "thread.metadata-updated", |
| 695 | threadId: forkThreadId, |
| 696 | occurredAt: yield* DateTime.now, |
| 697 | payload: { |
| 698 | ...thread, |
| 699 | forkedFrom: |
| 700 | history === "plain" |
| 701 | ? null |
| 702 | : { |
| 703 | type: "run", |
| 704 | threadId: ThreadId.make("absent"), |
| 705 | runId: RunId.make("absent"), |
| 706 | }, |
| 707 | }, |
| 708 | }, |
| 709 | ], |
| 710 | }); |
| 711 | const requestId = yield* armRegeneration({ |
| 712 | command: "empty:request", |
| 713 | threadId: forkThreadId, |
| 714 | }); |
| 715 | yield* titleRegeneration.execute({ |
| 716 | threadId: forkThreadId, |
| 717 | requestId, |
| 718 | kind: { type: "regenerate" }, |
| 719 | }); |
| 720 | assert.equal(harness.generateThreadTitle.mock.calls.length, 0); |
| 721 | const fork = yield* threads.getThreadRecords(forkThreadId, []); |
| 722 | assert.deepInclude(fork.thread.lastTitleRegeneration, { |
| 723 | requestId, |
| 724 | status: "failed", |
| 725 | message: "This thread has no messages to title yet.", |
| 726 | }); |
| 727 | }).pipe(Effect.provide(harness.layer)); |
| 728 | }), |
| 729 | ); |
| 730 | |
| 731 | it.effect("keeps the fork point when the source rolls it back after forking", () => |
| 732 | Effect.gen(function* () { |
| 733 | const harness = makeHarness(); |
| 734 | yield* Effect.gen(function* () { |
| 735 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 736 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 737 | const { sourceThreadId, forkRunId, forkThreadId } = yield* forkSeededSource( |
| 738 | "thread:title:rollback", |
| 739 | false, |
| 740 | false, |
| 741 | ); |
| 742 | yield* TestClock.adjust(1); |
| 743 | const source = yield* threads.getThreadRecords(sourceThreadId, ["runs"]); |
| 744 | const run = source.runs.find((run) => run.id === forkRunId); |
| 745 | assert.isDefined(run); |
| 746 | const now = yield* DateTime.now; |
| 747 | const eventSink = yield* EventSink.EventSinkV2; |
| 748 | yield* eventSink.write({ |
| 749 | events: [ |
| 750 | { |
| 751 | id: EventId.make("source:rollback"), |
| 752 | type: "run.updated", |
| 753 | threadId: sourceThreadId, |
| 754 | runId: run.id, |
| 755 | occurredAt: now, |
| 756 | payload: { ...run, status: "rolled_back", completedAt: now }, |
| 757 | }, |
| 758 | ], |
| 759 | }); |
| 760 | const requestId = yield* armRegeneration({ |
| 761 | command: "rollback:request", |
| 762 | threadId: forkThreadId, |
| 763 | }); |
| 764 | yield* titleRegeneration.execute({ |
| 765 | threadId: forkThreadId, |
| 766 | requestId, |
| 767 | kind: { type: "regenerate" }, |
| 768 | }); |
| 769 | const call = harness.generateThreadTitle.mock.calls[0]?.[0]; |
| 770 | assert.include(call?.forkSource?.history, "Move session storage from Redis to Postgres"); |
| 771 | assert.include(call?.forkSource?.history, "Rolled back attempt"); |
| 772 | assert.notInclude(call?.forkSource?.history, "Later work the fork never saw"); |
| 773 | const fork = yield* threads.getThreadRecords(forkThreadId, []); |
| 774 | assert.equal(fork.thread.title, "Generated title"); |
| 775 | }).pipe(Effect.provide(harness.layer)); |
| 776 | }), |
| 777 | ); |
| 778 | |
| 779 | it.effect("does not inherit imported history when the fork point is missing", () => |
| 780 | Effect.gen(function* () { |
| 781 | const harness = makeHarness(); |
| 782 | yield* Effect.gen(function* () { |
| 783 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 784 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 785 | const { sourceThreadId, forkThreadId } = yield* forkSeededSource("thread:title:invalid"); |
| 786 | yield* dispatchUserMessage({ |
| 787 | command: "imported:message", |
| 788 | threadId: sourceThreadId, |
| 789 | text: "Imported history", |
| 790 | }); |
| 791 | const source = yield* threads.getThreadRecords(sourceThreadId, []); |
| 792 | const fork = yield* threads.getThreadRecords(forkThreadId, []); |
| 793 | const eventSink = yield* EventSink.EventSinkV2; |
| 794 | yield* eventSink.write({ |
| 795 | events: [ |
| 796 | { |
| 797 | id: EventId.make("source:imported"), |
| 798 | type: "thread.metadata-updated", |
| 799 | threadId: sourceThreadId, |
| 800 | occurredAt: yield* DateTime.now, |
| 801 | payload: { ...source.thread, historyOrigin: "v1_import" }, |
| 802 | }, |
| 803 | { |
| 804 | id: EventId.make("fork:missing-run"), |
| 805 | type: "thread.metadata-updated", |
| 806 | threadId: forkThreadId, |
| 807 | occurredAt: yield* DateTime.now, |
| 808 | payload: { |
| 809 | ...fork.thread, |
| 810 | forkedFrom: { |
| 811 | type: "run", |
| 812 | threadId: sourceThreadId, |
| 813 | runId: RunId.make("absent:run"), |
| 814 | }, |
| 815 | }, |
| 816 | }, |
| 817 | ], |
| 818 | }); |
| 819 | const requestId = yield* armRegeneration({ |
| 820 | command: "invalid:request", |
| 821 | threadId: forkThreadId, |
| 822 | }); |
| 823 | yield* titleRegeneration.execute({ |
| 824 | threadId: forkThreadId, |
| 825 | requestId, |
| 826 | kind: { type: "regenerate" }, |
| 827 | }); |
| 828 | assert.equal(harness.generateThreadTitle.mock.calls.length, 0); |
| 829 | const updated = yield* threads.getThreadRecords(forkThreadId, []); |
| 830 | assert.deepInclude(updated.thread.lastTitleRegeneration, { |
| 831 | requestId, |
| 832 | status: "failed", |
| 833 | message: "This thread has no messages to title yet.", |
| 834 | }); |
| 835 | }).pipe(Effect.provide(harness.layer)); |
| 836 | }), |
| 837 | ); |
| 838 | |
| 839 | it.effect("inherits a side chat's own exchange without its parent's history", () => |
| 840 | Effect.gen(function* () { |
| 841 | const harness = makeHarness(); |
| 842 | yield* Effect.gen(function* () { |
| 843 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 844 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 845 | const { forkThreadId: sideChatId } = yield* forkSeededSource( |
| 846 | "thread:title:side-ancestor", |
| 847 | true, |
| 848 | ); |
| 849 | const runId = RunId.make("side:run"); |
| 850 | yield* recordRun({ |
| 851 | threadId: sideChatId, |
| 852 | runId, |
| 853 | ordinal: 1, |
| 854 | user: "Side topic", |
| 855 | assistant: "Side answer", |
| 856 | }); |
| 857 | const threadId = ThreadId.make("side:fork"); |
| 858 | yield* threads.dispatch({ |
| 859 | type: "thread.fork", |
| 860 | commandId: CommandId.make("side:fork"), |
| 861 | sourceThreadId: sideChatId, |
| 862 | targetThreadId: threadId, |
| 863 | sourcePoint: { type: "run", runId }, |
| 864 | title: "Side fork", |
| 865 | createdBy: "user", |
| 866 | creationSource: "web", |
| 867 | }); |
| 868 | const requestId = yield* armRegeneration({ command: "side:request", threadId }); |
| 869 | yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } }); |
| 870 | const call = harness.generateThreadTitle.mock.calls[0]?.[0]; |
| 871 | assert.equal(call?.forkSource?.title, "Seed title fork"); |
| 872 | assert.include(call?.forkSource?.history, "Side topic"); |
| 873 | assert.include(call?.forkSource?.history, "Side answer"); |
| 874 | assert.notInclude(call?.forkSource?.history, "Move session storage"); |
| 875 | }).pipe(Effect.provide(harness.layer)); |
| 876 | }), |
| 877 | ); |
| 878 | |
| 879 | it.effect("clears the marker and keeps the title when generation fails", () => |
| 880 | Effect.gen(function* () { |
| 881 | const harness = makeHarness({ |
| 882 | generateTitle: () => |
| 883 | Effect.fail( |
| 884 | new TextGenerationError({ |
| 885 | operation: "generateThreadTitle", |
| 886 | detail: |
| 887 | "Codex CLI command failed: OpenAI Codex\nuser\nConversation text\nmodel unavailable\n", |
| 888 | }), |
| 889 | ), |
| 890 | }); |
| 891 | yield* Effect.gen(function* () { |
| 892 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 893 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 894 | const threadId = yield* createThread({ |
| 895 | command: "command:title:failure:create", |
| 896 | thread: "thread:title:failure", |
| 897 | }); |
| 898 | yield* dispatchUserMessage({ |
| 899 | command: "command:title:failure:message", |
| 900 | threadId, |
| 901 | text: "Some conversation", |
| 902 | }); |
| 903 | const requestId = yield* armRegeneration({ command: "command:title:failure:1", threadId }); |
| 904 | |
| 905 | yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } }); |
| 906 | |
| 907 | assert.equal(harness.generateThreadTitle.mock.calls.length, 1); |
| 908 | const projection = yield* threads.getThreadProjection(threadId); |
| 909 | assert.equal(projection.thread.title, "Seed title"); |
| 910 | assert.isNotOk(projection.thread.titleRegeneration); |
| 911 | assert.deepInclude(projection.thread.lastTitleRegeneration, { |
| 912 | requestId, |
| 913 | status: "failed", |
| 914 | message: "model unavailable", |
| 915 | }); |
| 916 | }).pipe(Effect.provide(harness.layer)); |
| 917 | }), |
| 918 | ); |
| 919 | |
| 920 | it.effect("records an unchanged outcome when the model keeps the current title", () => |
| 921 | Effect.gen(function* () { |
| 922 | const harness = makeHarness({ |
| 923 | generateTitle: () => Effect.succeed({ title: "Seed title" }), |
| 924 | }); |
| 925 | yield* Effect.gen(function* () { |
| 926 | const threads = yield* ThreadManagement.ThreadManagementService; |
| 927 | const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; |
| 928 | const threadId = yield* createThread({ |
| 929 | command: "command:title:unchanged:create", |
| 930 | thread: "thread:title:unchanged", |
| 931 | }); |
| 932 | yield* dispatchUserMessage({ |
| 933 | command: "command:title:unchanged:message", |
| 934 | threadId, |
| 935 | text: "Some conversation", |
| 936 | }); |
| 937 | const requestId = yield* armRegeneration({ |
| 938 | command: "command:title:unchanged:1", |
| 939 | threadId, |
| 940 | }); |
| 941 | |
| 942 | yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } }); |
| 943 | |
| 944 | const projection = yield* threads.getThreadProjection(threadId); |
| 945 | assert.deepInclude(projection.thread.lastTitleRegeneration, { |
| 946 | requestId, |
| 947 | status: "unchanged", |
| 948 | }); |
| 949 | }).pipe(Effect.provide(harness.layer)); |
| 950 | }), |
| 951 | ); |
| 952 | }); |