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 { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; |
| 2 | import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/state/threads"; |
| 3 | import { |
| 4 | applyShellStreamEvent, |
| 5 | createEnvironmentSnapshotAtom, |
| 6 | EMPTY_SHELL_STATE, |
| 7 | type EnvironmentShellState, |
| 8 | type EnvironmentShellStatus, |
| 9 | } from "@t3tools/client-runtime/state/shell"; |
| 10 | import { makeThreadProjectionFixture } from "./test-fixtures"; |
| 11 | import * as Option from "effect/Option"; |
| 12 | import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 13 | import { |
| 14 | scopedProjectKey, |
| 15 | scopedThreadKey, |
| 16 | scopeProjectRef, |
| 17 | scopeThreadRef, |
| 18 | } from "@t3tools/client-runtime/environment"; |
| 19 | import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; |
| 20 | import { |
| 21 | defaultInstanceIdForDriver, |
| 22 | DEFAULT_MODEL, |
| 23 | DEFAULT_MODEL_BY_PROVIDER, |
| 24 | EnvironmentId, |
| 25 | ProjectId, |
| 26 | ProviderDriverKind, |
| 27 | ProviderInstanceId, |
| 28 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 29 | RunId, |
| 30 | ThreadId, |
| 31 | type OrchestrationV2ThreadShell, |
| 32 | type OrchestrationV2ShellSnapshot, |
| 33 | type ModelSelection, |
| 34 | type PreviewAnnotationPayload, |
| 35 | type ProviderOptionSelection, |
| 36 | type ScopedThreadRef, |
| 37 | type ServerProvider, |
| 38 | } from "@t3tools/contracts"; |
| 39 | import { createModelSelection } from "@t3tools/shared/model"; |
| 40 | |
| 41 | const CODEX_INSTANCE = ProviderInstanceId.make("codex"); |
| 42 | const CODEX_SECONDARY_INSTANCE = ProviderInstanceId.make("codex_secondary"); |
| 43 | const CLAUDE_AGENT_INSTANCE = ProviderInstanceId.make("claudeAgent"); |
| 44 | const CURSOR_INSTANCE = ProviderInstanceId.make("cursor"); |
| 45 | const CODEX_DRIVER = ProviderDriverKind.make("codex"); |
| 46 | const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); |
| 47 | const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); |
| 48 | |
| 49 | type ProviderOptionSelectionBag = ReadonlyArray<ProviderOptionSelection>; |
| 50 | type ProviderOptionSelectionsByProvider = Partial<Record<string, ProviderOptionSelectionBag>>; |
| 51 | |
| 52 | function toSelections( |
| 53 | options: Record<string, string | boolean | undefined> | undefined, |
| 54 | ): ReadonlyArray<ProviderOptionSelection> { |
| 55 | const result: Array<ProviderOptionSelection> = []; |
| 56 | if (!options) return result; |
| 57 | for (const [id, value] of Object.entries(options)) { |
| 58 | if (typeof value === "string" || typeof value === "boolean") { |
| 59 | result.push({ id, value }); |
| 60 | } |
| 61 | } |
| 62 | return result; |
| 63 | } |
| 64 | |
| 65 | function selectionsByProvider( |
| 66 | options: Partial<Record<ProviderDriverKind, Record<string, string | boolean | undefined>>>, |
| 67 | ): ProviderOptionSelectionsByProvider { |
| 68 | const result: ProviderOptionSelectionsByProvider = {}; |
| 69 | for (const [provider, bag] of Object.entries(options) as Array< |
| 70 | [ProviderDriverKind, Record<string, string | boolean | undefined>] |
| 71 | >) { |
| 72 | result[provider] = toSelections(bag); |
| 73 | } |
| 74 | return result; |
| 75 | } |
| 76 | import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test"; |
| 77 | import { createMemoryStorage } from "./lib/storage"; |
| 78 | |
| 79 | import { |
| 80 | COMPOSER_DRAFT_STORAGE_KEY, |
| 81 | subscribeComposerDraftModelReconciliation, |
| 82 | deriveEffectiveComposerModelState, |
| 83 | checkoutPullRequestUrlToLink, |
| 84 | clearComposerDraftsEnvironment, |
| 85 | beginBackgroundDraftSubmissionByRef, |
| 86 | clearBackgroundDraftSubmissionByRef, |
| 87 | finalizePromotedDraftThreadByRef, |
| 88 | markPromotedDraftThreadByRef, |
| 89 | resolveDraftPromotionNavigationTarget, |
| 90 | restoreFailedDraftThread, |
| 91 | subscribeDraftThreadPromotion, |
| 92 | type ComposerFileAttachment, |
| 93 | type ComposerImageAttachment, |
| 94 | composerFileNeedsReattach, |
| 95 | hydrateImagesFromPersisted, |
| 96 | partializeComposerDraftStoreState, |
| 97 | useComposerDraftStore, |
| 98 | DraftId, |
| 99 | } from "./composerDraftStore"; |
| 100 | import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition"; |
| 101 | import { insertInlineContextReference } from "./lib/composerContextReferences"; |
| 102 | import { |
| 103 | buildMessageContext, |
| 104 | environmentContextRecord, |
| 105 | terminalContextReference, |
| 106 | } from "./lib/composerContextRecords"; |
| 107 | import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; |
| 108 | import { |
| 109 | copiedComposerAttachmentFile, |
| 110 | rememberCopiedComposerAttachments, |
| 111 | } from "./lib/copiedComposerAttachments"; |
| 112 | import { formatTerminalContextReference, type TerminalContextDraft } from "./lib/terminalContext"; |
| 113 | import { createDeferredStorage } from "./lib/storage"; |
| 114 | import { applyPreviewServerSnapshot, resetPreviewStateForTests } from "./previewStateStore"; |
| 115 | |
| 116 | function makeImage(input: { |
| 117 | id: string; |
| 118 | previewUrl: string; |
| 119 | name?: string; |
| 120 | mimeType?: string; |
| 121 | sizeBytes?: number; |
| 122 | lastModified?: number; |
| 123 | }): ComposerImageAttachment { |
| 124 | const name = input.name ?? "image.png"; |
| 125 | const mimeType = input.mimeType ?? "image/png"; |
| 126 | const sizeBytes = input.sizeBytes ?? 4; |
| 127 | const lastModified = input.lastModified ?? 1_700_000_000_000; |
| 128 | const file = new File([new Uint8Array(sizeBytes).fill(1)], name, { |
| 129 | type: mimeType, |
| 130 | lastModified, |
| 131 | }); |
| 132 | return { |
| 133 | type: "image", |
| 134 | id: input.id, |
| 135 | name, |
| 136 | mimeType, |
| 137 | sizeBytes: file.size, |
| 138 | previewUrl: input.previewUrl, |
| 139 | file, |
| 140 | }; |
| 141 | } |
| 142 | |
| 143 | function makeFile(id: string): ComposerFileAttachment { |
| 144 | const file = new File(["report"], "report.pdf", { type: "application/pdf" }); |
| 145 | return { |
| 146 | type: "file", |
| 147 | id, |
| 148 | name: file.name, |
| 149 | mimeType: file.type, |
| 150 | sizeBytes: file.size, |
| 151 | file, |
| 152 | }; |
| 153 | } |
| 154 | |
| 155 | function makeTerminalContext(input: { |
| 156 | id: string; |
| 157 | text?: string; |
| 158 | terminalId?: string; |
| 159 | terminalLabel?: string; |
| 160 | lineStart?: number; |
| 161 | lineEnd?: number; |
| 162 | }): TerminalContextDraft { |
| 163 | return { |
| 164 | id: input.id, |
| 165 | threadId: ThreadId.make("thread-dedupe"), |
| 166 | terminalId: input.terminalId ?? "default", |
| 167 | terminalLabel: input.terminalLabel ?? "Terminal 1", |
| 168 | lineStart: input.lineStart ?? 4, |
| 169 | lineEnd: input.lineEnd ?? 5, |
| 170 | text: input.text ?? "git status\nOn branch main", |
| 171 | createdAt: "2026-03-13T12:00:00.000Z", |
| 172 | }; |
| 173 | } |
| 174 | |
| 175 | function resetComposerDraftStore() { |
| 176 | useComposerDraftStore.setState({ |
| 177 | rewindingThreadKeys: new Set(), |
| 178 | draftsByThreadKey: {}, |
| 179 | draftThreadsByThreadKey: {}, |
| 180 | logicalProjectDraftThreadKeyByLogicalProjectKey: {}, |
| 181 | backgroundSubmissionThreadKeys: {}, |
| 182 | promotedDraftRedirects: {}, |
| 183 | stickyModelSelectionByProvider: {}, |
| 184 | stickyOptionsByModelByProvider: {}, |
| 185 | stickyActiveProvider: null, |
| 186 | }); |
| 187 | } |
| 188 | |
| 189 | function modelSelection( |
| 190 | provider: ProviderDriverKind, |
| 191 | model: string, |
| 192 | options?: Record<string, string | boolean | undefined>, |
| 193 | ): ModelSelection { |
| 194 | return createModelSelection(defaultInstanceIdForDriver(provider), model, toSelections(options)); |
| 195 | } |
| 196 | |
| 197 | function providerModelOptions( |
| 198 | options: Partial<Record<string, Record<string, string | boolean | undefined>>>, |
| 199 | ): ProviderOptionSelectionsByProvider { |
| 200 | return selectionsByProvider(options); |
| 201 | } |
| 202 | |
| 203 | const TEST_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); |
| 204 | const OTHER_TEST_ENVIRONMENT_ID = EnvironmentId.make("environment-remote"); |
| 205 | const LEGACY_TEST_ENVIRONMENT_ID = EnvironmentId.make("__legacy__"); |
| 206 | |
| 207 | function threadKeyFor( |
| 208 | threadId: ThreadId, |
| 209 | environmentId: EnvironmentId = LEGACY_TEST_ENVIRONMENT_ID, |
| 210 | ): string { |
| 211 | if (environmentId === LEGACY_TEST_ENVIRONMENT_ID) { |
| 212 | return threadId; |
| 213 | } |
| 214 | return scopedThreadKey(scopeThreadRef(environmentId, threadId)); |
| 215 | } |
| 216 | |
| 217 | function draftFor(threadId: ThreadId, environmentId: EnvironmentId = LEGACY_TEST_ENVIRONMENT_ID) { |
| 218 | const store = useComposerDraftStore.getState().draftsByThreadKey; |
| 219 | return store[threadKeyFor(threadId, environmentId)] ?? store[threadId] ?? undefined; |
| 220 | } |
| 221 | |
| 222 | function draftByKey(key: string) { |
| 223 | return useComposerDraftStore.getState().draftsByThreadKey[key] ?? undefined; |
| 224 | } |
| 225 | |
| 226 | describe("composerDraftStore addImages", () => { |
| 227 | const threadId = ThreadId.make("thread-dedupe"); |
| 228 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 229 | let originalRevokeObjectUrl: typeof URL.revokeObjectURL; |
| 230 | let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>; |
| 231 | |
| 232 | beforeEach(() => { |
| 233 | resetComposerDraftStore(); |
| 234 | originalRevokeObjectUrl = URL.revokeObjectURL; |
| 235 | revokeSpy = vi.fn(); |
| 236 | URL.revokeObjectURL = revokeSpy; |
| 237 | }); |
| 238 | |
| 239 | afterEach(() => { |
| 240 | URL.revokeObjectURL = originalRevokeObjectUrl; |
| 241 | }); |
| 242 | |
| 243 | it("restores images with matching metadata without replacing unsent bytes", () => { |
| 244 | const store = useComposerDraftStore.getState(); |
| 245 | const unsent = makeImage({ id: "unsent", previewUrl: "blob:unsent" }); |
| 246 | const restored = { |
| 247 | ...unsent, |
| 248 | id: "restored", |
| 249 | previewUrl: "blob:restored", |
| 250 | file: new File([new Uint8Array(unsent.sizeBytes).fill(2)], unsent.name, { |
| 251 | type: unsent.mimeType, |
| 252 | lastModified: unsent.file.lastModified, |
| 253 | }), |
| 254 | }; |
| 255 | store.addImages(threadRef, [unsent]); |
| 256 | store.addImages(threadRef, [restored, restored], { allowDuplicates: true }); |
| 257 | |
| 258 | const images = store.getComposerDraft(threadRef)?.images; |
| 259 | expect(images?.map((image) => image.id)).toEqual(["unsent", "restored"]); |
| 260 | expect(images?.[0]?.file).toBe(unsent.file); |
| 261 | expect(images?.[1]?.file).toBe(restored.file); |
| 262 | expect(revokeSpy).not.toHaveBeenCalled(); |
| 263 | }); |
| 264 | |
| 265 | it("deduplicates byte-identical images across calls and keeps distinct bytes", () => { |
| 266 | // Hydrated copies get fresh lastModified values, like a restored stash or draft. |
| 267 | const persisted = (id: string, fill: number) => ({ |
| 268 | id, |
| 269 | name: "same.png", |
| 270 | mimeType: "image/png", |
| 271 | sizeBytes: 9, |
| 272 | dataUrl: `data:image/png;base64,${btoa(String.fromCharCode(...new Uint8Array(9).fill(fill)))}`, |
| 273 | }); |
| 274 | const [first, repeat, different] = hydrateImagesFromPersisted([ |
| 275 | persisted("img-a", 1), |
| 276 | persisted("img-b", 1), |
| 277 | persisted("img-c", 2), |
| 278 | ]); |
| 279 | const store = useComposerDraftStore.getState(); |
| 280 | |
| 281 | expect(store.addImage(threadRef, first!)).toBe(true); |
| 282 | expect(store.addImage(threadRef, { ...repeat!, previewUrl: "blob:b" })).toBe(false); |
| 283 | expect(store.addImage(threadRef, different!)).toBe(true); |
| 284 | |
| 285 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 286 | expect(draft?.images.map((image) => image.id)).toEqual(["img-a", "img-c"]); |
| 287 | expect(revokeSpy).toHaveBeenCalledWith("blob:b"); |
| 288 | }); |
| 289 | }); |
| 290 | |
| 291 | describe("composerDraftStore copied attachments", () => { |
| 292 | beforeEach(resetComposerDraftStore); |
| 293 | afterEach(() => { |
| 294 | rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map()); |
| 295 | resetComposerDraftStore(); |
| 296 | vi.restoreAllMocks(); |
| 297 | }); |
| 298 | |
| 299 | it("keeps unsent image and file bytes usable in another draft after source removal", async () => { |
| 300 | const source = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("copy-source")); |
| 301 | const target = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("copy-target")); |
| 302 | const image = makeImage({ id: "uploading-image", previewUrl: "blob:source" }); |
| 303 | const file = makeFile("uploading-file"); |
| 304 | const revoke = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); |
| 305 | const store = useComposerDraftStore.getState(); |
| 306 | store.addImages(source, [image]); |
| 307 | store.addFiles(source, [file]); |
| 308 | rememberCopiedComposerAttachments( |
| 309 | TEST_ENVIRONMENT_ID, |
| 310 | new Map([ |
| 311 | [image.id, image.file], |
| 312 | [file.id, file.file!], |
| 313 | ]), |
| 314 | ); |
| 315 | |
| 316 | store.removeImage(source, image.id); |
| 317 | store.clearComposerContent(source); |
| 318 | expect(store.getComposerDraft(source)).toBeNull(); |
| 319 | expect(revoke).toHaveBeenCalledWith(image.previewUrl); |
| 320 | |
| 321 | const copiedImage = copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, image.id); |
| 322 | const copiedFile = copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, file.id); |
| 323 | expect(copiedImage).toBe(image.file); |
| 324 | expect(copiedFile).toBe(file.file); |
| 325 | store.addImages(target, [{ ...image, file: copiedImage!, previewUrl: "blob:target" }]); |
| 326 | store.addFiles(target, [{ ...file, file: copiedFile! }]); |
| 327 | const draft = store.getComposerDraft(target)!; |
| 328 | expect([...new Uint8Array(await draft.images[0]!.file.arrayBuffer())]).toEqual([1, 1, 1, 1]); |
| 329 | expect(await draft.files[0]!.file!.text()).toBe("report"); |
| 330 | }); |
| 331 | |
| 332 | it("does not reuse bytes from another environment or a superseded clipboard copy", () => { |
| 333 | const first = makeImage({ id: "first", previewUrl: "blob:first" }); |
| 334 | const second = makeFile("second"); |
| 335 | rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map([[first.id, first.file]])); |
| 336 | expect(copiedComposerAttachmentFile(OTHER_TEST_ENVIRONMENT_ID, first.id)).toBeUndefined(); |
| 337 | |
| 338 | rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map([[second.id, second.file!]])); |
| 339 | expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, first.id)).toBeUndefined(); |
| 340 | expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, second.id)).toBe(second.file); |
| 341 | |
| 342 | rememberCopiedComposerAttachments(TEST_ENVIRONMENT_ID, new Map()); |
| 343 | expect(copiedComposerAttachmentFile(TEST_ENVIRONMENT_ID, second.id)).toBeUndefined(); |
| 344 | }); |
| 345 | }); |
| 346 | |
| 347 | describe("composerDraftStore unsent draft marker", () => { |
| 348 | const threadId = ThreadId.make("thread-unsent-marker"); |
| 349 | |
| 350 | beforeEach(() => { |
| 351 | resetComposerDraftStore(); |
| 352 | }); |
| 353 | |
| 354 | // regression: #11338 rewind locks are session-only and must not survive a reload |
| 355 | it("does not persist active rewind locks", () => { |
| 356 | const threadKey = threadKeyFor(threadId, TEST_ENVIRONMENT_ID); |
| 357 | useComposerDraftStore.setState({ rewindingThreadKeys: new Set([threadKey]) }); |
| 358 | |
| 359 | expect(useComposerDraftStore.getState().rewindingThreadKeys.has(threadKey)).toBe(true); |
| 360 | expect(partializeComposerDraftStoreState(useComposerDraftStore.getState())).not.toHaveProperty( |
| 361 | "rewindingThreadKeys", |
| 362 | ); |
| 363 | }); |
| 364 | }); |
| 365 | |
| 366 | describe("composerDraftStore file attachments", () => { |
| 367 | const threadId = ThreadId.make("thread-files"); |
| 368 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 369 | |
| 370 | beforeEach(() => { |
| 371 | resetComposerDraftStore(); |
| 372 | }); |
| 373 | |
| 374 | it("persists uploaded file references without including file contents", () => { |
| 375 | const store = useComposerDraftStore.getState(); |
| 376 | store.addFiles(threadRef, [ |
| 377 | { ...makeFile("file-1"), source: { _tag: "pasted-text" as const } }, |
| 378 | ]); |
| 379 | store.setFileUpload(threadRef, "file-1", TEST_ENVIRONMENT_ID, "pending-report-pdf"); |
| 380 | |
| 381 | const persistApi = useComposerDraftStore.persist as unknown as { |
| 382 | getOptions: () => { |
| 383 | merge: ( |
| 384 | persistedState: unknown, |
| 385 | currentState: ReturnType<typeof useComposerDraftStore.getState>, |
| 386 | ) => ReturnType<typeof useComposerDraftStore.getState>; |
| 387 | }; |
| 388 | }; |
| 389 | const options = persistApi.getOptions(); |
| 390 | const persisted = partializeComposerDraftStoreState(useComposerDraftStore.getState()); |
| 391 | |
| 392 | expect(persisted.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual( |
| 393 | [ |
| 394 | { |
| 395 | id: "file-1", |
| 396 | name: "report.pdf", |
| 397 | mimeType: "application/pdf", |
| 398 | sizeBytes: 6, |
| 399 | attachmentId: "pending-report-pdf", |
| 400 | environmentId: TEST_ENVIRONMENT_ID, |
| 401 | source: { _tag: "pasted-text" }, |
| 402 | }, |
| 403 | ], |
| 404 | ); |
| 405 | |
| 406 | const hydrated = options.merge(persisted, useComposerDraftStore.getState()); |
| 407 | expect(hydrated.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual([ |
| 408 | { |
| 409 | type: "file", |
| 410 | id: "file-1", |
| 411 | name: "report.pdf", |
| 412 | mimeType: "application/pdf", |
| 413 | sizeBytes: 6, |
| 414 | file: null, |
| 415 | uploadedAttachmentId: "pending-report-pdf", |
| 416 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 417 | source: { _tag: "pasted-text" }, |
| 418 | }, |
| 419 | ]); |
| 420 | }); |
| 421 | |
| 422 | it("persists a pending file as a needs-reattach marker instead of dropping it", () => { |
| 423 | const store = useComposerDraftStore.getState(); |
| 424 | store.addFiles(threadRef, [makeFile("file-pending")]); |
| 425 | |
| 426 | const persistApi = useComposerDraftStore.persist as unknown as { |
| 427 | getOptions: () => { |
| 428 | merge: ( |
| 429 | persistedState: unknown, |
| 430 | currentState: ReturnType<typeof useComposerDraftStore.getState>, |
| 431 | ) => ReturnType<typeof useComposerDraftStore.getState>; |
| 432 | }; |
| 433 | }; |
| 434 | const options = persistApi.getOptions(); |
| 435 | const persisted = partializeComposerDraftStoreState(useComposerDraftStore.getState()); |
| 436 | |
| 437 | expect(persisted.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual( |
| 438 | [ |
| 439 | { |
| 440 | id: "file-pending", |
| 441 | name: "report.pdf", |
| 442 | mimeType: "application/pdf", |
| 443 | sizeBytes: 6, |
| 444 | }, |
| 445 | ], |
| 446 | ); |
| 447 | |
| 448 | const hydrated = options.merge(persisted, useComposerDraftStore.getState()); |
| 449 | const hydratedFiles = |
| 450 | hydrated.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files; |
| 451 | expect(hydratedFiles).toEqual([ |
| 452 | { |
| 453 | type: "file", |
| 454 | id: "file-pending", |
| 455 | name: "report.pdf", |
| 456 | mimeType: "application/pdf", |
| 457 | sizeBytes: 6, |
| 458 | file: null, |
| 459 | }, |
| 460 | ]); |
| 461 | expect(hydratedFiles?.every(composerFileNeedsReattach)).toBe(true); |
| 462 | }); |
| 463 | |
| 464 | it("marks only the matching byte-less upload as missing", () => { |
| 465 | const store = useComposerDraftStore.getState(); |
| 466 | const hydrated: ComposerFileAttachment = { |
| 467 | ...makeFile("file-hydrated"), |
| 468 | file: null, |
| 469 | uploadedAttachmentId: "pending-old", |
| 470 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 471 | }; |
| 472 | const local: ComposerFileAttachment = { |
| 473 | ...makeFile("file-local"), |
| 474 | name: "local.txt", |
| 475 | mimeType: "text/plain", |
| 476 | }; |
| 477 | store.addFiles(threadRef, [hydrated, local]); |
| 478 | store.setFileUpload(threadRef, hydrated.id, TEST_ENVIRONMENT_ID, "pending-new"); |
| 479 | store.setFileUpload(threadRef, local.id, TEST_ENVIRONMENT_ID, "pending-local"); |
| 480 | |
| 481 | expect( |
| 482 | store.markFileUploadMissing(threadRef, hydrated.id, OTHER_TEST_ENVIRONMENT_ID, "pending-new"), |
| 483 | ).toBe(false); |
| 484 | expect( |
| 485 | store.markFileUploadMissing(threadRef, hydrated.id, TEST_ENVIRONMENT_ID, "pending-old"), |
| 486 | ).toBe(false); |
| 487 | expect( |
| 488 | store.markFileUploadMissing(threadRef, local.id, TEST_ENVIRONMENT_ID, "pending-local"), |
| 489 | ).toBe(false); |
| 490 | |
| 491 | expect(store.getComposerDraft(threadRef)?.files).toMatchObject([ |
| 492 | { |
| 493 | id: hydrated.id, |
| 494 | uploadedAttachmentId: "pending-new", |
| 495 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 496 | }, |
| 497 | { |
| 498 | id: local.id, |
| 499 | file: local.file, |
| 500 | uploadedAttachmentId: "pending-local", |
| 501 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 502 | }, |
| 503 | ]); |
| 504 | |
| 505 | expect( |
| 506 | store.markFileUploadMissing(threadRef, hydrated.id, TEST_ENVIRONMENT_ID, "pending-new"), |
| 507 | ).toBe(true); |
| 508 | const marker = store.getComposerDraft(threadRef)?.files[0]; |
| 509 | expect(marker && composerFileNeedsReattach(marker)).toBe(true); |
| 510 | expect(marker?.uploadedAttachmentId).toBeUndefined(); |
| 511 | expect(marker?.uploadEnvironmentId).toBeUndefined(); |
| 512 | }); |
| 513 | |
| 514 | it("enforces the combined file and image limit across separate updates", () => { |
| 515 | const store = useComposerDraftStore.getState(); |
| 516 | const images = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 }, (_, index) => |
| 517 | makeImage({ |
| 518 | id: `image-${index}`, |
| 519 | name: `image-${index}.png`, |
| 520 | previewUrl: `blob:image-${index}`, |
| 521 | }), |
| 522 | ); |
| 523 | store.addImages(threadRef, images); |
| 524 | store.addFiles(threadRef, [ |
| 525 | makeFile("file-accepted"), |
| 526 | { ...makeFile("file-overflow"), name: "other.pdf" }, |
| 527 | ]); |
| 528 | expect( |
| 529 | store.addImage( |
| 530 | threadRef, |
| 531 | makeImage({ id: "image-overflow", name: "overflow.png", previewUrl: "blob:overflow" }), |
| 532 | ), |
| 533 | ).toBe(false); |
| 534 | |
| 535 | const draft = store.getComposerDraft(threadRef); |
| 536 | expect(draft?.images).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1); |
| 537 | expect(draft?.files.map((file) => file.id)).toEqual(["file-accepted"]); |
| 538 | }); |
| 539 | |
| 540 | it("reattaches a DNG with an older generic-MIME marker at attachment capacity", () => { |
| 541 | const store = useComposerDraftStore.getState(); |
| 542 | const file = new File(["raw"], "photo.DNG", { type: "image/x-adobe-dng" }); |
| 543 | const marker: ComposerFileAttachment = { |
| 544 | type: "file", |
| 545 | id: "dng-marker", |
| 546 | name: file.name, |
| 547 | mimeType: "application/octet-stream", |
| 548 | sizeBytes: file.size, |
| 549 | file: null, |
| 550 | }; |
| 551 | store.addFiles(threadRef, [marker]); |
| 552 | store.addImages( |
| 553 | threadRef, |
| 554 | Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 }, (_, index) => |
| 555 | makeImage({ |
| 556 | id: `image-${index}`, |
| 557 | name: `image-${index}.png`, |
| 558 | previewUrl: `blob:image-${index}`, |
| 559 | }), |
| 560 | ), |
| 561 | ); |
| 562 | |
| 563 | const repicked: ComposerFileAttachment = { |
| 564 | ...marker, |
| 565 | id: "dng-repicked", |
| 566 | mimeType: file.type, |
| 567 | file, |
| 568 | }; |
| 569 | store.addFiles(threadRef, [repicked]); |
| 570 | |
| 571 | const files = store.getComposerDraft(threadRef)?.files; |
| 572 | expect(files).toEqual([repicked]); |
| 573 | expect(files?.some(composerFileNeedsReattach)).toBe(false); |
| 574 | }); |
| 575 | |
| 576 | it("replaces a needs-reattach marker when the same file is picked again", () => { |
| 577 | const store = useComposerDraftStore.getState(); |
| 578 | const marker: ComposerFileAttachment = { ...makeFile("file-marker"), file: null }; |
| 579 | store.addFiles(threadRef, [marker]); |
| 580 | expect(store.getComposerDraft(threadRef)?.files.every(composerFileNeedsReattach)).toBe(true); |
| 581 | |
| 582 | const repicked = makeFile("file-repicked"); |
| 583 | store.addFiles(threadRef, [repicked]); |
| 584 | |
| 585 | const files = store.getComposerDraft(threadRef)?.files; |
| 586 | expect(files?.map((file) => file.id)).toEqual(["file-repicked"]); |
| 587 | expect(files?.[0]?.file).not.toBeNull(); |
| 588 | expect(files?.some(composerFileNeedsReattach)).toBe(false); |
| 589 | }); |
| 590 | }); |
| 591 | |
| 592 | describe("composerDraftStore terminal contexts", () => { |
| 593 | const threadId = ThreadId.make("thread-dedupe"); |
| 594 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 595 | |
| 596 | beforeEach(() => { |
| 597 | useComposerDraftStore.setState({ |
| 598 | draftsByThreadKey: {}, |
| 599 | draftThreadsByThreadKey: {}, |
| 600 | logicalProjectDraftThreadKeyByLogicalProjectKey: {}, |
| 601 | stickyModelSelectionByProvider: {}, |
| 602 | stickyActiveProvider: null, |
| 603 | }); |
| 604 | }); |
| 605 | |
| 606 | it("deduplicates identical terminal contexts by selection signature", () => { |
| 607 | const first = makeTerminalContext({ id: "ctx-1" }); |
| 608 | const duplicate = makeTerminalContext({ id: "ctx-2" }); |
| 609 | |
| 610 | useComposerDraftStore.getState().addTerminalContexts(threadRef, [first, duplicate]); |
| 611 | |
| 612 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 613 | expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-1"]); |
| 614 | }); |
| 615 | |
| 616 | it("inserts terminal contexts at the requested inline prompt position", () => { |
| 617 | const first = makeTerminalContext({ id: "ctx-1" }); |
| 618 | const second = makeTerminalContext({ |
| 619 | id: "ctx-2", |
| 620 | terminalLabel: "Terminal 2", |
| 621 | lineStart: 9, |
| 622 | lineEnd: 10, |
| 623 | }); |
| 624 | const firstInsertion = insertInlineContextReference( |
| 625 | "alpha beta", |
| 626 | 6, |
| 627 | terminalContextReference(first), |
| 628 | ); |
| 629 | const secondInsertion = insertInlineContextReference( |
| 630 | firstInsertion.prompt, |
| 631 | 0, |
| 632 | terminalContextReference(second), |
| 633 | ); |
| 634 | |
| 635 | expect( |
| 636 | useComposerDraftStore |
| 637 | .getState() |
| 638 | .insertTerminalContext(threadRef, firstInsertion.prompt, first, 0), |
| 639 | ).toBe(true); |
| 640 | expect( |
| 641 | useComposerDraftStore |
| 642 | .getState() |
| 643 | .insertTerminalContext(threadRef, secondInsertion.prompt, second, 0), |
| 644 | ).toBe(true); |
| 645 | |
| 646 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 647 | expect(draft?.prompt).toBe( |
| 648 | `${formatTerminalContextReference(second)} alpha ${formatTerminalContextReference(first)} beta`, |
| 649 | ); |
| 650 | expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-2", "ctx-1"]); |
| 651 | }); |
| 652 | |
| 653 | it("sanitizes malformed persisted drafts during merge", () => { |
| 654 | const persistApi = useComposerDraftStore.persist as unknown as { |
| 655 | getOptions: () => { |
| 656 | merge: ( |
| 657 | persistedState: unknown, |
| 658 | currentState: ReturnType<typeof useComposerDraftStore.getState>, |
| 659 | ) => ReturnType<typeof useComposerDraftStore.getState>; |
| 660 | }; |
| 661 | }; |
| 662 | const mergedState = persistApi.getOptions().merge( |
| 663 | { |
| 664 | draftsByThreadId: { |
| 665 | [threadId]: { |
| 666 | prompt: "", |
| 667 | attachments: "not-an-array", |
| 668 | terminalContexts: "not-an-array", |
| 669 | provider: "bogus-provider", |
| 670 | modelOptions: "not-an-object", |
| 671 | }, |
| 672 | }, |
| 673 | draftThreadsByThreadId: "not-an-object", |
| 674 | projectDraftThreadIdByProjectKey: "not-an-object", |
| 675 | }, |
| 676 | useComposerDraftStore.getInitialState(), |
| 677 | ); |
| 678 | |
| 679 | expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]).toBeUndefined(); |
| 680 | expect(mergedState.draftThreadsByThreadKey).toEqual({}); |
| 681 | expect(mergedState.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual({}); |
| 682 | }); |
| 683 | }); |
| 684 | |
| 685 | describe("composerDraftStore context persistence", () => { |
| 686 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("context-persistence")); |
| 687 | const annotation: PreviewAnnotationPayload = { |
| 688 | id: "retry-note", |
| 689 | pageUrl: "http://localhost:3000/checkout", |
| 690 | pageTitle: "Checkout", |
| 691 | comment: "Keep the cart after a failed payment", |
| 692 | elements: [], |
| 693 | regions: [{ id: "error-region", rect: { x: 10, y: 20, width: 100, height: 50 } }], |
| 694 | strokes: [], |
| 695 | styleChanges: [], |
| 696 | screenshot: null, |
| 697 | createdAt: "2026-09-06T10:00:00.000Z", |
| 698 | }; |
| 699 | |
| 700 | beforeEach(resetComposerDraftStore); |
| 701 | |
| 702 | it("preserves snapshots and inline positions through repeated persistence and hydration", () => { |
| 703 | const terminal = { |
| 704 | ...makeTerminalContext({ id: "checkout-console" }), |
| 705 | threadId: threadRef.threadId, |
| 706 | }; |
| 707 | const store = useComposerDraftStore.getState(); |
| 708 | store.addTerminalContexts(threadRef, [terminal]); |
| 709 | store.addPreviewAnnotation(threadRef, annotation); |
| 710 | const terminalLink = formatTerminalContextReference(terminal); |
| 711 | const prompt = `Inspect ${terminalLink}. Apply [Retry note](t3-context://v1/preview-annotation/preview-annotation_retry-note). Compare ${terminalLink} again.`; |
| 712 | store.setPrompt(threadRef, prompt); |
| 713 | let state = useComposerDraftStore.getState(); |
| 714 | const merge = useComposerDraftStore.persist.getOptions().merge!; |
| 715 | |
| 716 | for (let reload = 0; reload < 3; reload++) { |
| 717 | state = merge( |
| 718 | JSON.parse(JSON.stringify(partializeComposerDraftStoreState(state))), |
| 719 | useComposerDraftStore.getInitialState(), |
| 720 | ); |
| 721 | const draft = state.draftsByThreadKey[scopedThreadKey(threadRef)]; |
| 722 | expect(draft?.prompt).toBe(prompt); |
| 723 | expect(draft?.terminalContexts).toEqual([terminal]); |
| 724 | expect(draft?.previewAnnotations).toEqual([annotation]); |
| 725 | } |
| 726 | }); |
| 727 | |
| 728 | // regression: #35010 typing a draft in one tab erased drafts another tab saved after it loaded |
| 729 | it("keeps a draft another tab saved after this tab loaded", async () => { |
| 730 | const sharedStorage = createMemoryStorage(); |
| 731 | vi.stubGlobal("localStorage", sharedStorage); |
| 732 | vi.stubGlobal("window", new EventTarget()); |
| 733 | vi.useFakeTimers(); |
| 734 | vi.resetModules(); |
| 735 | try { |
| 736 | const thisTab = await import("./composerDraftStore"); |
| 737 | vi.resetModules(); |
| 738 | const otherTab = await import("./composerDraftStore"); |
| 739 | const betaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("beta-new-thread")); |
| 740 | const alphaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("alpha-new-thread")); |
| 741 | |
| 742 | otherTab.useComposerDraftStore.getState().setPrompt(betaRef, "beta draft"); |
| 743 | await vi.advanceTimersByTimeAsync(300); |
| 744 | window.dispatchEvent( |
| 745 | Object.assign(new Event("storage"), { key: COMPOSER_DRAFT_STORAGE_KEY }), |
| 746 | ); |
| 747 | thisTab.useComposerDraftStore.getState().setPrompt(alphaRef, "alpha draft"); |
| 748 | await vi.advanceTimersByTimeAsync(300); |
| 749 | |
| 750 | const saved = JSON.parse(sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string); |
| 751 | expect(saved.state.draftsByThreadKey[scopedThreadKey(betaRef)]?.prompt).toBe("beta draft"); |
| 752 | expect(saved.state.draftsByThreadKey[scopedThreadKey(alphaRef)]?.prompt).toBe("alpha draft"); |
| 753 | } finally { |
| 754 | vi.useRealTimers(); |
| 755 | vi.unstubAllGlobals(); |
| 756 | vi.resetModules(); |
| 757 | } |
| 758 | }); |
| 759 | }); |
| 760 | |
| 761 | describe("composerDraftStore thread contexts", () => { |
| 762 | const threadId = ThreadId.make("thread-with-context"); |
| 763 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 764 | const attached = threadContextRecord( |
| 765 | scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("attached-thread")), |
| 766 | "Fix [login] flow", |
| 767 | ); |
| 768 | |
| 769 | beforeEach(resetComposerDraftStore); |
| 770 | |
| 771 | it("attaches once per thread, appends one chip, and survives persistence", () => { |
| 772 | const store = useComposerDraftStore.getState(); |
| 773 | store.setPrompt(threadRef, "Compare with"); |
| 774 | store.addThreadContexts(threadRef, [attached]); |
| 775 | store.addThreadContexts(threadRef, [attached, { ...attached, title: "renamed" }]); |
| 776 | |
| 777 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 778 | expect(draft?.threadContexts).toEqual([attached]); |
| 779 | expect(attached.label).toBe("Fix login flow"); |
| 780 | expect(draft?.prompt).toBe( |
| 781 | `Compare with [${attached.label}](t3-context://v1/thread/${attached.contextId}) `, |
| 782 | ); |
| 783 | |
| 784 | const merge = useComposerDraftStore.persist.getOptions().merge!; |
| 785 | const hydrated = merge( |
| 786 | JSON.parse( |
| 787 | JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), |
| 788 | ), |
| 789 | useComposerDraftStore.getInitialState(), |
| 790 | ); |
| 791 | expect(hydrated.draftsByThreadKey[scopedThreadKey(threadRef)]?.threadContexts).toEqual([ |
| 792 | attached, |
| 793 | ]); |
| 794 | expect(hydrated.draftsByThreadKey[scopedThreadKey(threadRef)]?.prompt).toBe(draft?.prompt); |
| 795 | }); |
| 796 | }); |
| 797 | |
| 798 | describe("composerDraftStore environment contexts", () => { |
| 799 | const threadId = ThreadId.make("thread-with-machine"); |
| 800 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 801 | const vps = environmentContextRecord(EnvironmentId.make("environment-vps"), "Hetzner [vps]"); |
| 802 | |
| 803 | beforeEach(resetComposerDraftStore); |
| 804 | |
| 805 | it("mentions a machine once, survives persistence, and sends only its identity", () => { |
| 806 | const store = useComposerDraftStore.getState(); |
| 807 | store.setPrompt(threadRef, "Run it on"); |
| 808 | store.addEnvironmentContexts(threadRef, [vps]); |
| 809 | store.addEnvironmentContexts(threadRef, [{ ...vps, label: "renamed" }]); |
| 810 | |
| 811 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 812 | expect(draft?.environmentContexts).toEqual([vps]); |
| 813 | expect(vps.label).toBe("Hetzner vps"); |
| 814 | expect(draft?.prompt).toBe( |
| 815 | `Run it on [${vps.label}](t3-context://v1/environment/${vps.contextId}) `, |
| 816 | ); |
| 817 | |
| 818 | const merge = useComposerDraftStore.persist.getOptions().merge!; |
| 819 | const hydrated = merge( |
| 820 | JSON.parse( |
| 821 | JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())), |
| 822 | ), |
| 823 | useComposerDraftStore.getInitialState(), |
| 824 | ); |
| 825 | const restored = hydrated.draftsByThreadKey[scopedThreadKey(threadRef)]; |
| 826 | expect(restored?.environmentContexts).toEqual([vps]); |
| 827 | expect(restored?.prompt).toBe(draft?.prompt); |
| 828 | |
| 829 | expect( |
| 830 | buildMessageContext({ |
| 831 | terminalContexts: [], |
| 832 | reviewComments: [], |
| 833 | previewAnnotations: [], |
| 834 | environmentContexts: restored?.environmentContexts ?? [], |
| 835 | })?.records, |
| 836 | ).toEqual([ |
| 837 | { |
| 838 | version: 1, |
| 839 | kind: "environment", |
| 840 | contextId: vps.contextId, |
| 841 | label: "Hetzner vps", |
| 842 | environmentId: "environment-vps", |
| 843 | }, |
| 844 | ]); |
| 845 | }); |
| 846 | |
| 847 | it("drops the chip with the record and removes an otherwise empty draft", () => { |
| 848 | const store = useComposerDraftStore.getState(); |
| 849 | store.addEnvironmentContexts(threadRef, [vps]); |
| 850 | store.setEnvironmentContexts(threadRef, []); |
| 851 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined(); |
| 852 | }); |
| 853 | }); |
| 854 | |
| 855 | describe("composerDraftStore project draft thread mapping", () => { |
| 856 | const projectId = ProjectId.make("project-a"); |
| 857 | const otherProjectId = ProjectId.make("project-b"); |
| 858 | const projectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, projectId); |
| 859 | const otherProjectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, otherProjectId); |
| 860 | const remoteProjectRef = scopeProjectRef(OTHER_TEST_ENVIRONMENT_ID, projectId); |
| 861 | const threadId = ThreadId.make("thread-a"); |
| 862 | const otherThreadId = ThreadId.make("thread-b"); |
| 863 | const draftId = DraftId.make("draft-a"); |
| 864 | const otherDraftId = DraftId.make("draft-b"); |
| 865 | const sharedDraftId = DraftId.make("draft-shared"); |
| 866 | const localDraftId = DraftId.make("draft-local"); |
| 867 | const remoteDraftId = DraftId.make("draft-remote"); |
| 868 | |
| 869 | beforeEach(() => { |
| 870 | resetComposerDraftStore(); |
| 871 | }); |
| 872 | |
| 873 | it("clears composer data for one environment without touching another", () => { |
| 874 | const store = useComposerDraftStore.getState(); |
| 875 | const localThreadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 876 | const remoteThreadRef = scopeThreadRef(OTHER_TEST_ENVIRONMENT_ID, otherThreadId); |
| 877 | const originalRevokeObjectUrl = URL.revokeObjectURL; |
| 878 | const revokeSpy = vi.fn<(url: string) => void>(); |
| 879 | URL.revokeObjectURL = revokeSpy; |
| 880 | |
| 881 | try { |
| 882 | store.setProjectDraftThreadId(projectRef, localDraftId, { threadId }); |
| 883 | store.setProjectDraftThreadId(remoteProjectRef, remoteDraftId, { |
| 884 | threadId: otherThreadId, |
| 885 | }); |
| 886 | store.setPrompt(localDraftId, "local draft"); |
| 887 | store.setPrompt(remoteDraftId, "remote draft"); |
| 888 | store.addImage(localDraftId, makeImage({ id: "img-local", previewUrl: "blob:local-draft" })); |
| 889 | store.setPrompt(localThreadRef, "local thread draft"); |
| 890 | store.setPrompt(remoteThreadRef, "remote thread draft"); |
| 891 | useComposerDraftStore.setState({ |
| 892 | rewindingThreadKeys: new Set([ |
| 893 | threadKeyFor(threadId, TEST_ENVIRONMENT_ID), |
| 894 | threadKeyFor(otherThreadId, OTHER_TEST_ENVIRONMENT_ID), |
| 895 | ]), |
| 896 | }); |
| 897 | |
| 898 | clearComposerDraftsEnvironment(TEST_ENVIRONMENT_ID); |
| 899 | |
| 900 | const next = useComposerDraftStore.getState(); |
| 901 | expect([...next.rewindingThreadKeys]).toEqual([ |
| 902 | threadKeyFor(otherThreadId, OTHER_TEST_ENVIRONMENT_ID), |
| 903 | ]); |
| 904 | expect(next.getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 905 | expect(next.getDraftThreadByProjectRef(remoteProjectRef)).not.toBeNull(); |
| 906 | expect(next.getComposerDraft(localDraftId)).toBeNull(); |
| 907 | expect(next.getComposerDraft(remoteDraftId)?.prompt).toBe("remote thread draft"); |
| 908 | expect(next.getComposerDraft(localThreadRef)).toBeNull(); |
| 909 | expect(next.getComposerDraft(remoteThreadRef)?.prompt).toBe("remote thread draft"); |
| 910 | expect(revokeSpy).toHaveBeenCalledWith("blob:local-draft"); |
| 911 | } finally { |
| 912 | URL.revokeObjectURL = originalRevokeObjectUrl; |
| 913 | } |
| 914 | }); |
| 915 | |
| 916 | it("removes a draft's previous project mapping when retargeted in place", () => { |
| 917 | const store = useComposerDraftStore.getState(); |
| 918 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 919 | store.setPrompt(draftId, "keep this prompt"); |
| 920 | |
| 921 | store.setProjectDraftThreadId(otherProjectRef, draftId, { threadId }); |
| 922 | |
| 923 | expect(store.getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 924 | expect(store.getDraftThreadByProjectRef(otherProjectRef)?.draftId).toBe(draftId); |
| 925 | expect(store.getComposerDraft(draftId)?.prompt).toBe("keep this prompt"); |
| 926 | }); |
| 927 | |
| 928 | it("rotates a failed bootstrap thread id without losing its draft", () => { |
| 929 | const store = useComposerDraftStore.getState(); |
| 930 | const retryThreadId = ThreadId.make("thread-retry"); |
| 931 | store.setProjectDraftThreadId(projectRef, draftId, { |
| 932 | threadId, |
| 933 | branch: "feature/test", |
| 934 | worktreePath: null, |
| 935 | createdAt: "2026-01-01T00:00:00.000Z", |
| 936 | envMode: "worktree", |
| 937 | startFromOrigin: true, |
| 938 | runtimeMode: "approval-required", |
| 939 | interactionMode: "plan", |
| 940 | }); |
| 941 | store.setPrompt(draftId, "keep this prompt"); |
| 942 | markPromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); |
| 943 | |
| 944 | store.setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), projectRef, draftId, { |
| 945 | threadId: retryThreadId, |
| 946 | createdAt: "2026-01-01T00:01:00.000Z", |
| 947 | }); |
| 948 | |
| 949 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({ |
| 950 | threadId: retryThreadId, |
| 951 | branch: "feature/test", |
| 952 | worktreePath: null, |
| 953 | createdAt: "2026-01-01T00:01:00.000Z", |
| 954 | envMode: "worktree", |
| 955 | startFromOrigin: true, |
| 956 | runtimeMode: "approval-required", |
| 957 | interactionMode: "plan", |
| 958 | promotedTo: null, |
| 959 | }); |
| 960 | expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt).toBe( |
| 961 | "keep this prompt", |
| 962 | ); |
| 963 | }); |
| 964 | |
| 965 | it("clears only matching project draft mapping entries", () => { |
| 966 | const store = useComposerDraftStore.getState(); |
| 967 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 968 | store.setPrompt(draftId, "hello"); |
| 969 | |
| 970 | store.clearProjectDraftThreadById(projectRef, otherDraftId); |
| 971 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)?.threadId).toBe( |
| 972 | threadId, |
| 973 | ); |
| 974 | |
| 975 | store.clearProjectDraftThreadById(projectRef, draftId); |
| 976 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 977 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull(); |
| 978 | expect(draftByKey(draftId)).toBeUndefined(); |
| 979 | }); |
| 980 | |
| 981 | // regression: #1264 deleting a project must release its draft thread's image blob URLs |
| 982 | it("revokes draft image blob URLs when clearing a project's draft thread", () => { |
| 983 | const store = useComposerDraftStore.getState(); |
| 984 | const originalRevokeObjectUrl = URL.revokeObjectURL; |
| 985 | const revokeSpy = vi.fn<(url: string) => void>(); |
| 986 | URL.revokeObjectURL = revokeSpy; |
| 987 | |
| 988 | try { |
| 989 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 990 | store.addImage(draftId, makeImage({ id: "img-project-clear", previewUrl: "blob:clear" })); |
| 991 | |
| 992 | store.clearProjectDraftThreadId(projectRef); |
| 993 | |
| 994 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 995 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull(); |
| 996 | expect(revokeSpy).toHaveBeenCalledWith("blob:clear"); |
| 997 | } finally { |
| 998 | URL.revokeObjectURL = originalRevokeObjectUrl; |
| 999 | } |
| 1000 | }); |
| 1001 | |
| 1002 | it("clears empty composer drafts when remapping a project to a new draft thread", () => { |
| 1003 | const store = useComposerDraftStore.getState(); |
| 1004 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1005 | |
| 1006 | store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId }); |
| 1007 | |
| 1008 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)?.threadId).toBe( |
| 1009 | otherThreadId, |
| 1010 | ); |
| 1011 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull(); |
| 1012 | expect(draftByKey(draftId)).toBeUndefined(); |
| 1013 | }); |
| 1014 | |
| 1015 | it("keeps a draft with an open page when remapping a project to a new draft thread", () => { |
| 1016 | const store = useComposerDraftStore.getState(); |
| 1017 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1018 | applyPreviewServerSnapshot(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId), { |
| 1019 | threadId, |
| 1020 | tabId: "tab-link", |
| 1021 | navStatus: { _tag: "Success", url: "https://example.com/", title: "Example" }, |
| 1022 | canGoBack: false, |
| 1023 | canGoForward: false, |
| 1024 | updatedAt: "2026-10-09T00:00:00.000Z", |
| 1025 | }); |
| 1026 | try { |
| 1027 | store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId }); |
| 1028 | |
| 1029 | expect(useComposerDraftStore.getState().getDraftThread(draftId)?.threadId).toBe(threadId); |
| 1030 | const persisted = partializeComposerDraftStoreState(useComposerDraftStore.getState()); |
| 1031 | expect(persisted.draftThreadsByThreadKey[draftId]?.threadId).toBe(threadId); |
| 1032 | } finally { |
| 1033 | resetPreviewStateForTests(); |
| 1034 | } |
| 1035 | }); |
| 1036 | |
| 1037 | it("keeps invested composer drafts alive unmapped when remapping a project to a new draft thread", () => { |
| 1038 | const store = useComposerDraftStore.getState(); |
| 1039 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1040 | store.setPrompt(draftId, "keep me around"); |
| 1041 | |
| 1042 | store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId }); |
| 1043 | |
| 1044 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)?.threadId).toBe( |
| 1045 | otherThreadId, |
| 1046 | ); |
| 1047 | expect(useComposerDraftStore.getState().getDraftThread(draftId)?.threadId).toBe(threadId); |
| 1048 | expect(draftByKey(draftId)?.prompt).toBe("keep me around"); |
| 1049 | }); |
| 1050 | |
| 1051 | it("clears every session for a project, including unmapped invested drafts", () => { |
| 1052 | const store = useComposerDraftStore.getState(); |
| 1053 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1054 | store.setPrompt(draftId, "invested"); |
| 1055 | store.setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId }); |
| 1056 | |
| 1057 | store.clearProjectDraftThreadId(projectRef); |
| 1058 | |
| 1059 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 1060 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull(); |
| 1061 | expect(useComposerDraftStore.getState().getDraftThread(otherDraftId)).toBeNull(); |
| 1062 | expect(draftByKey(draftId)).toBeUndefined(); |
| 1063 | }); |
| 1064 | |
| 1065 | it("keeps composer drafts when the thread is still mapped by another project", () => { |
| 1066 | const store = useComposerDraftStore.getState(); |
| 1067 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1068 | store.setProjectDraftThreadId(otherProjectRef, sharedDraftId, { threadId }); |
| 1069 | store.setPrompt(sharedDraftId, "keep me"); |
| 1070 | |
| 1071 | store.clearProjectDraftThreadId(projectRef); |
| 1072 | |
| 1073 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 1074 | expect( |
| 1075 | useComposerDraftStore.getState().getDraftThreadByProjectRef(otherProjectRef)?.threadId, |
| 1076 | ).toBe(threadId); |
| 1077 | expect(draftByKey(sharedDraftId)?.prompt).toBe("keep me"); |
| 1078 | }); |
| 1079 | |
| 1080 | it("does not clear composer drafts for existing server threads during promotion cleanup", () => { |
| 1081 | const store = useComposerDraftStore.getState(); |
| 1082 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 1083 | store.setPrompt(threadRef, "keep me"); |
| 1084 | |
| 1085 | markPromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); |
| 1086 | |
| 1087 | expect(useComposerDraftStore.getState().getDraftThread(threadRef)).toBeNull(); |
| 1088 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("keep me"); |
| 1089 | }); |
| 1090 | |
| 1091 | it("promotes matching thread ids separately for each environment", () => { |
| 1092 | const store = useComposerDraftStore.getState(); |
| 1093 | const localThreadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 1094 | const remoteThreadRef = scopeThreadRef(OTHER_TEST_ENVIRONMENT_ID, threadId); |
| 1095 | |
| 1096 | store.setProjectDraftThreadId(projectRef, localDraftId, { threadId }); |
| 1097 | store.setPrompt(localDraftId, "local draft"); |
| 1098 | store.setProjectDraftThreadId(remoteProjectRef, remoteDraftId, { threadId }); |
| 1099 | store.setPrompt(remoteDraftId, "remote draft"); |
| 1100 | |
| 1101 | markPromotedDraftThreadByRef(localThreadRef); |
| 1102 | |
| 1103 | expect(store.getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 1104 | expect(store.getDraftThreadByProjectRef(remoteProjectRef)?.threadId).toBe(threadId); |
| 1105 | expect(store.getDraftThreadByRef(localThreadRef)?.promotedTo).toEqual(localThreadRef); |
| 1106 | expect(store.getDraftThreadByRef(remoteThreadRef)?.promotedTo).toBeNull(); |
| 1107 | expect(draftByKey(localDraftId)?.prompt).toBe("local draft"); |
| 1108 | expect(draftByKey(remoteDraftId)?.prompt).toBe("remote draft"); |
| 1109 | |
| 1110 | markPromotedDraftThreadByRef(remoteThreadRef); |
| 1111 | |
| 1112 | expect(store.getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 1113 | expect(store.getDraftThreadByProjectRef(remoteProjectRef)).toBeNull(); |
| 1114 | expect(store.getDraftThreadByRef(localThreadRef)?.promotedTo).toEqual(localThreadRef); |
| 1115 | expect(store.getDraftThreadByRef(remoteThreadRef)?.promotedTo).toEqual(remoteThreadRef); |
| 1116 | expect(draftByKey(localDraftId)?.prompt).toBe("local draft"); |
| 1117 | expect(draftByKey(remoteDraftId)?.prompt).toBe("remote draft"); |
| 1118 | }); |
| 1119 | |
| 1120 | it("keeps background submission pending until navigation or failure releases it", () => { |
| 1121 | const store = useComposerDraftStore.getState(); |
| 1122 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1123 | const ref = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 1124 | const key = scopedThreadKey(ref); |
| 1125 | beginBackgroundDraftSubmissionByRef(ref); |
| 1126 | expect(useComposerDraftStore.getState().backgroundSubmissionThreadKeys[key]).toBe(true); |
| 1127 | clearBackgroundDraftSubmissionByRef(ref); |
| 1128 | expect(useComposerDraftStore.getState().backgroundSubmissionThreadKeys[key]).toBeUndefined(); |
| 1129 | expect(useComposerDraftStore.getState().getDraftSession(draftId)).not.toBeNull(); |
| 1130 | beginBackgroundDraftSubmissionByRef(ref); |
| 1131 | finalizePromotedDraftThreadByRef(ref); |
| 1132 | expect(useComposerDraftStore.getState().backgroundSubmissionThreadKeys[key]).toBeUndefined(); |
| 1133 | expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); |
| 1134 | }); |
| 1135 | |
| 1136 | it("restores a failed draft without changing the fresh draft", () => { |
| 1137 | const store = useComposerDraftStore.getState(); |
| 1138 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1139 | const sentDraft = useComposerDraftStore.getState().getDraftSession(draftId)!; |
| 1140 | markPromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); |
| 1141 | const freshId = DraftId.make("fresh-background-draft"); |
| 1142 | store.setProjectDraftThreadId(projectRef, freshId, { threadId: ThreadId.make("fresh-thread") }); |
| 1143 | store.setPrompt(freshId, "new work"); |
| 1144 | store.setDraftThreadContext(draftId, { branch: "retry-base" }); |
| 1145 | restoreFailedDraftThread(draftId, sentDraft, ThreadId.make("retry-thread")); |
| 1146 | store.setPrompt(draftId, "retry work"); |
| 1147 | expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toBeNull(); |
| 1148 | expect(useComposerDraftStore.getState().getDraftSession(draftId)?.threadId).toBe( |
| 1149 | "retry-thread", |
| 1150 | ); |
| 1151 | expect(useComposerDraftStore.getState().getDraftSession(draftId)?.branch).toBe("retry-base"); |
| 1152 | expect(draftByKey(freshId)?.prompt).toBe("new work"); |
| 1153 | expect(draftByKey(draftId)?.prompt).toBe("retry work"); |
| 1154 | }); |
| 1155 | |
| 1156 | it("moves composer edits made during promotion to the canonical thread", () => { |
| 1157 | const store = useComposerDraftStore.getState(); |
| 1158 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1159 | markPromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); |
| 1160 | store.setPrompt(draftId, "typed during setup"); |
| 1161 | |
| 1162 | finalizePromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); |
| 1163 | |
| 1164 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 1165 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull(); |
| 1166 | expect(draftByKey(draftId)).toBeUndefined(); |
| 1167 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("typed during setup"); |
| 1168 | }); |
| 1169 | |
| 1170 | it("finalizes a matching materialized draft even when promotion was not pre-marked", () => { |
| 1171 | const store = useComposerDraftStore.getState(); |
| 1172 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1173 | store.setPrompt(draftId, "promote me"); |
| 1174 | |
| 1175 | finalizePromotedDraftThreadByRef(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)); |
| 1176 | |
| 1177 | expect(useComposerDraftStore.getState().getDraftThreadByProjectRef(projectRef)).toBeNull(); |
| 1178 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toBeNull(); |
| 1179 | expect(draftByKey(draftId)).toBeUndefined(); |
| 1180 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("promote me"); |
| 1181 | }); |
| 1182 | |
| 1183 | it("preserves existing branch and worktree when setProjectDraftThreadId receives undefined", () => { |
| 1184 | const store = useComposerDraftStore.getState(); |
| 1185 | store.setProjectDraftThreadId(projectRef, draftId, { |
| 1186 | threadId, |
| 1187 | branch: "main", |
| 1188 | worktreePath: "/tmp/main-worktree", |
| 1189 | }); |
| 1190 | const runtimeUndefinedOptions = { |
| 1191 | branch: undefined, |
| 1192 | worktreePath: undefined, |
| 1193 | } as unknown as { |
| 1194 | branch?: string | null; |
| 1195 | worktreePath?: string | null; |
| 1196 | }; |
| 1197 | store.setProjectDraftThreadId(projectRef, draftId, runtimeUndefinedOptions); |
| 1198 | |
| 1199 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({ |
| 1200 | environmentId: TEST_ENVIRONMENT_ID, |
| 1201 | projectId, |
| 1202 | branch: "main", |
| 1203 | worktreePath: "/tmp/main-worktree", |
| 1204 | envMode: "worktree", |
| 1205 | }); |
| 1206 | }); |
| 1207 | |
| 1208 | it("clears branch and worktree but keeps env mode when remapping a draft to another environment", () => { |
| 1209 | const store = useComposerDraftStore.getState(); |
| 1210 | store.setProjectDraftThreadId(projectRef, draftId, { |
| 1211 | threadId, |
| 1212 | branch: "feature/local-only", |
| 1213 | worktreePath: "/tmp/local-worktree", |
| 1214 | envMode: "worktree", |
| 1215 | startFromOrigin: true, |
| 1216 | }); |
| 1217 | |
| 1218 | store.setLogicalProjectDraftThreadId(scopedProjectKey(projectRef), remoteProjectRef, draftId, { |
| 1219 | threadId, |
| 1220 | }); |
| 1221 | |
| 1222 | expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({ |
| 1223 | environmentId: OTHER_TEST_ENVIRONMENT_ID, |
| 1224 | projectId, |
| 1225 | branch: null, |
| 1226 | worktreePath: null, |
| 1227 | envMode: "worktree", |
| 1228 | startFromOrigin: true, |
| 1229 | }); |
| 1230 | }); |
| 1231 | |
| 1232 | it("clears stale upload metadata when retargeting a draft to another environment", () => { |
| 1233 | const store = useComposerDraftStore.getState(); |
| 1234 | const hydratedFile: ComposerFileAttachment = { |
| 1235 | ...makeFile("file-cross-environment"), |
| 1236 | file: null, |
| 1237 | uploadedAttachmentId: "local-environment-upload", |
| 1238 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 1239 | }; |
| 1240 | |
| 1241 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1242 | store.addFiles(draftId, [hydratedFile]); |
| 1243 | |
| 1244 | store.setProjectDraftThreadId(remoteProjectRef, draftId, { threadId }); |
| 1245 | |
| 1246 | const file = store.getComposerDraft(draftId)?.files[0]; |
| 1247 | expect(file).toMatchObject({ |
| 1248 | id: hydratedFile.id, |
| 1249 | file: null, |
| 1250 | }); |
| 1251 | expect(file?.uploadedAttachmentId).toBeUndefined(); |
| 1252 | expect(file?.uploadEnvironmentId).toBeUndefined(); |
| 1253 | expect(file && composerFileNeedsReattach(file)).toBe(true); |
| 1254 | }); |
| 1255 | |
| 1256 | it("rechecks balancing when an empty draft is remapped to another project member", () => { |
| 1257 | const store = useComposerDraftStore.getState(); |
| 1258 | store.setProjectDraftThreadId(projectRef, draftId, { |
| 1259 | threadId, |
| 1260 | environmentSelection: "auto", |
| 1261 | loadBalancedEnvironmentId: TEST_ENVIRONMENT_ID, |
| 1262 | }); |
| 1263 | store.setProjectDraftThreadId(remoteProjectRef, draftId, { threadId }); |
| 1264 | expect(store.getDraftThread(draftId)).toMatchObject({ |
| 1265 | environmentSelection: "auto", |
| 1266 | loadBalancedEnvironmentId: null, |
| 1267 | }); |
| 1268 | store.setDraftThreadContext(draftId, { loadBalancedEnvironmentId: OTHER_TEST_ENVIRONMENT_ID }); |
| 1269 | store.setDraftThreadContext(draftId, { projectRef }); |
| 1270 | expect(store.getDraftThread(draftId)).toMatchObject({ |
| 1271 | environmentSelection: "auto", |
| 1272 | loadBalancedEnvironmentId: null, |
| 1273 | }); |
| 1274 | }); |
| 1275 | |
| 1276 | it("pins manual workspace choices and can return to automatic routing without losing the prompt", () => { |
| 1277 | const store = useComposerDraftStore.getState(); |
| 1278 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1279 | store.setPrompt(draftId, "keep this prompt"); |
| 1280 | store.setDraftThreadContext(draftId, { |
| 1281 | projectRef: remoteProjectRef, |
| 1282 | environmentSelection: "auto", |
| 1283 | loadBalancedEnvironmentId: OTHER_TEST_ENVIRONMENT_ID, |
| 1284 | }); |
| 1285 | expect(store.getDraftThread(draftId)).toMatchObject({ |
| 1286 | environmentId: OTHER_TEST_ENVIRONMENT_ID, |
| 1287 | environmentSelection: "auto", |
| 1288 | loadBalancedEnvironmentId: OTHER_TEST_ENVIRONMENT_ID, |
| 1289 | }); |
| 1290 | store.setDraftThreadContext(draftId, { branch: "feature/pinned" }); |
| 1291 | expect(store.getDraftThread(draftId)?.environmentSelection).toBe("manual"); |
| 1292 | store.setDraftThreadContext(draftId, { |
| 1293 | branch: null, |
| 1294 | environmentSelection: "auto", |
| 1295 | loadBalancedEnvironmentId: null, |
| 1296 | }); |
| 1297 | expect(store.getDraftThread(draftId)).toMatchObject({ |
| 1298 | branch: null, |
| 1299 | environmentSelection: "auto", |
| 1300 | loadBalancedEnvironmentId: null, |
| 1301 | }); |
| 1302 | expect(store.getComposerDraft(draftId)?.prompt).toBe("keep this prompt"); |
| 1303 | }); |
| 1304 | }); |
| 1305 | |
| 1306 | function modelReconciliationHarness( |
| 1307 | environmentId: EnvironmentId, |
| 1308 | threadId: ThreadId, |
| 1309 | initialStatus: EnvironmentShellStatus = "live", |
| 1310 | ) { |
| 1311 | const tasks: Array<() => void> = []; |
| 1312 | const registry = AtomRegistry.make({ |
| 1313 | scheduleTask: (task) => { |
| 1314 | tasks.push(task); |
| 1315 | return () => {}; |
| 1316 | }, |
| 1317 | }); |
| 1318 | onTestFinished(() => registry.dispose()); |
| 1319 | const flush = () => { |
| 1320 | for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task(); |
| 1321 | }; |
| 1322 | const selectedThreadId = ThreadId.make("another-selected-thread"); |
| 1323 | const thread: OrchestrationV2ThreadShell = { |
| 1324 | ...makeThreadProjectionFixture().thread, |
| 1325 | latestRunId: null, |
| 1326 | activeRunId: null, |
| 1327 | status: "idle", |
| 1328 | pendingRuntimeRequest: null, |
| 1329 | latestVisibleMessage: null, |
| 1330 | latestUserMessageAt: null, |
| 1331 | hasActionableProposedPlan: false, |
| 1332 | itemCount: 0, |
| 1333 | visibleItemCount: 0, |
| 1334 | }; |
| 1335 | const initialSnapshot: OrchestrationV2ShellSnapshot = { |
| 1336 | schemaVersion: 1, |
| 1337 | snapshotSequence: 0, |
| 1338 | projects: [], |
| 1339 | archivedThreads: [], |
| 1340 | threads: [ |
| 1341 | { ...thread, id: threadId }, |
| 1342 | { ...thread, id: selectedThreadId }, |
| 1343 | ], |
| 1344 | }; |
| 1345 | const shellStateAtom = Atom.make<EnvironmentShellState>({ |
| 1346 | ...EMPTY_SHELL_STATE, |
| 1347 | snapshot: Option.some(initialSnapshot), |
| 1348 | status: initialStatus, |
| 1349 | }); |
| 1350 | const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success); |
| 1351 | const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId); |
| 1352 | const catalogValueAtom = Atom.make({ |
| 1353 | isReady: true, |
| 1354 | entries: new Map([ |
| 1355 | [ |
| 1356 | environmentId, |
| 1357 | { |
| 1358 | target: new PrimaryConnectionTarget({ |
| 1359 | environmentId, |
| 1360 | label: "Environment", |
| 1361 | httpBaseUrl: "https://example.test", |
| 1362 | wsBaseUrl: "wss://example.test", |
| 1363 | }), |
| 1364 | profile: Option.none(), |
| 1365 | enabled: true, |
| 1366 | }, |
| 1367 | ], |
| 1368 | ]), |
| 1369 | }); |
| 1370 | // A pick sent to the thread: shown over the durable snapshot until it settles. |
| 1371 | const inFlightPickAtom = Atom.make<ModelSelection | null>(null); |
| 1372 | const visibleSnapshotAtom = Atom.make((get) => { |
| 1373 | const snapshot = get(snapshotAtom); |
| 1374 | const pick = get(inFlightPickAtom); |
| 1375 | if (!snapshot || !pick) return snapshot; |
| 1376 | return { |
| 1377 | ...snapshot, |
| 1378 | threads: snapshot.threads.map((candidate) => |
| 1379 | candidate.id === threadId ? { ...candidate, modelSelection: pick } : candidate, |
| 1380 | ), |
| 1381 | }; |
| 1382 | }); |
| 1383 | const pendingThreadIdsAtom = Atom.map( |
| 1384 | inFlightPickAtom, |
| 1385 | (pick): ReadonlySet<ThreadId> => new Set(pick ? [threadId] : []), |
| 1386 | ); |
| 1387 | const shells = createEnvironmentThreadShellAtoms({ |
| 1388 | catalogValueAtom, |
| 1389 | snapshotAtom: () => visibleSnapshotAtom, |
| 1390 | hiddenThreadTagsAtom: () => Atom.make(null), |
| 1391 | }); |
| 1392 | const selectedShell = shells.threadShellAtom({ environmentId, threadId: selectedThreadId }); |
| 1393 | onTestFinished(registry.mount(selectedShell)); |
| 1394 | onTestFinished( |
| 1395 | subscribeComposerDraftModelReconciliation({ |
| 1396 | registry, |
| 1397 | threadShellAtom: shells.threadShellAtom, |
| 1398 | threadRefsAtom: shells.threadRefsAtom, |
| 1399 | shellStateAtom: () => shellResultAtom, |
| 1400 | pendingThreadIdsAtom: () => pendingThreadIdsAtom, |
| 1401 | }), |
| 1402 | ); |
| 1403 | flush(); |
| 1404 | return { |
| 1405 | flush, |
| 1406 | showInFlightPick(pick: ModelSelection | null) { |
| 1407 | registry.set(inFlightPickAtom, pick); |
| 1408 | flush(); |
| 1409 | }, |
| 1410 | setStatus(status: EnvironmentShellStatus) { |
| 1411 | registry.set(shellStateAtom, { ...registry.get(shellStateAtom), status }); |
| 1412 | flush(); |
| 1413 | }, |
| 1414 | update(changes: Partial<OrchestrationV2ThreadShell>, status?: EnvironmentShellStatus) { |
| 1415 | const state = registry.get(shellStateAtom); |
| 1416 | const snapshot = Option.getOrThrow(state.snapshot); |
| 1417 | registry.set(shellStateAtom, { |
| 1418 | ...state, |
| 1419 | status: status ?? state.status, |
| 1420 | snapshot: Option.some( |
| 1421 | applyShellStreamEvent(snapshot, { |
| 1422 | kind: "thread.updated", |
| 1423 | location: "active", |
| 1424 | sequence: snapshot.snapshotSequence + 1, |
| 1425 | thread: { ...snapshot.threads[0]!, ...changes }, |
| 1426 | }), |
| 1427 | ), |
| 1428 | }); |
| 1429 | flush(); |
| 1430 | expect(registry.get(selectedShell)?.id).toBe(selectedThreadId); |
| 1431 | }, |
| 1432 | model: () => registry.get(shells.threadShellAtom({ environmentId, threadId }))!.modelSelection, |
| 1433 | }; |
| 1434 | } |
| 1435 | |
| 1436 | type PromotionShell = NonNullable< |
| 1437 | Parameters<typeof resolveDraftPromotionNavigationTarget>[0]["serverThread"] |
| 1438 | >; |
| 1439 | |
| 1440 | function draftPromotionHarness() { |
| 1441 | const tasks: Array<() => void> = []; |
| 1442 | const registry = AtomRegistry.make({ |
| 1443 | scheduleTask: (task) => { |
| 1444 | tasks.push(task); |
| 1445 | return () => {}; |
| 1446 | }, |
| 1447 | }); |
| 1448 | onTestFinished(() => registry.dispose()); |
| 1449 | const flush = () => { |
| 1450 | for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task(); |
| 1451 | }; |
| 1452 | const threadRefsAtom = Atom.make<ReadonlyArray<ScopedThreadRef>>([]); |
| 1453 | const shellAtoms = new Map<string, Atom.Writable<PromotionShell | null>>(); |
| 1454 | const shellAtom = (ref: ScopedThreadRef) => { |
| 1455 | const key = scopedThreadKey(ref); |
| 1456 | let atom = shellAtoms.get(key); |
| 1457 | if (!atom) { |
| 1458 | atom = Atom.make<PromotionShell | null>(null); |
| 1459 | shellAtoms.set(key, atom); |
| 1460 | } |
| 1461 | return atom; |
| 1462 | }; |
| 1463 | onTestFinished( |
| 1464 | subscribeDraftThreadPromotion({ registry, threadRefsAtom, threadShellAtom: shellAtom }), |
| 1465 | ); |
| 1466 | flush(); |
| 1467 | return { |
| 1468 | flush, |
| 1469 | arrive(ref: ScopedThreadRef, shell: PromotionShell | null = null) { |
| 1470 | registry.set(shellAtom(ref), shell); |
| 1471 | registry.set(threadRefsAtom, [...registry.get(threadRefsAtom), ref]); |
| 1472 | flush(); |
| 1473 | }, |
| 1474 | updateShell(ref: ScopedThreadRef, shell: PromotionShell) { |
| 1475 | registry.set(shellAtom(ref), shell); |
| 1476 | flush(); |
| 1477 | }, |
| 1478 | }; |
| 1479 | } |
| 1480 | |
| 1481 | describe("composerDraftStore draft promotion", () => { |
| 1482 | const projectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, ProjectId.make("project-promotion")); |
| 1483 | const draftId = DraftId.make("draft-promotion"); |
| 1484 | const threadId = ThreadId.make("thread-promotion"); |
| 1485 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 1486 | const preparingRun = { |
| 1487 | runId: RunId.make("run-promotion"), |
| 1488 | status: "preparing" as const, |
| 1489 | requestedAt: "2026-03-29T00:00:00.000Z", |
| 1490 | startedAt: null, |
| 1491 | completedAt: null, |
| 1492 | assistantMessageId: null, |
| 1493 | }; |
| 1494 | |
| 1495 | beforeEach(resetComposerDraftStore); |
| 1496 | |
| 1497 | it("stays on the draft until the server owns the send", () => { |
| 1498 | expect( |
| 1499 | resolveDraftPromotionNavigationTarget({ |
| 1500 | serverThreadRef: threadRef, |
| 1501 | serverThread: { latestRun: preparingRun, latestUserMessageAt: null }, |
| 1502 | backgroundSubmissionPending: false, |
| 1503 | }), |
| 1504 | ).toBeNull(); |
| 1505 | expect( |
| 1506 | resolveDraftPromotionNavigationTarget({ |
| 1507 | serverThreadRef: threadRef, |
| 1508 | serverThread: { latestRun: null, latestUserMessageAt: null }, |
| 1509 | backgroundSubmissionPending: false, |
| 1510 | }), |
| 1511 | ).toBeNull(); |
| 1512 | const persisted = { latestRun: preparingRun, latestUserMessageAt: "2026-03-29T00:00:00.000Z" }; |
| 1513 | expect( |
| 1514 | resolveDraftPromotionNavigationTarget({ |
| 1515 | serverThreadRef: threadRef, |
| 1516 | serverThread: persisted, |
| 1517 | backgroundSubmissionPending: false, |
| 1518 | }), |
| 1519 | ).toBe(threadRef); |
| 1520 | expect( |
| 1521 | resolveDraftPromotionNavigationTarget({ |
| 1522 | serverThreadRef: threadRef, |
| 1523 | serverThread: persisted, |
| 1524 | backgroundSubmissionPending: true, |
| 1525 | }), |
| 1526 | ).toBeNull(); |
| 1527 | }); |
| 1528 | |
| 1529 | it("marks a draft promoting when its reserved thread arrives, then finalizes into it", async () => { |
| 1530 | const h = draftPromotionHarness(); |
| 1531 | const store = useComposerDraftStore.getState(); |
| 1532 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1533 | store.setPrompt(draftId, "typed during setup"); |
| 1534 | h.flush(); |
| 1535 | expect(store.getDraftSession(draftId)?.promotedTo).toBeNull(); |
| 1536 | |
| 1537 | h.arrive(threadRef, { latestRun: preparingRun, latestUserMessageAt: null }); |
| 1538 | expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual( |
| 1539 | threadRef, |
| 1540 | ); |
| 1541 | |
| 1542 | h.updateShell(threadRef, { |
| 1543 | latestRun: preparingRun, |
| 1544 | latestUserMessageAt: "2026-03-29T00:00:00.000Z", |
| 1545 | }); |
| 1546 | await waitForDraftHeroTransition(); |
| 1547 | |
| 1548 | const state = useComposerDraftStore.getState(); |
| 1549 | expect(state.getDraftSession(draftId)).toBeNull(); |
| 1550 | expect(state.getPromotedDraftRedirect(draftId)).toEqual(threadRef); |
| 1551 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("typed during setup"); |
| 1552 | }); |
| 1553 | |
| 1554 | it("holds a background submission on its draft until the send settles", async () => { |
| 1555 | const h = draftPromotionHarness(); |
| 1556 | const store = useComposerDraftStore.getState(); |
| 1557 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1558 | beginBackgroundDraftSubmissionByRef(threadRef); |
| 1559 | h.arrive(threadRef, { |
| 1560 | latestRun: preparingRun, |
| 1561 | latestUserMessageAt: "2026-03-29T00:00:00.000Z", |
| 1562 | }); |
| 1563 | await waitForDraftHeroTransition(); |
| 1564 | expect(useComposerDraftStore.getState().getDraftSession(draftId)?.promotedTo).toEqual( |
| 1565 | threadRef, |
| 1566 | ); |
| 1567 | |
| 1568 | clearBackgroundDraftSubmissionByRef(threadRef); |
| 1569 | h.flush(); |
| 1570 | await waitForDraftHeroTransition(); |
| 1571 | expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); |
| 1572 | }); |
| 1573 | |
| 1574 | it("does not finalize a draft whose send failed and was restored", async () => { |
| 1575 | const h = draftPromotionHarness(); |
| 1576 | const store = useComposerDraftStore.getState(); |
| 1577 | store.setProjectDraftThreadId(projectRef, draftId, { threadId }); |
| 1578 | const sent = useComposerDraftStore.getState().getDraftSession(draftId)!; |
| 1579 | h.arrive(threadRef, { |
| 1580 | latestRun: { ...preparingRun, status: "failed" as const }, |
| 1581 | latestUserMessageAt: null, |
| 1582 | }); |
| 1583 | restoreFailedDraftThread(draftId, sent, ThreadId.make("retry-thread")); |
| 1584 | h.flush(); |
| 1585 | await waitForDraftHeroTransition(); |
| 1586 | expect(useComposerDraftStore.getState().getDraftSession(draftId)?.threadId).toBe( |
| 1587 | "retry-thread", |
| 1588 | ); |
| 1589 | }); |
| 1590 | }); |
| 1591 | |
| 1592 | describe("composerDraftStore modelSelection", () => { |
| 1593 | const threadId = ThreadId.make("thread-model-options"); |
| 1594 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 1595 | |
| 1596 | beforeEach(() => { |
| 1597 | resetComposerDraftStore(); |
| 1598 | }); |
| 1599 | |
| 1600 | it("retains a pick matching cached state until the live shell confirms it", () => { |
| 1601 | const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId, "cached"); |
| 1602 | const pick = h.model(); |
| 1603 | useComposerDraftStore.getState().setModelSelection(threadRef, pick, { explicit: true }); |
| 1604 | h.flush(); |
| 1605 | const before = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 1606 | expect(before?.modelSelectionByProvider[pick.instanceId]).toEqual(pick); |
| 1607 | |
| 1608 | for (const status of ["empty", "synchronizing", "cached"] as const) { |
| 1609 | h.setStatus(status); |
| 1610 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before); |
| 1611 | } |
| 1612 | h.update({ modelSelection: { ...pick, model: "remote-model" } }, "live"); |
| 1613 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before); |
| 1614 | h.update({ modelSelection: pick }, "synchronizing"); |
| 1615 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before); |
| 1616 | h.setStatus("live"); |
| 1617 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined(); |
| 1618 | }); |
| 1619 | |
| 1620 | it("keeps a pick matching the old model while an earlier pick is still in flight", () => { |
| 1621 | const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId); |
| 1622 | const store = useComposerDraftStore.getState(); |
| 1623 | const original = h.model(); |
| 1624 | const other = { ...original, model: "remote-model" }; |
| 1625 | store.setModelSelection(threadRef, other, { explicit: true }); |
| 1626 | h.showInFlightPick(other); |
| 1627 | store.setModelSelection(threadRef, original, { explicit: true }); |
| 1628 | h.showInFlightPick(original); |
| 1629 | const latest = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 1630 | expect(latest?.modelSelectionByProvider[original.instanceId]).toEqual(original); |
| 1631 | |
| 1632 | // The earlier pick lands, then the latest one is rejected. |
| 1633 | h.update({ modelSelection: other }); |
| 1634 | h.showInFlightPick(null); |
| 1635 | expect(h.model()).toEqual(other); |
| 1636 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest); |
| 1637 | }); |
| 1638 | |
| 1639 | it.each(["consecutive model", "consecutive options", "returning model"] as const)( |
| 1640 | "releases only the latest accepted pick after %s picks", |
| 1641 | (kind) => { |
| 1642 | const store = useComposerDraftStore.getState(); |
| 1643 | store.setPrompt(threadRef, "keep this follow-up"); |
| 1644 | const select = () => { |
| 1645 | if (kind === "consecutive options") { |
| 1646 | store.setProviderModelOptions( |
| 1647 | threadRef, |
| 1648 | CODEX_DRIVER, |
| 1649 | toSelections({ reasoningEffort: "high" }), |
| 1650 | { instanceId: CODEX_INSTANCE, model: "gpt-5.5" }, |
| 1651 | ); |
| 1652 | } else { |
| 1653 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.5"), { |
| 1654 | explicit: true, |
| 1655 | }); |
| 1656 | } |
| 1657 | }; |
| 1658 | select(); |
| 1659 | const first = draftFor(threadId, TEST_ENVIRONMENT_ID)!.modelSelectionByProvider[ |
| 1660 | CODEX_INSTANCE |
| 1661 | ]!; |
| 1662 | if (kind === "returning model") { |
| 1663 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), { |
| 1664 | explicit: true, |
| 1665 | }); |
| 1666 | } |
| 1667 | select(); |
| 1668 | const latest = draftFor(threadId, TEST_ENVIRONMENT_ID)!; |
| 1669 | |
| 1670 | store.releaseModelSelection(threadRef, first); |
| 1671 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBe(latest); |
| 1672 | store.releaseModelSelection(threadRef, latest.modelSelectionByProvider[CODEX_INSTANCE]!); |
| 1673 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBeUndefined(); |
| 1674 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider).toEqual({}); |
| 1675 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("keep this follow-up"); |
| 1676 | }, |
| 1677 | ); |
| 1678 | |
| 1679 | it("releases an inactive thread pick only after its queued model becomes durable", () => { |
| 1680 | const store = useComposerDraftStore.getState(); |
| 1681 | const pick = modelSelection(CODEX_DRIVER, "gpt-5.5", { fastMode: false }); |
| 1682 | store.setPrompt(threadRef, "keep this unsent follow-up"); |
| 1683 | store.addImage(threadRef, makeImage({ id: "image", previewUrl: "blob:keep-image" })); |
| 1684 | store.setTerminalContexts(threadRef, [makeTerminalContext({ id: "terminal" })]); |
| 1685 | store.setRuntimeMode(threadRef, "approval-required"); |
| 1686 | store.setInteractionMode(threadRef, "plan"); |
| 1687 | store.setModelSelection(threadRef, pick, { explicit: true }); |
| 1688 | const before = draftFor(threadId, TEST_ENVIRONMENT_ID)!; |
| 1689 | const remoteRef = scopeThreadRef(OTHER_TEST_ENVIRONMENT_ID, threadId); |
| 1690 | store.setModelSelection(remoteRef, pick, { explicit: true }); |
| 1691 | const remoteBefore = draftFor(threadId, OTHER_TEST_ENVIRONMENT_ID); |
| 1692 | const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId); |
| 1693 | |
| 1694 | h.update({ status: "queued" }); |
| 1695 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before); |
| 1696 | h.update({ status: "running", modelSelection: modelSelection(CODEX_DRIVER, "gpt-5.5") }); |
| 1697 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual({ |
| 1698 | ...before, |
| 1699 | activeProvider: null, |
| 1700 | modelSelectionByProvider: {}, |
| 1701 | modelSelectionExplicit: undefined, |
| 1702 | }); |
| 1703 | expect(draftFor(threadId, OTHER_TEST_ENVIRONMENT_ID)).toEqual(remoteBefore); |
| 1704 | |
| 1705 | const remoteModel = DEFAULT_MODEL_BY_PROVIDER[CLAUDE_AGENT_DRIVER]!; |
| 1706 | h.update({ modelSelection: modelSelection(CLAUDE_AGENT_DRIVER, remoteModel) }); |
| 1707 | const effective = deriveEffectiveComposerModelState({ |
| 1708 | threadStarted: false, |
| 1709 | draft: draftFor(threadId, TEST_ENVIRONMENT_ID), |
| 1710 | providers: [ |
| 1711 | { |
| 1712 | instanceId: CLAUDE_AGENT_INSTANCE, |
| 1713 | driver: CLAUDE_AGENT_DRIVER, |
| 1714 | enabled: true, |
| 1715 | installed: true, |
| 1716 | version: null, |
| 1717 | status: "ready", |
| 1718 | auth: { status: "authenticated" }, |
| 1719 | checkedAt: "2026-01-01T00:00:00.000Z", |
| 1720 | models: [{ slug: remoteModel, name: remoteModel, isCustom: false, capabilities: {} }], |
| 1721 | slashCommands: [], |
| 1722 | skills: [], |
| 1723 | }, |
| 1724 | ], |
| 1725 | selectedProvider: CLAUDE_AGENT_DRIVER, |
| 1726 | selectedInstanceId: CLAUDE_AGENT_INSTANCE, |
| 1727 | threadModelSelection: h.model(), |
| 1728 | projectModelSelection: null, |
| 1729 | settings: DEFAULT_UNIFIED_SETTINGS, |
| 1730 | }); |
| 1731 | expect(effective.selectedModel).toBe(remoteModel); |
| 1732 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider).toEqual({}); |
| 1733 | }); |
| 1734 | |
| 1735 | it("retains an unavailable provider pick through differing durable model updates", () => { |
| 1736 | const store = useComposerDraftStore.getState(); |
| 1737 | const pick = createModelSelection(CODEX_SECONDARY_INSTANCE, "gpt-5.5", [ |
| 1738 | { id: "reasoningEffort", value: "high" }, |
| 1739 | { id: "fastMode", value: true }, |
| 1740 | ]); |
| 1741 | // A remembered primary pick is the visible fallback while the secondary is unavailable. |
| 1742 | const primary = modelSelection(CODEX_DRIVER, DEFAULT_MODEL); |
| 1743 | store.setModelSelection(threadRef, primary); |
| 1744 | store.setModelSelection(threadRef, pick, { explicit: true }); |
| 1745 | const before = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 1746 | const h = modelReconciliationHarness(TEST_ENVIRONMENT_ID, threadId); |
| 1747 | h.update({ modelSelection: primary }); |
| 1748 | const fallback = deriveEffectiveComposerModelState({ |
| 1749 | threadStarted: false, |
| 1750 | draft: before, |
| 1751 | providers: [], |
| 1752 | selectedProvider: CODEX_DRIVER, |
| 1753 | selectedInstanceId: CODEX_INSTANCE, |
| 1754 | threadModelSelection: h.model(), |
| 1755 | projectModelSelection: null, |
| 1756 | settings: DEFAULT_UNIFIED_SETTINGS, |
| 1757 | }); |
| 1758 | expect(fallback.selectedModel).toBe(h.model().model); |
| 1759 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before); |
| 1760 | |
| 1761 | for (const modelSelection of [ |
| 1762 | { ...pick, instanceId: CODEX_INSTANCE }, |
| 1763 | { ...pick, model: "gpt-5.4" }, |
| 1764 | { ...pick, options: [{ id: "reasoningEffort", value: "high" }] }, |
| 1765 | { |
| 1766 | ...pick, |
| 1767 | options: [ |
| 1768 | { id: "reasoningEffort", value: "low" }, |
| 1769 | { id: "fastMode", value: true }, |
| 1770 | ], |
| 1771 | }, |
| 1772 | ]) { |
| 1773 | h.update({ modelSelection }); |
| 1774 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toEqual(before); |
| 1775 | } |
| 1776 | h.update({ modelSelection: { ...pick, options: pick.options!.toReversed() } }); |
| 1777 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined(); |
| 1778 | }); |
| 1779 | |
| 1780 | it("marks picker writes explicit and seeding writes non-explicit", () => { |
| 1781 | const store = useComposerDraftStore.getState(); |
| 1782 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4")); |
| 1783 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBeUndefined(); |
| 1784 | |
| 1785 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), { |
| 1786 | explicit: true, |
| 1787 | }); |
| 1788 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBe(true); |
| 1789 | |
| 1790 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), { |
| 1791 | replaceOptions: true, |
| 1792 | }); |
| 1793 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBeUndefined(); |
| 1794 | }); |
| 1795 | |
| 1796 | it("replaces only the targeted provider options on the current model selection", () => { |
| 1797 | const store = useComposerDraftStore.getState(); |
| 1798 | |
| 1799 | store.setModelSelection( |
| 1800 | threadRef, |
| 1801 | modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { |
| 1802 | effort: "max", |
| 1803 | fastMode: true, |
| 1804 | }), |
| 1805 | ); |
| 1806 | store.setStickyModelSelection( |
| 1807 | modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { |
| 1808 | effort: "max", |
| 1809 | fastMode: true, |
| 1810 | }), |
| 1811 | ); |
| 1812 | |
| 1813 | store.setProviderModelOptions( |
| 1814 | threadRef, |
| 1815 | CLAUDE_AGENT_DRIVER, |
| 1816 | toSelections({ thinking: false }), |
| 1817 | { |
| 1818 | persistSticky: true, |
| 1819 | }, |
| 1820 | ); |
| 1821 | |
| 1822 | expect( |
| 1823 | draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CLAUDE_AGENT_INSTANCE], |
| 1824 | ).toEqual( |
| 1825 | modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { |
| 1826 | thinking: false, |
| 1827 | }), |
| 1828 | ); |
| 1829 | expect( |
| 1830 | useComposerDraftStore.getState().stickyModelSelectionByProvider[CLAUDE_AGENT_INSTANCE], |
| 1831 | ).toEqual( |
| 1832 | modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6", { |
| 1833 | thinking: false, |
| 1834 | }), |
| 1835 | ); |
| 1836 | }); |
| 1837 | |
| 1838 | // regression: #6011 new threads ignored project default models unless edits are marked explicit |
| 1839 | it("marks trait edits as explicit model intent", () => { |
| 1840 | const store = useComposerDraftStore.getState(); |
| 1841 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4")); |
| 1842 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBeUndefined(); |
| 1843 | |
| 1844 | store.setProviderModelOptions( |
| 1845 | threadRef, |
| 1846 | CODEX_DRIVER, |
| 1847 | toSelections({ reasoningEffort: "xhigh" }), |
| 1848 | ); |
| 1849 | |
| 1850 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionExplicit).toBe(true); |
| 1851 | expect( |
| 1852 | draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_INSTANCE], |
| 1853 | ).toEqual(modelSelection(CODEX_DRIVER, "gpt-5.4", { reasoningEffort: "xhigh" })); |
| 1854 | }); |
| 1855 | |
| 1856 | describe("seeded draft model on a started thread", () => { |
| 1857 | const providers: ReadonlyArray<ServerProvider> = [ |
| 1858 | { |
| 1859 | instanceId: CODEX_INSTANCE, |
| 1860 | driver: CODEX_DRIVER, |
| 1861 | enabled: true, |
| 1862 | installed: true, |
| 1863 | version: null, |
| 1864 | status: "ready", |
| 1865 | auth: { status: "authenticated" }, |
| 1866 | checkedAt: "2026-01-01T00:00:00.000Z", |
| 1867 | models: ["gpt-5.4", "gpt-5.3-codex"].map((slug) => ({ |
| 1868 | slug, |
| 1869 | name: slug, |
| 1870 | isCustom: false, |
| 1871 | capabilities: {}, |
| 1872 | })), |
| 1873 | slashCommands: [], |
| 1874 | skills: [], |
| 1875 | }, |
| 1876 | ]; |
| 1877 | const threadSelection = modelSelection(CODEX_DRIVER, "gpt-5.3-codex", { |
| 1878 | reasoningEffort: "low", |
| 1879 | }); |
| 1880 | const effective = (threadStarted: boolean, baseSelection = threadSelection) => { |
| 1881 | const state = deriveEffectiveComposerModelState({ |
| 1882 | draft: useComposerDraftStore.getState().getComposerDraft(threadRef), |
| 1883 | threadStarted, |
| 1884 | providers, |
| 1885 | selectedProvider: CODEX_DRIVER, |
| 1886 | selectedInstanceId: CODEX_INSTANCE, |
| 1887 | threadModelSelection: baseSelection, |
| 1888 | projectModelSelection: null, |
| 1889 | settings: DEFAULT_UNIFIED_SETTINGS, |
| 1890 | }); |
| 1891 | return { |
| 1892 | model: state.selectedModel, |
| 1893 | options: state.modelOptions?.[CODEX_INSTANCE] ?? [], |
| 1894 | }; |
| 1895 | }; |
| 1896 | |
| 1897 | it("applies the seed only until the thread starts, then only an explicit pick wins", () => { |
| 1898 | const store = useComposerDraftStore.getState(); |
| 1899 | store.setModelSelection( |
| 1900 | threadRef, |
| 1901 | modelSelection(CODEX_DRIVER, "gpt-5.4", { reasoningEffort: "high" }), |
| 1902 | ); |
| 1903 | |
| 1904 | expect(effective(false)).toEqual({ |
| 1905 | model: "gpt-5.4", |
| 1906 | options: toSelections({ reasoningEffort: "high" }), |
| 1907 | }); |
| 1908 | expect(effective(true)).toEqual({ |
| 1909 | model: "gpt-5.3-codex", |
| 1910 | options: toSelections({ reasoningEffort: "low" }), |
| 1911 | }); |
| 1912 | |
| 1913 | store.setModelSelection( |
| 1914 | threadRef, |
| 1915 | modelSelection(CODEX_DRIVER, "gpt-5.4", { reasoningEffort: "high" }), |
| 1916 | { explicit: true }, |
| 1917 | ); |
| 1918 | expect(effective(true)).toEqual({ |
| 1919 | model: "gpt-5.4", |
| 1920 | options: toSelections({ reasoningEffort: "high" }), |
| 1921 | }); |
| 1922 | }); |
| 1923 | |
| 1924 | it.each([false, true])( |
| 1925 | "an explicit optionless pick overrides base traits when threadStarted=%s", |
| 1926 | (threadStarted) => { |
| 1927 | const store = useComposerDraftStore.getState(); |
| 1928 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), { |
| 1929 | explicit: true, |
| 1930 | replaceOptions: true, |
| 1931 | }); |
| 1932 | expect(effective(threadStarted)).toEqual({ model: "gpt-5.4", options: [] }); |
| 1933 | }, |
| 1934 | ); |
| 1935 | |
| 1936 | it("restores saved traits when the base model uses an alias", () => { |
| 1937 | useComposerDraftStore |
| 1938 | .getState() |
| 1939 | .setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4"), { |
| 1940 | explicit: true, |
| 1941 | replaceOptions: true, |
| 1942 | }); |
| 1943 | expect( |
| 1944 | effective(true, modelSelection(CODEX_DRIVER, "5.4", { reasoningEffort: "low" })), |
| 1945 | ).toEqual({ model: "gpt-5.4", options: toSelections({ reasoningEffort: "low" }) }); |
| 1946 | }); |
| 1947 | |
| 1948 | it("keeps the thread's model when traits change over a seed", () => { |
| 1949 | const store = useComposerDraftStore.getState(); |
| 1950 | store.setModelSelection(threadRef, modelSelection(CODEX_DRIVER, "gpt-5.4")); |
| 1951 | store.setProviderModelOptions( |
| 1952 | threadRef, |
| 1953 | CODEX_DRIVER, |
| 1954 | toSelections({ reasoningEffort: "high" }), |
| 1955 | { instanceId: CODEX_INSTANCE, model: "gpt-5.3-codex" }, |
| 1956 | ); |
| 1957 | |
| 1958 | expect(effective(true)).toEqual({ |
| 1959 | model: "gpt-5.3-codex", |
| 1960 | options: toSelections({ reasoningEffort: "high" }), |
| 1961 | }); |
| 1962 | }); |
| 1963 | }); |
| 1964 | |
| 1965 | it("stores provider option changes on a selected custom instance", () => { |
| 1966 | const store = useComposerDraftStore.getState(); |
| 1967 | |
| 1968 | store.setProviderModelOptions( |
| 1969 | threadRef, |
| 1970 | CODEX_DRIVER, |
| 1971 | toSelections({ reasoningEffort: "low" }), |
| 1972 | { |
| 1973 | instanceId: CODEX_SECONDARY_INSTANCE, |
| 1974 | model: "gpt-5-codex", |
| 1975 | persistSticky: true, |
| 1976 | }, |
| 1977 | ); |
| 1978 | |
| 1979 | expect( |
| 1980 | draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_SECONDARY_INSTANCE], |
| 1981 | ).toEqual( |
| 1982 | expect.objectContaining({ |
| 1983 | instanceId: CODEX_SECONDARY_INSTANCE, |
| 1984 | model: "gpt-5-codex", |
| 1985 | options: [{ id: "reasoningEffort", value: "low" }], |
| 1986 | }), |
| 1987 | ); |
| 1988 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.activeProvider).toBe(CODEX_SECONDARY_INSTANCE); |
| 1989 | expect(useComposerDraftStore.getState().stickyActiveProvider).toBe(CODEX_SECONDARY_INSTANCE); |
| 1990 | expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toBe( |
| 1991 | undefined, |
| 1992 | ); |
| 1993 | expect( |
| 1994 | useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_SECONDARY_INSTANCE], |
| 1995 | ).toEqual( |
| 1996 | expect.objectContaining({ |
| 1997 | instanceId: CODEX_SECONDARY_INSTANCE, |
| 1998 | options: [{ id: "reasoningEffort", value: "low" }], |
| 1999 | }), |
| 2000 | ); |
| 2001 | expect( |
| 2002 | useComposerDraftStore.getState().stickyOptionsByModelByProvider[CODEX_SECONDARY_INSTANCE], |
| 2003 | ).toEqual({ "gpt-5-codex": [{ id: "reasoningEffort", value: "low" }] }); |
| 2004 | |
| 2005 | // A custom slug that matches a Codex alias stays exact; the picker already resolved it. |
| 2006 | store.setModelSelection(threadRef, createModelSelection(CODEX_SECONDARY_INSTANCE, "gpt-5.3"), { |
| 2007 | explicit: true, |
| 2008 | replaceOptions: true, |
| 2009 | }); |
| 2010 | expect( |
| 2011 | draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CODEX_SECONDARY_INSTANCE] |
| 2012 | ?.model, |
| 2013 | ).toBe("gpt-5.3"); |
| 2014 | }); |
| 2015 | }); |
| 2016 | |
| 2017 | describe("composerDraftStore per-model sticky options", () => { |
| 2018 | const threadId = ThreadId.make("thread-per-model-options"); |
| 2019 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 2020 | |
| 2021 | beforeEach(() => { |
| 2022 | resetComposerDraftStore(); |
| 2023 | }); |
| 2024 | |
| 2025 | it("remembers sticky options per model and restores them on model switch", () => { |
| 2026 | const store = useComposerDraftStore.getState(); |
| 2027 | |
| 2028 | store.setProviderModelOptions( |
| 2029 | threadRef, |
| 2030 | CODEX_DRIVER, |
| 2031 | toSelections({ reasoningEffort: "xhigh" }), |
| 2032 | { instanceId: CODEX_INSTANCE, model: "gpt-5.3-codex", persistSticky: true }, |
| 2033 | ); |
| 2034 | store.setProviderModelOptions( |
| 2035 | threadRef, |
| 2036 | CODEX_DRIVER, |
| 2037 | toSelections({ reasoningEffort: "high" }), |
| 2038 | { instanceId: CODEX_INSTANCE, model: "gpt-5.4", persistSticky: true }, |
| 2039 | ); |
| 2040 | |
| 2041 | expect(useComposerDraftStore.getState().stickyOptionsByModelByProvider[CODEX_INSTANCE]).toEqual( |
| 2042 | { |
| 2043 | "gpt-5.3-codex": toSelections({ reasoningEffort: "xhigh" }), |
| 2044 | "gpt-5.4": toSelections({ reasoningEffort: "high" }), |
| 2045 | }, |
| 2046 | ); |
| 2047 | }); |
| 2048 | |
| 2049 | it("keeps the sticky model's own traits when traits change on another shown model", () => { |
| 2050 | const store = useComposerDraftStore.getState(); |
| 2051 | store.setStickyModelSelection( |
| 2052 | modelSelection(CODEX_DRIVER, "gpt-5.3-codex", { reasoningEffort: "xhigh" }), |
| 2053 | ); |
| 2054 | |
| 2055 | store.setProviderModelOptions( |
| 2056 | threadRef, |
| 2057 | CODEX_DRIVER, |
| 2058 | toSelections({ reasoningEffort: "low" }), |
| 2059 | { instanceId: CODEX_INSTANCE, model: "gpt-5.4", persistSticky: true }, |
| 2060 | ); |
| 2061 | expect(useComposerDraftStore.getState().stickyModelSelectionByProvider[CODEX_INSTANCE]).toEqual( |
| 2062 | modelSelection(CODEX_DRIVER, "gpt-5.3-codex", { reasoningEffort: "xhigh" }), |
| 2063 | ); |
| 2064 | expect( |
| 2065 | useComposerDraftStore.getState().stickyOptionsByModelByProvider[CODEX_INSTANCE]?.["gpt-5.4"], |
| 2066 | ).toEqual(toSelections({ reasoningEffort: "low" })); |
| 2067 | |
| 2068 | store.setProviderModelOptions(threadRef, CODEX_DRIVER, null, { |
| 2069 | instanceId: CODEX_INSTANCE, |
| 2070 | model: "gpt-5.4", |
| 2071 | persistSticky: true, |
| 2072 | }); |
| 2073 | |
| 2074 | const state = useComposerDraftStore.getState(); |
| 2075 | expect(state.stickyModelSelectionByProvider[CODEX_INSTANCE]).toEqual( |
| 2076 | modelSelection(CODEX_DRIVER, "gpt-5.3-codex", { reasoningEffort: "xhigh" }), |
| 2077 | ); |
| 2078 | expect(state.stickyOptionsByModelByProvider[CODEX_INSTANCE]?.["gpt-5.4"]).toBeUndefined(); |
| 2079 | }); |
| 2080 | |
| 2081 | it("seeds per-model memory from a persisted sticky selection on upgrade", () => { |
| 2082 | const persistApi = useComposerDraftStore.persist as unknown as { |
| 2083 | getOptions: () => { |
| 2084 | merge: ( |
| 2085 | persistedState: unknown, |
| 2086 | currentState: ReturnType<typeof useComposerDraftStore.getState>, |
| 2087 | ) => Pick< |
| 2088 | ReturnType<typeof useComposerDraftStore.getState>, |
| 2089 | "stickyModelSelectionByProvider" | "stickyOptionsByModelByProvider" |
| 2090 | >; |
| 2091 | }; |
| 2092 | }; |
| 2093 | const mergedState = persistApi.getOptions().merge( |
| 2094 | { |
| 2095 | stickyModelSelectionByProvider: { |
| 2096 | [CODEX_INSTANCE]: { |
| 2097 | instanceId: CODEX_INSTANCE, |
| 2098 | model: "gpt-5.3-codex", |
| 2099 | options: [{ id: "reasoningEffort", value: "low" }], |
| 2100 | }, |
| 2101 | }, |
| 2102 | }, |
| 2103 | useComposerDraftStore.getInitialState(), |
| 2104 | ); |
| 2105 | |
| 2106 | expect(mergedState.stickyOptionsByModelByProvider).toEqual({ |
| 2107 | [CODEX_INSTANCE]: { "gpt-5.3-codex": [{ id: "reasoningEffort", value: "low" }] }, |
| 2108 | }); |
| 2109 | }); |
| 2110 | }); |
| 2111 | |
| 2112 | describe("composerDraftStore sticky composer settings", () => { |
| 2113 | beforeEach(() => { |
| 2114 | resetComposerDraftStore(); |
| 2115 | }); |
| 2116 | |
| 2117 | it("preserves sticky provider options when model selection omits options", () => { |
| 2118 | const store = useComposerDraftStore.getState(); |
| 2119 | |
| 2120 | store.setStickyModelSelection( |
| 2121 | modelSelection(CURSOR_DRIVER, "composer-2", { |
| 2122 | fastMode: false, |
| 2123 | }), |
| 2124 | ); |
| 2125 | store.setStickyModelSelection(modelSelection(CURSOR_DRIVER, "composer-2.5")); |
| 2126 | |
| 2127 | expect( |
| 2128 | useComposerDraftStore.getState().stickyModelSelectionByProvider[CURSOR_INSTANCE], |
| 2129 | ).toEqual( |
| 2130 | modelSelection(CURSOR_DRIVER, "composer-2.5", { |
| 2131 | fastMode: false, |
| 2132 | }), |
| 2133 | ); |
| 2134 | }); |
| 2135 | |
| 2136 | it("applies sticky activeProvider to new drafts", () => { |
| 2137 | const store = useComposerDraftStore.getState(); |
| 2138 | const threadId = ThreadId.make("thread-sticky-active-provider"); |
| 2139 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 2140 | |
| 2141 | store.setStickyModelSelection(modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6")); |
| 2142 | store.applyStickyState(threadRef); |
| 2143 | |
| 2144 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toMatchObject({ |
| 2145 | modelSelectionByProvider: { |
| 2146 | claudeAgent: modelSelection(CLAUDE_AGENT_DRIVER, "claude-opus-4-6"), |
| 2147 | }, |
| 2148 | activeProvider: "claudeAgent", |
| 2149 | }); |
| 2150 | }); |
| 2151 | |
| 2152 | it("replaces a non-explicit stale model and its options with sticky state", () => { |
| 2153 | const store = useComposerDraftStore.getState(); |
| 2154 | const draftId = DraftId.make("draft-stale-sticky-seed"); |
| 2155 | |
| 2156 | store.setModelSelection( |
| 2157 | draftId, |
| 2158 | modelSelection(CODEX_DRIVER, "stale-model", { reasoningEffort: "low" }), |
| 2159 | ); |
| 2160 | store.setStickyModelSelection( |
| 2161 | modelSelection(CODEX_DRIVER, "sticky-model", { reasoningEffort: "xhigh" }), |
| 2162 | ); |
| 2163 | store.applyStickyState(draftId); |
| 2164 | |
| 2165 | expect(draftByKey(draftId)).toMatchObject({ |
| 2166 | activeProvider: CODEX_INSTANCE, |
| 2167 | modelSelectionByProvider: { |
| 2168 | [CODEX_INSTANCE]: modelSelection(CODEX_DRIVER, "sticky-model", { |
| 2169 | reasoningEffort: "xhigh", |
| 2170 | }), |
| 2171 | }, |
| 2172 | }); |
| 2173 | }); |
| 2174 | |
| 2175 | // regression: #6011 a stale seeded model overrode the project default |
| 2176 | it("clears a non-explicit stale model when there is no sticky state", () => { |
| 2177 | const store = useComposerDraftStore.getState(); |
| 2178 | const draftId = DraftId.make("draft-stale-without-sticky"); |
| 2179 | |
| 2180 | store.setModelSelection(draftId, modelSelection(CODEX_DRIVER, "stale-model")); |
| 2181 | store.applyStickyState(draftId); |
| 2182 | |
| 2183 | expect(draftByKey(draftId)).toBeUndefined(); |
| 2184 | }); |
| 2185 | }); |
| 2186 | |
| 2187 | describe("composerDraftStore model seed migration", () => { |
| 2188 | const staleDraftId = DraftId.make("draft-legacy-stale-model"); |
| 2189 | const explicitDraftId = DraftId.make("draft-legacy-explicit-model"); |
| 2190 | const typedDraftId = DraftId.make("draft-legacy-typed-model"); |
| 2191 | const staleThreadId = ThreadId.make("thread-legacy-stale-model"); |
| 2192 | const explicitThreadId = ThreadId.make("thread-legacy-explicit-model"); |
| 2193 | const typedThreadId = ThreadId.make("thread-legacy-typed-model"); |
| 2194 | const serverThreadId = ThreadId.make("thread-server-model"); |
| 2195 | const serverThreadKey = scopedThreadKey(scopeThreadRef(TEST_ENVIRONMENT_ID, serverThreadId)); |
| 2196 | const projectId = ProjectId.make("project-model-migration"); |
| 2197 | const logicalProjectKey = `${TEST_ENVIRONMENT_ID}:/tmp/project-model-migration`; |
| 2198 | |
| 2199 | const draftThread = (threadId: ThreadId) => ({ |
| 2200 | threadId, |
| 2201 | environmentId: TEST_ENVIRONMENT_ID, |
| 2202 | projectId, |
| 2203 | logicalProjectKey, |
| 2204 | createdAt: "2026-08-01T00:00:00.000Z", |
| 2205 | runtimeMode: "full-access", |
| 2206 | interactionMode: "default", |
| 2207 | branch: null, |
| 2208 | worktreePath: null, |
| 2209 | envMode: "local", |
| 2210 | startFromOrigin: false, |
| 2211 | promotedTo: null, |
| 2212 | }); |
| 2213 | |
| 2214 | beforeEach(async () => { |
| 2215 | resetComposerDraftStore(); |
| 2216 | await useComposerDraftStore.persist.clearStorage(); |
| 2217 | }); |
| 2218 | |
| 2219 | afterEach(async () => { |
| 2220 | await useComposerDraftStore.persist.clearStorage(); |
| 2221 | }); |
| 2222 | |
| 2223 | it.each([1, 2])( |
| 2224 | "keeps the legacy sticky Codex selection when v%s storage omitted the provider", |
| 2225 | async (version) => { |
| 2226 | vi.useFakeTimers(); |
| 2227 | try { |
| 2228 | const stickySelection = modelSelection(CODEX_DRIVER, "gpt-5.6-terra", { |
| 2229 | reasoningEffort: "xhigh", |
| 2230 | }); |
| 2231 | const storage = useComposerDraftStore.persist.getOptions().storage; |
| 2232 | expect(storage).toBeDefined(); |
| 2233 | storage?.setItem(COMPOSER_DRAFT_STORAGE_KEY, { |
| 2234 | version, |
| 2235 | state: { |
| 2236 | draftsByThreadId: {}, |
| 2237 | draftThreadsByThreadId: {}, |
| 2238 | projectDraftThreadIdByProjectId: {}, |
| 2239 | stickyModel: stickySelection.model, |
| 2240 | stickyModelOptions: providerModelOptions({ |
| 2241 | [CODEX_DRIVER]: { reasoningEffort: "xhigh" }, |
| 2242 | }), |
| 2243 | }, |
| 2244 | } as never); |
| 2245 | await vi.advanceTimersByTimeAsync(300); |
| 2246 | |
| 2247 | await useComposerDraftStore.persist.rehydrate(); |
| 2248 | |
| 2249 | expect(useComposerDraftStore.getState()).toMatchObject({ |
| 2250 | stickyModelSelectionByProvider: { [CODEX_INSTANCE]: stickySelection }, |
| 2251 | stickyActiveProvider: null, |
| 2252 | }); |
| 2253 | } finally { |
| 2254 | vi.useRealTimers(); |
| 2255 | } |
| 2256 | }, |
| 2257 | ); |
| 2258 | |
| 2259 | it("strips seeded models only from empty draft sessions when upgrading storage", async () => { |
| 2260 | vi.useFakeTimers(); |
| 2261 | try { |
| 2262 | const staleSelection = modelSelection(CODEX_DRIVER, "gpt-5.4"); |
| 2263 | const stickySelection = modelSelection(CODEX_DRIVER, "gpt-5.6-terra", { |
| 2264 | reasoningEffort: "xhigh", |
| 2265 | }); |
| 2266 | const storage = useComposerDraftStore.persist.getOptions().storage; |
| 2267 | expect(storage).toBeDefined(); |
| 2268 | storage?.setItem(COMPOSER_DRAFT_STORAGE_KEY, { |
| 2269 | version: 8, |
| 2270 | state: { |
| 2271 | draftsByThreadKey: { |
| 2272 | [staleDraftId]: { |
| 2273 | prompt: "", |
| 2274 | attachments: [], |
| 2275 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2276 | activeProvider: CODEX_INSTANCE, |
| 2277 | runtimeMode: "approval-required", |
| 2278 | }, |
| 2279 | [typedDraftId]: { |
| 2280 | prompt: "keep this prompt", |
| 2281 | attachments: [], |
| 2282 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2283 | activeProvider: CODEX_INSTANCE, |
| 2284 | }, |
| 2285 | [explicitDraftId]: { |
| 2286 | prompt: "", |
| 2287 | attachments: [], |
| 2288 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2289 | activeProvider: CODEX_INSTANCE, |
| 2290 | modelSelectionExplicit: true, |
| 2291 | }, |
| 2292 | [serverThreadKey]: { |
| 2293 | prompt: "", |
| 2294 | attachments: [], |
| 2295 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2296 | activeProvider: CODEX_INSTANCE, |
| 2297 | }, |
| 2298 | }, |
| 2299 | draftThreadsByThreadKey: { |
| 2300 | [staleDraftId]: draftThread(staleThreadId), |
| 2301 | [explicitDraftId]: draftThread(explicitThreadId), |
| 2302 | [typedDraftId]: draftThread(typedThreadId), |
| 2303 | }, |
| 2304 | logicalProjectDraftThreadKeyByLogicalProjectKey: { |
| 2305 | [logicalProjectKey]: staleDraftId, |
| 2306 | }, |
| 2307 | stickyModelSelectionByProvider: { [CODEX_INSTANCE]: stickySelection }, |
| 2308 | stickyActiveProvider: CODEX_INSTANCE, |
| 2309 | }, |
| 2310 | } as never); |
| 2311 | await vi.advanceTimersByTimeAsync(300); |
| 2312 | |
| 2313 | await useComposerDraftStore.persist.rehydrate(); |
| 2314 | |
| 2315 | expect(draftByKey(staleDraftId)).toMatchObject({ |
| 2316 | modelSelectionByProvider: {}, |
| 2317 | activeProvider: null, |
| 2318 | runtimeMode: "approval-required", |
| 2319 | }); |
| 2320 | expect(draftByKey(typedDraftId)).toMatchObject({ |
| 2321 | prompt: "keep this prompt", |
| 2322 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2323 | activeProvider: CODEX_INSTANCE, |
| 2324 | }); |
| 2325 | expect(draftByKey(explicitDraftId)).toMatchObject({ |
| 2326 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2327 | activeProvider: CODEX_INSTANCE, |
| 2328 | modelSelectionExplicit: true, |
| 2329 | }); |
| 2330 | expect(draftByKey(serverThreadKey)).toMatchObject({ |
| 2331 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2332 | activeProvider: CODEX_INSTANCE, |
| 2333 | }); |
| 2334 | expect(useComposerDraftStore.getState().draftThreadsByThreadKey[staleDraftId]).toMatchObject({ |
| 2335 | environmentId: TEST_ENVIRONMENT_ID, |
| 2336 | projectId, |
| 2337 | logicalProjectKey, |
| 2338 | }); |
| 2339 | expect(useComposerDraftStore.getState()).toMatchObject({ |
| 2340 | stickyModelSelectionByProvider: { [CODEX_INSTANCE]: stickySelection }, |
| 2341 | stickyActiveProvider: CODEX_INSTANCE, |
| 2342 | }); |
| 2343 | } finally { |
| 2344 | vi.useRealTimers(); |
| 2345 | } |
| 2346 | }); |
| 2347 | |
| 2348 | it("keeps v8 file-only draft sessions and their seeded models", async () => { |
| 2349 | vi.useFakeTimers(); |
| 2350 | try { |
| 2351 | const uploadedDraftId = DraftId.make("draft-legacy-uploaded-file"); |
| 2352 | const markerDraftId = DraftId.make("draft-legacy-file-marker"); |
| 2353 | const uploadedThreadId = ThreadId.make("thread-legacy-uploaded-file"); |
| 2354 | const markerThreadId = ThreadId.make("thread-legacy-file-marker"); |
| 2355 | const staleSelection = modelSelection(CODEX_DRIVER, "gpt-5.4"); |
| 2356 | const storage = useComposerDraftStore.persist.getOptions().storage; |
| 2357 | expect(storage).toBeDefined(); |
| 2358 | storage?.setItem(COMPOSER_DRAFT_STORAGE_KEY, { |
| 2359 | version: 8, |
| 2360 | state: { |
| 2361 | draftsByThreadKey: { |
| 2362 | [uploadedDraftId]: { |
| 2363 | prompt: "", |
| 2364 | attachments: [], |
| 2365 | files: [ |
| 2366 | { |
| 2367 | id: "file-uploaded", |
| 2368 | name: "uploaded-report.pdf", |
| 2369 | mimeType: "application/pdf", |
| 2370 | sizeBytes: 128, |
| 2371 | attachmentId: "attachment-uploaded", |
| 2372 | environmentId: TEST_ENVIRONMENT_ID, |
| 2373 | }, |
| 2374 | ], |
| 2375 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2376 | activeProvider: CODEX_INSTANCE, |
| 2377 | }, |
| 2378 | [markerDraftId]: { |
| 2379 | prompt: "", |
| 2380 | attachments: [], |
| 2381 | files: [ |
| 2382 | { |
| 2383 | id: "file-needs-reattach", |
| 2384 | name: "local-notes.txt", |
| 2385 | mimeType: "text/plain", |
| 2386 | sizeBytes: 64, |
| 2387 | }, |
| 2388 | ], |
| 2389 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2390 | activeProvider: CODEX_INSTANCE, |
| 2391 | runtimeMode: "approval-required", |
| 2392 | }, |
| 2393 | }, |
| 2394 | draftThreadsByThreadKey: { |
| 2395 | [uploadedDraftId]: draftThread(uploadedThreadId), |
| 2396 | [markerDraftId]: draftThread(markerThreadId), |
| 2397 | }, |
| 2398 | logicalProjectDraftThreadKeyByLogicalProjectKey: {}, |
| 2399 | stickyModelSelectionByProvider: {}, |
| 2400 | stickyActiveProvider: null, |
| 2401 | }, |
| 2402 | } as never); |
| 2403 | await vi.advanceTimersByTimeAsync(300); |
| 2404 | |
| 2405 | await useComposerDraftStore.persist.rehydrate(); |
| 2406 | |
| 2407 | expect(draftByKey(uploadedDraftId)).toMatchObject({ |
| 2408 | files: [ |
| 2409 | { |
| 2410 | id: "file-uploaded", |
| 2411 | name: "uploaded-report.pdf", |
| 2412 | uploadedAttachmentId: "attachment-uploaded", |
| 2413 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 2414 | }, |
| 2415 | ], |
| 2416 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2417 | activeProvider: CODEX_INSTANCE, |
| 2418 | }); |
| 2419 | expect(draftByKey(markerDraftId)).toMatchObject({ |
| 2420 | files: [ |
| 2421 | { |
| 2422 | id: "file-needs-reattach", |
| 2423 | name: "local-notes.txt", |
| 2424 | file: null, |
| 2425 | }, |
| 2426 | ], |
| 2427 | modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection }, |
| 2428 | activeProvider: CODEX_INSTANCE, |
| 2429 | runtimeMode: "approval-required", |
| 2430 | }); |
| 2431 | expect(draftByKey(markerDraftId)?.files.every(composerFileNeedsReattach)).toBe(true); |
| 2432 | } finally { |
| 2433 | vi.useRealTimers(); |
| 2434 | } |
| 2435 | }); |
| 2436 | |
| 2437 | it("upgrades v5 selections that name a provider and keep options in an object", async () => { |
| 2438 | vi.useFakeTimers(); |
| 2439 | try { |
| 2440 | const legacySelection = { |
| 2441 | provider: "codex", |
| 2442 | model: "gpt-5.4", |
| 2443 | options: { reasoningEffort: "high", fastMode: true }, |
| 2444 | }; |
| 2445 | const storage = useComposerDraftStore.persist.getOptions().storage; |
| 2446 | expect(storage).toBeDefined(); |
| 2447 | storage?.setItem(COMPOSER_DRAFT_STORAGE_KEY, { |
| 2448 | version: 5, |
| 2449 | state: { |
| 2450 | draftsByThreadKey: { |
| 2451 | [serverThreadKey]: { |
| 2452 | prompt: "keep this draft", |
| 2453 | attachments: [], |
| 2454 | modelSelectionByProvider: { codex: legacySelection }, |
| 2455 | activeProvider: "codex", |
| 2456 | }, |
| 2457 | }, |
| 2458 | draftThreadsByThreadKey: {}, |
| 2459 | stickyModelSelectionByProvider: { codex: legacySelection }, |
| 2460 | stickyActiveProvider: "codex", |
| 2461 | }, |
| 2462 | } as never); |
| 2463 | await vi.advanceTimersByTimeAsync(300); |
| 2464 | |
| 2465 | await useComposerDraftStore.persist.rehydrate(); |
| 2466 | |
| 2467 | const upgraded = modelSelection(CODEX_DRIVER, "gpt-5.4", { |
| 2468 | reasoningEffort: "high", |
| 2469 | fastMode: true, |
| 2470 | }); |
| 2471 | expect(draftByKey(serverThreadKey)).toMatchObject({ |
| 2472 | prompt: "keep this draft", |
| 2473 | modelSelectionByProvider: { [CODEX_INSTANCE]: upgraded }, |
| 2474 | }); |
| 2475 | expect(useComposerDraftStore.getState().stickyModelSelectionByProvider).toEqual({ |
| 2476 | [CODEX_INSTANCE]: upgraded, |
| 2477 | }); |
| 2478 | } finally { |
| 2479 | vi.useRealTimers(); |
| 2480 | } |
| 2481 | }); |
| 2482 | }); |
| 2483 | |
| 2484 | function createMockStorage() { |
| 2485 | const store = new Map<string, string>(); |
| 2486 | return { |
| 2487 | getItem: vi.fn((name: string) => store.get(name) ?? null), |
| 2488 | setItem: vi.fn((name: string, value: string) => { |
| 2489 | store.set(name, value); |
| 2490 | }), |
| 2491 | removeItem: vi.fn((name: string) => { |
| 2492 | store.delete(name); |
| 2493 | }), |
| 2494 | }; |
| 2495 | } |
| 2496 | |
| 2497 | describe("createDeferredStorage", () => { |
| 2498 | const serialize = vi.fn((value: string) => `s:${value}`); |
| 2499 | |
| 2500 | beforeEach(() => { |
| 2501 | vi.useFakeTimers(); |
| 2502 | serialize.mockClear(); |
| 2503 | }); |
| 2504 | |
| 2505 | afterEach(() => { |
| 2506 | vi.useRealTimers(); |
| 2507 | }); |
| 2508 | |
| 2509 | it("removeItem cancels a pending setItem write", () => { |
| 2510 | const base = createMockStorage(); |
| 2511 | const storage = createDeferredStorage(base, serialize); |
| 2512 | |
| 2513 | storage.setItem("key", "v1"); |
| 2514 | storage.removeItem("key"); |
| 2515 | |
| 2516 | vi.advanceTimersByTime(300); |
| 2517 | expect(serialize).not.toHaveBeenCalled(); |
| 2518 | expect(base.setItem).not.toHaveBeenCalled(); |
| 2519 | expect(base.removeItem).toHaveBeenCalledWith("key"); |
| 2520 | }); |
| 2521 | |
| 2522 | it("flush serializes and writes the pending value immediately", () => { |
| 2523 | const base = createMockStorage(); |
| 2524 | const storage = createDeferredStorage(base, serialize); |
| 2525 | |
| 2526 | storage.setItem("key", "v1"); |
| 2527 | expect(base.setItem).not.toHaveBeenCalled(); |
| 2528 | |
| 2529 | storage.flush(); |
| 2530 | expect(base.setItem).toHaveBeenCalledWith("key", "s:v1"); |
| 2531 | |
| 2532 | vi.advanceTimersByTime(300); |
| 2533 | expect(serialize).toHaveBeenCalledTimes(1); |
| 2534 | expect(base.setItem).toHaveBeenCalledTimes(1); |
| 2535 | }); |
| 2536 | }); |
| 2537 | |
| 2538 | describe("composerDraftStore inline context references", () => { |
| 2539 | const threadId = ThreadId.make("thread-inline-context"); |
| 2540 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 2541 | const reviewComment = { |
| 2542 | id: "rc-1", |
| 2543 | sectionId: "file:a/b.ts", |
| 2544 | sectionTitle: "File comment", |
| 2545 | filePath: "a/b.ts", |
| 2546 | startIndex: 3, |
| 2547 | endIndex: 3, |
| 2548 | rangeLabel: "L4", |
| 2549 | text: "Why?", |
| 2550 | diff: "const x = 1;", |
| 2551 | }; |
| 2552 | const reviewLink = "[b.ts L4](t3-context://v1/review-comment/review-comment_rc-1)"; |
| 2553 | const annotation = { |
| 2554 | id: "ann-1", |
| 2555 | pageUrl: "http://localhost:3000/", |
| 2556 | pageTitle: "Home", |
| 2557 | comment: "Bigger", |
| 2558 | elements: [], |
| 2559 | regions: [], |
| 2560 | strokes: [], |
| 2561 | styleChanges: [], |
| 2562 | screenshot: null, |
| 2563 | createdAt: "2026-01-01T00:00:00.000Z", |
| 2564 | }; |
| 2565 | const annotationLink = "[Bigger](t3-context://v1/preview-annotation/preview-annotation_ann-1)"; |
| 2566 | |
| 2567 | beforeEach(() => { |
| 2568 | resetComposerDraftStore(); |
| 2569 | }); |
| 2570 | |
| 2571 | it("appends a link when a review comment is added and strips it on removal", () => { |
| 2572 | const store = useComposerDraftStore.getState(); |
| 2573 | store.setPrompt(threadRef, "look"); |
| 2574 | store.addReviewComment(threadRef, reviewComment); |
| 2575 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe(`look ${reviewLink} `); |
| 2576 | store.addReviewComment(threadRef, { ...reviewComment, text: "edited" }); |
| 2577 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe(`look ${reviewLink} `); |
| 2578 | store.removeReviewComment(threadRef, "rc-1"); |
| 2579 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("look"); |
| 2580 | }); |
| 2581 | |
| 2582 | it("keeps bulk-set review records and their inline references in sync", () => { |
| 2583 | const store = useComposerDraftStore.getState(); |
| 2584 | store.setPrompt(threadRef, "Explain this pull request."); |
| 2585 | store.setReviewComments(threadRef, [reviewComment]); |
| 2586 | |
| 2587 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe( |
| 2588 | `Explain this pull request. ${reviewLink} `, |
| 2589 | ); |
| 2590 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.reviewComments).toEqual([reviewComment]); |
| 2591 | |
| 2592 | store.setReviewComments(threadRef, []); |
| 2593 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("Explain this pull request."); |
| 2594 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.reviewComments).toEqual([]); |
| 2595 | }); |
| 2596 | |
| 2597 | it("hands new review comments to a registered caret handler instead of appending", () => { |
| 2598 | const store = useComposerDraftStore.getState(); |
| 2599 | store.setPrompt(threadRef, "look"); |
| 2600 | const seen: string[] = []; |
| 2601 | store.setContextInsertionHandler(threadRef, (references) => { |
| 2602 | seen.push(...references.map((reference) => reference.contextId)); |
| 2603 | return true; |
| 2604 | }); |
| 2605 | store.addReviewComment(threadRef, reviewComment); |
| 2606 | expect(seen).toEqual(["review-comment_rc-1"]); |
| 2607 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("look"); |
| 2608 | store.setContextInsertionHandler(threadRef, null); |
| 2609 | store.addReviewComment(threadRef, { ...reviewComment, id: "rc-2" }); |
| 2610 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe( |
| 2611 | "look [b.ts L4](t3-context://v1/review-comment/review-comment_rc-2) ", |
| 2612 | ); |
| 2613 | }); |
| 2614 | |
| 2615 | it("does not overwrite a prompt update made by the caret handler", () => { |
| 2616 | const store = useComposerDraftStore.getState(); |
| 2617 | store.setPrompt(threadRef, "before after"); |
| 2618 | store.setContextInsertionHandler(threadRef, (references) => { |
| 2619 | const reference = references[0]; |
| 2620 | if (!reference) return false; |
| 2621 | useComposerDraftStore |
| 2622 | .getState() |
| 2623 | .setPrompt( |
| 2624 | threadRef, |
| 2625 | `before [${reference.label}](t3-context://v1/${reference.kind}/${reference.contextId}) after`, |
| 2626 | ); |
| 2627 | return true; |
| 2628 | }); |
| 2629 | |
| 2630 | store.addReviewComment(threadRef, reviewComment); |
| 2631 | |
| 2632 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe(`before ${reviewLink} after`); |
| 2633 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.reviewComments).toEqual([reviewComment]); |
| 2634 | store.setContextInsertionHandler(threadRef, null); |
| 2635 | }); |
| 2636 | |
| 2637 | it("keeps links for retained context when clearing text and attachments", () => { |
| 2638 | const store = useComposerDraftStore.getState(); |
| 2639 | store.addReviewComment(threadRef, reviewComment); |
| 2640 | store.addPreviewAnnotation(threadRef, annotation); |
| 2641 | store.clearComposerPromptAndImages(threadRef); |
| 2642 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 2643 | expect(draft?.prompt).toContain(reviewLink); |
| 2644 | expect(draft?.prompt).toContain(annotationLink); |
| 2645 | expect(draft?.reviewComments).toEqual([reviewComment]); |
| 2646 | expect(draft?.previewAnnotations).toEqual([annotation]); |
| 2647 | }); |
| 2648 | }); |
| 2649 | |
| 2650 | describe("composerDraftStore attachment references", () => { |
| 2651 | const threadId = ThreadId.make("thread-attachment-refs"); |
| 2652 | const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); |
| 2653 | const fileLink = "[notes.txt](t3-context://v1/file/file_file-1)"; |
| 2654 | const imageLink = "[shot.png](t3-context://v1/image/image_img-1)"; |
| 2655 | |
| 2656 | beforeEach(() => { |
| 2657 | resetComposerDraftStore(); |
| 2658 | }); |
| 2659 | |
| 2660 | it("reports which attachments it accepted so only those get chips", () => { |
| 2661 | const store = useComposerDraftStore.getState(); |
| 2662 | const file = { |
| 2663 | type: "file" as const, |
| 2664 | id: "file-1", |
| 2665 | name: "notes.txt", |
| 2666 | mimeType: "text/plain", |
| 2667 | sizeBytes: 3, |
| 2668 | file: null, |
| 2669 | uploadedAttachmentId: "p", |
| 2670 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 2671 | }; |
| 2672 | expect(store.addFiles(threadRef, [file])).toEqual(["file-1"]); |
| 2673 | expect(store.addFiles(threadRef, [{ ...file, id: "file-2" }])).toEqual([]); |
| 2674 | const image = makeImage({ id: "img-1", previewUrl: "blob:img-1", name: "shot.png" }); |
| 2675 | expect(store.addImages(threadRef, [image])).toEqual(["img-1"]); |
| 2676 | expect( |
| 2677 | store.addImages(threadRef, [{ ...image, id: "img-2", previewUrl: "blob:img-2" }]), |
| 2678 | ).toEqual([]); |
| 2679 | }); |
| 2680 | |
| 2681 | it("strips references when an image or file is removed", () => { |
| 2682 | const store = useComposerDraftStore.getState(); |
| 2683 | store.setPrompt(threadRef, `see ${imageLink} and ${fileLink} ok`); |
| 2684 | store.addImages(threadRef, [ |
| 2685 | makeImage({ id: "img-1", previewUrl: "blob:img-1", name: "shot.png" }), |
| 2686 | ]); |
| 2687 | store.addFiles(threadRef, [ |
| 2688 | { |
| 2689 | type: "file", |
| 2690 | id: "file-1", |
| 2691 | name: "notes.txt", |
| 2692 | mimeType: "text/plain", |
| 2693 | sizeBytes: 3, |
| 2694 | file: null, |
| 2695 | uploadedAttachmentId: "pending-1", |
| 2696 | uploadEnvironmentId: TEST_ENVIRONMENT_ID, |
| 2697 | }, |
| 2698 | ]); |
| 2699 | store.removeImage(threadRef, "img-1"); |
| 2700 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe(`see and ${fileLink} ok`); |
| 2701 | store.removeFile(threadRef, "file-1"); |
| 2702 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("see and ok"); |
| 2703 | }); |
| 2704 | |
| 2705 | it("moves a needs-reattach marker's chip to the re-picked file", () => { |
| 2706 | const store = useComposerDraftStore.getState(); |
| 2707 | store.setPrompt(threadRef, "see [notes.txt](t3-context://v1/file/file_marker-1) ok"); |
| 2708 | store.addFiles(threadRef, [ |
| 2709 | { |
| 2710 | type: "file", |
| 2711 | id: "marker-1", |
| 2712 | name: "notes.txt", |
| 2713 | mimeType: "text/plain", |
| 2714 | sizeBytes: 3, |
| 2715 | file: null, |
| 2716 | }, |
| 2717 | ]); |
| 2718 | const acceptedIds = store.addFiles(threadRef, [ |
| 2719 | { |
| 2720 | type: "file", |
| 2721 | id: "fresh-1", |
| 2722 | name: "notes.txt", |
| 2723 | mimeType: "text/plain", |
| 2724 | sizeBytes: 3, |
| 2725 | file: new File(["abc"], "notes.txt", { type: "text/plain" }), |
| 2726 | }, |
| 2727 | ]); |
| 2728 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); |
| 2729 | expect(acceptedIds).toEqual([]); |
| 2730 | expect(draft?.files.map((file) => file.id)).toEqual(["fresh-1"]); |
| 2731 | expect(draft?.prompt).toBe("see [notes.txt](t3-context://v1/file/file_fresh-1) ok"); |
| 2732 | }); |
| 2733 | |
| 2734 | it.each(["old.file:1", "file-1"])( |
| 2735 | "rewrites persisted attachment references before removal: %s", |
| 2736 | (id) => { |
| 2737 | const merged = useComposerDraftStore.persist.getOptions().merge!( |
| 2738 | { |
| 2739 | draftsByThreadKey: { |
| 2740 | [threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]: { |
| 2741 | prompt: `before [notes.txt](t3-context://v1/file/${id}) after`, |
| 2742 | attachments: [], |
| 2743 | files: [{ id, name: "notes.txt", mimeType: "text/plain", sizeBytes: 3 }], |
| 2744 | }, |
| 2745 | }, |
| 2746 | }, |
| 2747 | useComposerDraftStore.getInitialState(), |
| 2748 | ); |
| 2749 | useComposerDraftStore.setState(merged); |
| 2750 | const draft = draftFor(threadId, TEST_ENVIRONMENT_ID)!; |
| 2751 | expect(draft.prompt.match(/t3-context:/g)).toHaveLength(1); |
| 2752 | expect(draft.prompt).not.toContain(`/file/${id})`); |
| 2753 | useComposerDraftStore.getState().removeFile(threadRef, id); |
| 2754 | expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("before after"); |
| 2755 | }, |
| 2756 | ); |
| 2757 | |
| 2758 | it("appends chips for persisted files that predate references", () => { |
| 2759 | const persistApi = useComposerDraftStore.persist as unknown as { |
| 2760 | getOptions: () => { |
| 2761 | merge: ( |
| 2762 | persistedState: unknown, |
| 2763 | currentState: ReturnType<typeof useComposerDraftStore.getState>, |
| 2764 | ) => ReturnType<typeof useComposerDraftStore.getState>; |
| 2765 | }; |
| 2766 | }; |
| 2767 | const mergedState = persistApi.getOptions().merge( |
| 2768 | { |
| 2769 | draftsByThreadId: { |
| 2770 | [threadId]: { |
| 2771 | prompt: "old", |
| 2772 | attachments: [], |
| 2773 | files: [{ id: "file-1", name: "notes.txt", mimeType: "text/plain", sizeBytes: 3 }], |
| 2774 | }, |
| 2775 | }, |
| 2776 | draftThreadsByThreadId: {}, |
| 2777 | projectDraftThreadIdByProjectKey: {}, |
| 2778 | }, |
| 2779 | useComposerDraftStore.getInitialState(), |
| 2780 | ); |
| 2781 | expect(mergedState.draftsByThreadKey[threadKeyFor(threadId)]?.prompt).toBe(`old ${fileLink} `); |
| 2782 | }); |
| 2783 | |
| 2784 | it("migrates legacy image references without doubling their image marker", () => { |
| 2785 | const merged = useComposerDraftStore.persist.getOptions().merge!( |
| 2786 | { |
| 2787 | draftsByThreadKey: { |
| 2788 | [threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]: { |
| 2789 | prompt: "see  after", |
| 2790 | attachments: [ |
| 2791 | { |
| 2792 | id: "img-1", |
| 2793 | name: "shot.png", |
| 2794 | mimeType: "image/png", |
| 2795 | sizeBytes: 1, |
| 2796 | dataUrl: "data:image/png;base64,YQ==", |
| 2797 | }, |
| 2798 | ], |
| 2799 | }, |
| 2800 | }, |
| 2801 | }, |
| 2802 | useComposerDraftStore.getInitialState(), |
| 2803 | ); |
| 2804 | expect(merged.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.prompt).toBe( |
| 2805 | "see  after", |
| 2806 | ); |
| 2807 | }); |
| 2808 | |
| 2809 | it("preserves canonical references when another producer ID matches their namespace", () => { |
| 2810 | const prompt = |
| 2811 | " "; |
| 2812 | const merged = useComposerDraftStore.persist.getOptions().merge!( |
| 2813 | { |
| 2814 | draftsByThreadKey: { |
| 2815 | [threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]: { |
| 2816 | prompt, |
| 2817 | attachments: ["x", "image_x"].map((id) => ({ |
| 2818 | id, |
| 2819 | name: `${id}.png`, |
| 2820 | mimeType: "image/png", |
| 2821 | sizeBytes: 1, |
| 2822 | dataUrl: "data:image/png;base64,YQ==", |
| 2823 | })), |
| 2824 | }, |
| 2825 | }, |
| 2826 | }, |
| 2827 | useComposerDraftStore.getInitialState(), |
| 2828 | ); |
| 2829 | expect(merged.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.prompt).toBe( |
| 2830 | prompt, |
| 2831 | ); |
| 2832 | }); |
| 2833 | }); |
| 2834 | |
| 2835 | describe("composerDraftStore checkout pull request", () => { |
| 2836 | const projectId = ProjectId.make("project-checkout"); |
| 2837 | const projectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, projectId); |
| 2838 | const otherProjectRef = scopeProjectRef(TEST_ENVIRONMENT_ID, ProjectId.make("project-other")); |
| 2839 | const threadId = ThreadId.make("thread-checkout"); |
| 2840 | const draftId = DraftId.make("draft-checkout"); |
| 2841 | const url = "https://github.com/acme/widgets/pull/42"; |
| 2842 | const checkout = { url, branch: "feature/pr-42" }; |
| 2843 | |
| 2844 | beforeEach(() => { |
| 2845 | resetComposerDraftStore(); |
| 2846 | }); |
| 2847 | |
| 2848 | const store = () => useComposerDraftStore.getState(); |
| 2849 | const toLink = () => checkoutPullRequestUrlToLink(store().getDraftSession(draftId)); |
| 2850 | |
| 2851 | function draftOnMain() { |
| 2852 | store().setProjectDraftThreadId(projectRef, draftId, { threadId, branch: "main" }); |
| 2853 | } |
| 2854 | |
| 2855 | // GitActionsControl's live branch sync writes the git status branch onto the draft. The status |
| 2856 | // refresh after a checkout is forked server-side, so the prepare response lands first and the |
| 2857 | // sync replays the stale pre-checkout branch before the fresh status corrects it. |
| 2858 | function liveBranchSync(branch: string) { |
| 2859 | store().setDraftThreadContext(draftId, { |
| 2860 | branch, |
| 2861 | worktreePath: null, |
| 2862 | environmentSelection: "manual", |
| 2863 | }); |
| 2864 | } |
| 2865 | |
| 2866 | it("still links after a local checkout the live branch sync briefly reverts", () => { |
| 2867 | draftOnMain(); |
| 2868 | store().setDraftThreadContext(draftId, { |
| 2869 | branch: checkout.branch, |
| 2870 | worktreePath: null, |
| 2871 | envMode: "local", |
| 2872 | checkoutPullRequest: checkout, |
| 2873 | }); |
| 2874 | liveBranchSync("main"); |
| 2875 | liveBranchSync(checkout.branch); |
| 2876 | |
| 2877 | expect(toLink()).toBe(url); |
| 2878 | }); |
| 2879 | |
| 2880 | it("does not link once the draft has moved to another branch", () => { |
| 2881 | draftOnMain(); |
| 2882 | store().setDraftThreadContext(draftId, { |
| 2883 | branch: checkout.branch, |
| 2884 | checkoutPullRequest: checkout, |
| 2885 | }); |
| 2886 | liveBranchSync("main"); |
| 2887 | |
| 2888 | expect(toLink()).toBeNull(); |
| 2889 | }); |
| 2890 | |
| 2891 | it("is dropped when cleared or when the draft moves to another project", () => { |
| 2892 | store().setProjectDraftThreadId(projectRef, draftId, { |
| 2893 | threadId, |
| 2894 | branch: checkout.branch, |
| 2895 | checkoutPullRequest: checkout, |
| 2896 | }); |
| 2897 | store().setDraftThreadContext(draftId, { checkoutPullRequest: null }); |
| 2898 | expect(store().getDraftSession(draftId)?.checkoutPullRequest).toBeUndefined(); |
| 2899 | |
| 2900 | store().setDraftThreadContext(draftId, { checkoutPullRequest: checkout }); |
| 2901 | store().setDraftThreadContext(draftId, { projectRef: otherProjectRef }); |
| 2902 | expect(store().getDraftSession(draftId)?.checkoutPullRequest).toBeUndefined(); |
| 2903 | }); |
| 2904 | |
| 2905 | it("persists the pull request and still restores drafts saved without one", async () => { |
| 2906 | vi.useFakeTimers(); |
| 2907 | try { |
| 2908 | await useComposerDraftStore.persist.clearStorage(); |
| 2909 | const legacyDraftId = DraftId.make("draft-before-checkout-links"); |
| 2910 | const storage = useComposerDraftStore.persist.getOptions().storage; |
| 2911 | expect(storage).toBeDefined(); |
| 2912 | const persistedDraftThread = (id: ThreadId) => ({ |
| 2913 | threadId: id, |
| 2914 | environmentId: TEST_ENVIRONMENT_ID, |
| 2915 | projectId, |
| 2916 | logicalProjectKey: scopedProjectKey(projectRef), |
| 2917 | createdAt: "2026-08-01T00:00:00.000Z", |
| 2918 | runtimeMode: "full-access", |
| 2919 | interactionMode: "default", |
| 2920 | branch: checkout.branch, |
| 2921 | worktreePath: null, |
| 2922 | envMode: "local", |
| 2923 | startFromOrigin: false, |
| 2924 | promotedTo: null, |
| 2925 | }); |
| 2926 | storage?.setItem(COMPOSER_DRAFT_STORAGE_KEY, { |
| 2927 | version: 9, |
| 2928 | state: { |
| 2929 | draftsByThreadKey: {}, |
| 2930 | draftThreadsByThreadKey: { |
| 2931 | [draftId]: { ...persistedDraftThread(threadId), checkoutPullRequest: checkout }, |
| 2932 | [legacyDraftId]: persistedDraftThread(ThreadId.make("thread-legacy")), |
| 2933 | }, |
| 2934 | logicalProjectDraftThreadKeyByLogicalProjectKey: { |
| 2935 | [scopedProjectKey(projectRef)]: draftId, |
| 2936 | }, |
| 2937 | }, |
| 2938 | } as never); |
| 2939 | await vi.advanceTimersByTimeAsync(300); |
| 2940 | |
| 2941 | await useComposerDraftStore.persist.rehydrate(); |
| 2942 | |
| 2943 | expect(toLink()).toBe(url); |
| 2944 | const legacy = store().getDraftSession(legacyDraftId); |
| 2945 | expect(legacy).toMatchObject({ branch: checkout.branch }); |
| 2946 | expect(checkoutPullRequestUrlToLink(legacy)).toBeNull(); |
| 2947 | expect( |
| 2948 | partializeComposerDraftStoreState(store()).draftThreadsByThreadKey[draftId], |
| 2949 | ).toMatchObject({ checkoutPullRequest: checkout }); |
| 2950 | } finally { |
| 2951 | await useComposerDraftStore.persist.clearStorage(); |
| 2952 | vi.useRealTimers(); |
| 2953 | resetComposerDraftStore(); |
| 2954 | } |
| 2955 | }); |
| 2956 | }); |