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, 04:45 UTC
| 1 | import { |
| 2 | AuthOrchestrationOperateScope, |
| 3 | CommandId, |
| 4 | EnvironmentId, |
| 5 | MessageId, |
| 6 | ProjectId, |
| 7 | ProviderInstanceId, |
| 8 | ThreadId, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import { attachmentUploadError } from "@t3tools/client-runtime/state/attachment-uploads"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Cause from "effect/Cause"; |
| 13 | import { AsyncResult, type Atom } from "effect/reactivity"; |
| 14 | import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; |
| 15 | import { threadOutboxRetryDelayMs, type QueuedThreadMessage } from "./thread-outbox-model"; |
| 16 | |
| 17 | const state = vi.hoisted(() => ({ |
| 18 | draftText: "Keep this draft separate", |
| 19 | cleanups: [] as Array<() => void>, |
| 20 | delivery: null as { |
| 21 | readonly drain: () => void; |
| 22 | readonly dispose: () => void; |
| 23 | } | null, |
| 24 | start: vi.fn(), |
| 25 | metadata: vi.fn(), |
| 26 | runtime: vi.fn(), |
| 27 | interaction: vi.fn(), |
| 28 | prepare: vi.fn(), |
| 29 | checkout: vi.fn(), |
| 30 | // Delivery runs commands as Effects; tests steer them with the settled results the mocks return. |
| 31 | command: (Effect: typeof import("effect/Effect"), settle: (input: unknown) => unknown) => ({ |
| 32 | label: "command", |
| 33 | run: (_registry: unknown, input: unknown) => |
| 34 | Effect.promise( |
| 35 | async () => |
| 36 | (await settle(input)) as |
| 37 | | import("effect/reactivity").AsyncResult.Success<unknown> |
| 38 | | import("effect/reactivity").AsyncResult.Failure<unknown, Error>, |
| 39 | ).pipe( |
| 40 | Effect.flatMap((result) => |
| 41 | result._tag === "Failure" ? Effect.failCause(result.cause) : Effect.succeed(result.value), |
| 42 | ), |
| 43 | ), |
| 44 | }), |
| 45 | modelUnavailable: vi.fn(() => false), |
| 46 | familyMount: vi.fn(() => () => {}), |
| 47 | threadShells: null as unknown as Atom.Writable<ReadonlyArray<unknown>>, |
| 48 | manager: null as unknown as ReturnType< |
| 49 | typeof import("./thread-outbox-manager").createThreadOutboxManager |
| 50 | >, |
| 51 | thread: { |
| 52 | environmentId: "secondary", |
| 53 | id: "thread", |
| 54 | modelSelection: { instanceId: "codex", model: "gpt-5.4" }, |
| 55 | runtimeMode: "full-access", |
| 56 | interactionMode: "default", |
| 57 | session: null, |
| 58 | }, |
| 59 | config: { |
| 60 | shellThreadFamilies: false, |
| 61 | providers: [{ instanceId: "codex", driver: "codex", models: [] }], |
| 62 | environment: { capabilities: {} }, |
| 63 | }, |
| 64 | })); |
| 65 | vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); |
| 66 | vi.mock("./session", async () => { |
| 67 | const { Atom } = await import("effect/reactivity"); |
| 68 | const { appAtomRegistry } = await import("./atom-registry"); |
| 69 | // A session's state is reduced to whether it grants the operate scope. |
| 70 | const sessionStateAtom = Atom.family((_id: string) => Atom.make(false).pipe(Atom.keepAlive)); |
| 71 | const sessionHasScope = (granted: boolean, scope: string) => |
| 72 | granted && scope === AuthOrchestrationOperateScope; |
| 73 | return { |
| 74 | environmentSession: { sessionStateAtom }, |
| 75 | sessionHasScope, |
| 76 | readEnvironmentScope: (environmentId: string, scope: string) => |
| 77 | sessionHasScope(appAtomRegistry.get(sessionStateAtom(environmentId)), scope), |
| 78 | }; |
| 79 | }); |
| 80 | vi.mock("./projects", async () => { |
| 81 | const { Atom } = await import("effect/reactivity"); |
| 82 | return { environmentProjects: { projectsAtom: Atom.make([]) } }; |
| 83 | }); |
| 84 | vi.mock("./workspace", async () => { |
| 85 | const { Atom } = await import("effect/reactivity"); |
| 86 | return { |
| 87 | workspaceConnections: { |
| 88 | environmentsAtom: Atom.make([{ environmentId: "secondary", connectionState: "connected" }]), |
| 89 | }, |
| 90 | }; |
| 91 | }); |
| 92 | vi.mock("./server", async () => { |
| 93 | const { Atom } = await import("effect/reactivity"); |
| 94 | return { |
| 95 | serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) }, |
| 96 | environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.config]])), |
| 97 | }; |
| 98 | }); |
| 99 | vi.mock("./threads", async () => { |
| 100 | const { Atom, AsyncResult } = await import("effect/reactivity"); |
| 101 | const Effect = await import("effect/Effect"); |
| 102 | state.threadShells = Atom.make<ReadonlyArray<unknown>>([state.thread]).pipe(Atom.keepAlive); |
| 103 | return { |
| 104 | threadEnvironment: { |
| 105 | startTurn: state.command(Effect, state.start), |
| 106 | updateMetadata: state.command(Effect, state.metadata), |
| 107 | setRuntimeMode: state.command(Effect, state.runtime), |
| 108 | setInteractionMode: state.command(Effect, state.interaction), |
| 109 | }, |
| 110 | environmentThreadShells: { threadShellsAtom: state.threadShells }, |
| 111 | threadFamilies: { |
| 112 | mount: state.familyMount, |
| 113 | familyAtom: () => Atom.make(AsyncResult.success({})), |
| 114 | refresh: vi.fn(), |
| 115 | }, |
| 116 | environmentThreadDetails: { stateAtom: () => Atom.make(null) }, |
| 117 | }; |
| 118 | }); |
| 119 | vi.mock("./git", async () => ({ |
| 120 | gitEnvironment: { |
| 121 | preparePullRequestThread: state.command(await import("effect/Effect"), state.checkout), |
| 122 | }, |
| 123 | })); |
| 124 | vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable })); |
| 125 | vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" })); |
| 126 | vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare })); |
| 127 | vi.mock("./composer-attachment-uploads", () => ({ uploadComposerAttachmentShared: vi.fn() })); |
| 128 | vi.mock("./thread-outbox", async () => { |
| 129 | const { createThreadOutboxManager } = await import("./thread-outbox-manager"); |
| 130 | const { appAtomRegistry } = await import("./atom-registry"); |
| 131 | state.manager = createThreadOutboxManager({ |
| 132 | registry: appAtomRegistry, |
| 133 | storage: { |
| 134 | load: async () => ({ messages: [], errors: [] }), |
| 135 | write: async () => {}, |
| 136 | remove: async () => {}, |
| 137 | }, |
| 138 | }); |
| 139 | return { |
| 140 | threadOutboxManager: state.manager, |
| 141 | threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id), |
| 142 | confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) => |
| 143 | state.manager.confirmQueued(message), |
| 144 | updateThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) => |
| 145 | state.manager.update(message, revision), |
| 146 | }; |
| 147 | }); |
| 148 | vi.mock("./thread-outbox-removal", () => ({ |
| 149 | removeThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) => |
| 150 | state.manager.remove(message, revision), |
| 151 | })); |
| 152 | vi.mock("./use-thread-outbox", async () => { |
| 153 | const { Atom } = await import("effect/reactivity"); |
| 154 | return { |
| 155 | editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), |
| 156 | dispatchingQueuedMessageIdsAtom: Atom.make<Readonly<Record<MessageId, true>>>({}).pipe( |
| 157 | Atom.keepAlive, |
| 158 | ), |
| 159 | retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), |
| 160 | threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])), |
| 161 | }; |
| 162 | }); |
| 163 | vi.mock("./use-composer-drafts", async () => { |
| 164 | const { Atom } = await import("effect/reactivity"); |
| 165 | return { |
| 166 | composerDraftsAtom: Atom.make({}), |
| 167 | removeDeliveredCloudQueuedMessage: async () => {}, |
| 168 | appendComposerDraftAttachments: vi.fn(), |
| 169 | flushComposerDrafts: vi.fn(async () => {}), |
| 170 | getComposerDraftSnapshot: vi.fn(() => ({ text: state.draftText, attachments: [] })), |
| 171 | mergeComposerDraftContent: vi.fn(async (_key: string, input: { text: string }) => { |
| 172 | state.draftText += `\n${input.text}`; |
| 173 | }), |
| 174 | replaceComposerDraftAttachments: vi.fn(), |
| 175 | setFreshSessionPending: vi.fn(), |
| 176 | undoComposerDraftMerge: vi.fn(), |
| 177 | updateComposerDraftSettings: vi.fn(), |
| 178 | waitForComposerDraftsLoaded: vi.fn(), |
| 179 | }; |
| 180 | }); |
| 181 | |
| 182 | import { appAtomRegistry } from "./atom-registry"; |
| 183 | import { environmentSession } from "./session"; |
| 184 | import { dispatchingQueuedMessageIdsAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox"; |
| 185 | |
| 186 | const sendingMessageIds = () => Object.keys(appAtomRegistry.get(dispatchingQueuedMessageIdsAtom)); |
| 187 | import { createThreadOutboxDelivery } from "./threadOutboxDelivery"; |
| 188 | import { workspaceConnections } from "./workspace"; |
| 189 | |
| 190 | const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({ |
| 191 | environmentId: EnvironmentId.make("secondary"), |
| 192 | threadId: ThreadId.make("thread"), |
| 193 | commandId: CommandId.make("command"), |
| 194 | messageId: MessageId.make("message"), |
| 195 | text: "Keep this queued", |
| 196 | attachments: [], |
| 197 | createdAt: "2026-09-05T00:00:00.000Z", |
| 198 | ...overrides, |
| 199 | }); |
| 200 | const remaining = () => |
| 201 | Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat(); |
| 202 | |
| 203 | function setOperateGrant(environmentId: string, granted: boolean): void { |
| 204 | // The mocked session atom holds the grant itself (see the ./session mock). |
| 205 | const sessionAtom = environmentSession.sessionStateAtom(EnvironmentId.make(environmentId)); |
| 206 | appAtomRegistry.set(sessionAtom as unknown as Atom.Writable<boolean>, granted); |
| 207 | } |
| 208 | |
| 209 | function runDrain() { |
| 210 | const settled = Promise.withResolvers<void>(); |
| 211 | const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { |
| 212 | if (Object.keys(ids).length === 0) settled.resolve(); |
| 213 | }); |
| 214 | startDelivery(); |
| 215 | return settled.promise.finally(release); |
| 216 | } |
| 217 | |
| 218 | /** Starts the service once per test; later calls run another drain pass. */ |
| 219 | function startDelivery(): void { |
| 220 | if (state.delivery !== null) { |
| 221 | state.delivery.drain(); |
| 222 | return; |
| 223 | } |
| 224 | const delivery = createThreadOutboxDelivery(); |
| 225 | state.delivery = delivery; |
| 226 | state.cleanups.push(() => { |
| 227 | delivery.dispose(); |
| 228 | state.delivery = null; |
| 229 | }); |
| 230 | } |
| 231 | |
| 232 | beforeEach(() => { |
| 233 | setOperateGrant("primary", true); |
| 234 | setOperateGrant("secondary", false); |
| 235 | state.draftText = "Keep this draft separate"; |
| 236 | state.config.shellThreadFamilies = false; |
| 237 | state.modelUnavailable.mockReset().mockReturnValue(false); |
| 238 | state.familyMount.mockReset().mockReturnValue(() => {}); |
| 239 | appAtomRegistry.set(state.threadShells, [state.thread]); |
| 240 | appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {}); |
| 241 | appAtomRegistry.set(dispatchingQueuedMessageIdsAtom, {}); |
| 242 | appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); |
| 243 | for (const command of [ |
| 244 | state.start, |
| 245 | state.metadata, |
| 246 | state.runtime, |
| 247 | state.interaction, |
| 248 | state.checkout, |
| 249 | ]) { |
| 250 | command.mockReset().mockResolvedValue(AsyncResult.success(undefined)); |
| 251 | } |
| 252 | state.start.mockResolvedValue(AsyncResult.success({})); |
| 253 | state.prepare.mockReset().mockImplementation(({ attachments }) => |
| 254 | Effect.succeed({ |
| 255 | status: "ready", |
| 256 | attachments: [], |
| 257 | draftAttachments: attachments, |
| 258 | pendingAttachmentIds: [], |
| 259 | }), |
| 260 | ); |
| 261 | }); |
| 262 | |
| 263 | describe("queued PR checkout", () => { |
| 264 | const queuedPullRequest = () => |
| 265 | message({ |
| 266 | threadId: ThreadId.make("new-pr-thread"), |
| 267 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, |
| 268 | creation: { |
| 269 | projectId: ProjectId.make("project"), |
| 270 | projectCwd: "/repo", |
| 271 | workspaceMode: "worktree", |
| 272 | branch: "fork/feature", |
| 273 | worktreePath: null, |
| 274 | pullRequestReference: "https://github.com/acme/repo/pull/123", |
| 275 | }, |
| 276 | }); |
| 277 | const preparedCheckout = { |
| 278 | branch: "pr-123", |
| 279 | worktreePath: "/repo/.t3/worktrees/pr-123", |
| 280 | isOnPullRequestHead: true, |
| 281 | }; |
| 282 | |
| 283 | it("waits for the provider's PR checkout and launches in that worktree", async () => { |
| 284 | setOperateGrant("secondary", true); |
| 285 | await state.manager.enqueue(queuedPullRequest()); |
| 286 | const started = Promise.withResolvers<void>(); |
| 287 | const checkout = |
| 288 | Promise.withResolvers<AsyncResult.AsyncResult<typeof preparedCheckout, Error>>(); |
| 289 | state.checkout.mockImplementationOnce(() => { |
| 290 | started.resolve(); |
| 291 | return checkout.promise; |
| 292 | }); |
| 293 | const drained = runDrain(); |
| 294 | await started.promise; |
| 295 | expect(state.start).not.toHaveBeenCalled(); |
| 296 | expect(state.checkout).toHaveBeenCalledWith({ |
| 297 | environmentId: "secondary", |
| 298 | input: { cwd: "/repo", reference: "https://github.com/acme/repo/pull/123", mode: "worktree" }, |
| 299 | }); |
| 300 | checkout.resolve(AsyncResult.success(preparedCheckout)); |
| 301 | await drained; |
| 302 | expect(state.start).toHaveBeenCalledOnce(); |
| 303 | const bootstrap = state.start.mock.calls[0]?.[0].input.bootstrap; |
| 304 | expect(bootstrap.createThread).toMatchObject({ |
| 305 | branch: "pr-123", |
| 306 | worktreePath: preparedCheckout.worktreePath, |
| 307 | }); |
| 308 | expect(bootstrap.prepareWorktree).toBeUndefined(); |
| 309 | expect(remaining()).toEqual([]); |
| 310 | }); |
| 311 | |
| 312 | it("keeps the PR source queued on a transport failure without starting the agent", async () => { |
| 313 | setOperateGrant("secondary", true); |
| 314 | const queued = queuedPullRequest(); |
| 315 | await state.manager.enqueue(queued); |
| 316 | state.checkout.mockResolvedValueOnce( |
| 317 | AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))), |
| 318 | ); |
| 319 | await runDrain(); |
| 320 | expect(state.start).not.toHaveBeenCalled(); |
| 321 | expect(remaining()).toEqual([queued]); |
| 322 | }); |
| 323 | |
| 324 | it("stops launch if operation access is revoked while checking out the PR", async () => { |
| 325 | setOperateGrant("secondary", true); |
| 326 | const queued = queuedPullRequest(); |
| 327 | await state.manager.enqueue(queued); |
| 328 | state.checkout.mockImplementationOnce(async () => { |
| 329 | setOperateGrant("secondary", false); |
| 330 | return AsyncResult.success(preparedCheckout); |
| 331 | }); |
| 332 | await runDrain(); |
| 333 | expect(state.start).not.toHaveBeenCalled(); |
| 334 | expect(remaining()).toEqual([queued]); |
| 335 | }); |
| 336 | |
| 337 | it("does not launch a stale task edited while the PR checkout was running", async () => { |
| 338 | setOperateGrant("secondary", true); |
| 339 | const queued = queuedPullRequest(); |
| 340 | await state.manager.enqueue(queued); |
| 341 | const edited = { ...queued, text: "Updated instructions" }; |
| 342 | state.checkout.mockImplementationOnce(async () => { |
| 343 | await state.manager.update(edited); |
| 344 | return AsyncResult.success(preparedCheckout); |
| 345 | }); |
| 346 | await runDrain(); |
| 347 | expect(state.start).not.toHaveBeenCalled(); |
| 348 | expect(remaining()).toEqual([edited]); |
| 349 | }); |
| 350 | }); |
| 351 | afterEach(() => { |
| 352 | state.cleanups.splice(0).forEach((cleanup) => cleanup()); |
| 353 | }); |
| 354 | |
| 355 | describe("queued task operation access", () => { |
| 356 | it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => { |
| 357 | const queued = message(); |
| 358 | await state.manager.enqueue(queued); |
| 359 | startDelivery(); |
| 360 | expect(state.start).not.toHaveBeenCalled(); |
| 361 | expect(state.prepare).not.toHaveBeenCalled(); |
| 362 | expect(remaining()).toEqual([queued]); |
| 363 | setOperateGrant("secondary", true); |
| 364 | await runDrain(); |
| 365 | expect(state.start).toHaveBeenCalledOnce(); |
| 366 | expect(remaining()).toEqual([]); |
| 367 | }); |
| 368 | |
| 369 | it("backs off instead of redelivering at once when a delivery hits a defect", async () => { |
| 370 | setOperateGrant("secondary", true); |
| 371 | const queued = message(); |
| 372 | await state.manager.enqueue(queued); |
| 373 | // Awaited steps catch their own failures, so a defect in the delivery's own code is what |
| 374 | // rejects a delivery. |
| 375 | state.modelUnavailable.mockImplementationOnce(() => { |
| 376 | throw new TypeError("Cannot read properties of undefined"); |
| 377 | }); |
| 378 | await runDrain(); |
| 379 | expect(state.modelUnavailable).toHaveBeenCalledOnce(); |
| 380 | expect(state.prepare).not.toHaveBeenCalled(); |
| 381 | expect(state.start).not.toHaveBeenCalled(); |
| 382 | expect(sendingMessageIds()).toEqual([]); |
| 383 | expect(remaining()).toEqual([queued]); |
| 384 | }); |
| 385 | |
| 386 | it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => { |
| 387 | setOperateGrant("secondary", true); |
| 388 | state.config.shellThreadFamilies = true; |
| 389 | const subAgentThread = { ...state.thread, id: "sub-agent" }; |
| 390 | // A cached family merges its rows into the shell list as soon as it is mounted. |
| 391 | state.familyMount.mockImplementationOnce(() => { |
| 392 | appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]); |
| 393 | return () => {}; |
| 394 | }); |
| 395 | const queued = message({ threadId: ThreadId.make("sub-agent") }); |
| 396 | startDelivery(); |
| 397 | appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true }); |
| 398 | await state.manager.enqueue(queued); |
| 399 | const delivered = Promise.withResolvers<void>(); |
| 400 | const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { |
| 401 | if (Object.keys(ids).length === 0) delivered.resolve(); |
| 402 | }); |
| 403 | // Ending the edit wakes the thread through a registry notification, the path on which the |
| 404 | // mount's synchronous row change wakes it again while it is deciding. |
| 405 | appAtomRegistry.set(editingQueuedMessageIdsAtom, {}); |
| 406 | await delivered.promise.finally(release); |
| 407 | expect(state.familyMount).toHaveBeenCalledOnce(); |
| 408 | // One fiber took the message: a second would have prepared it again. |
| 409 | expect(state.prepare).toHaveBeenCalledOnce(); |
| 410 | expect(state.start).toHaveBeenCalledOnce(); |
| 411 | expect(remaining()).toEqual([]); |
| 412 | }); |
| 413 | |
| 414 | it("stops the remaining settings and turn commands when an earlier update loses access", async () => { |
| 415 | setOperateGrant("secondary", true); |
| 416 | const queued = message({ |
| 417 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" }, |
| 418 | runtimeMode: "approval-required", |
| 419 | interactionMode: "plan", |
| 420 | }); |
| 421 | await state.manager.enqueue(queued); |
| 422 | state.runtime.mockImplementationOnce(async () => { |
| 423 | setOperateGrant("secondary", false); |
| 424 | return AsyncResult.success(undefined); |
| 425 | }); |
| 426 | await runDrain(); |
| 427 | expect(state.runtime).toHaveBeenCalledOnce(); |
| 428 | expect(state.interaction).not.toHaveBeenCalled(); |
| 429 | expect(state.prepare).not.toHaveBeenCalled(); |
| 430 | expect(state.start).not.toHaveBeenCalled(); |
| 431 | expect(remaining()).toEqual([queued]); |
| 432 | }); |
| 433 | |
| 434 | it.each([ |
| 435 | { isCreation: false, accepted: false }, |
| 436 | { isCreation: true, accepted: true }, |
| 437 | ])( |
| 438 | "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)", |
| 439 | async ({ isCreation, accepted }) => { |
| 440 | setOperateGrant("secondary", true); |
| 441 | const queued = message( |
| 442 | isCreation |
| 443 | ? { |
| 444 | threadId: ThreadId.make("new-thread"), |
| 445 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, |
| 446 | creation: { |
| 447 | projectId: ProjectId.make("project"), |
| 448 | projectCwd: "/repo", |
| 449 | workspaceMode: "local", |
| 450 | branch: null, |
| 451 | worktreePath: null, |
| 452 | }, |
| 453 | } |
| 454 | : {}, |
| 455 | ); |
| 456 | await state.manager.enqueue(queued); |
| 457 | const started = Promise.withResolvers<void>(); |
| 458 | const delivery = |
| 459 | Promise.withResolvers<AsyncResult.AsyncResult<{ readonly sequence?: number }, Error>>(); |
| 460 | state.start.mockImplementationOnce(() => { |
| 461 | started.resolve(); |
| 462 | return delivery.promise; |
| 463 | }); |
| 464 | const drained = runDrain(); |
| 465 | await started.promise; |
| 466 | setOperateGrant("secondary", false); |
| 467 | delivery.resolve( |
| 468 | accepted |
| 469 | ? AsyncResult.success({}) |
| 470 | : AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))), |
| 471 | ); |
| 472 | await drained; |
| 473 | |
| 474 | expect(remaining()).toEqual(accepted ? [] : [queued]); |
| 475 | expect(state.draftText).toBe("Keep this draft separate"); |
| 476 | if (!accepted) { |
| 477 | setOperateGrant("secondary", true); |
| 478 | await runDrain(); |
| 479 | expect(state.start).toHaveBeenCalledTimes(2); |
| 480 | expect(remaining()).toEqual([]); |
| 481 | expect(state.draftText).toBe("Keep this draft separate"); |
| 482 | } |
| 483 | }, |
| 484 | ); |
| 485 | |
| 486 | it.each([ |
| 487 | { isCreation: false, uploadFails: false }, |
| 488 | { isCreation: true, uploadFails: false }, |
| 489 | { isCreation: false, uploadFails: true }, |
| 490 | { isCreation: true, uploadFails: true }, |
| 491 | ])( |
| 492 | "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)", |
| 493 | async ({ isCreation, uploadFails }) => { |
| 494 | setOperateGrant("secondary", true); |
| 495 | const queued = message( |
| 496 | isCreation |
| 497 | ? { |
| 498 | threadId: ThreadId.make("new-thread"), |
| 499 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, |
| 500 | creation: { |
| 501 | projectId: ProjectId.make("project"), |
| 502 | projectCwd: "/repo", |
| 503 | workspaceMode: "local", |
| 504 | branch: null, |
| 505 | worktreePath: null, |
| 506 | }, |
| 507 | } |
| 508 | : {}, |
| 509 | ); |
| 510 | await state.manager.enqueue(queued); |
| 511 | state.prepare.mockImplementationOnce(({ attachments }) => |
| 512 | Effect.suspend(() => { |
| 513 | setOperateGrant("secondary", false); |
| 514 | return uploadFails |
| 515 | ? Effect.fail( |
| 516 | attachmentUploadError(new Error("This connection cannot upload attachments.")), |
| 517 | ) |
| 518 | : Effect.succeed({ |
| 519 | status: "ready", |
| 520 | attachments: [], |
| 521 | draftAttachments: attachments, |
| 522 | pendingAttachmentIds: [], |
| 523 | }); |
| 524 | }), |
| 525 | ); |
| 526 | await runDrain(); |
| 527 | expect(state.prepare).toHaveBeenCalledOnce(); |
| 528 | expect(state.start).not.toHaveBeenCalled(); |
| 529 | expect(remaining()).toEqual([queued]); |
| 530 | }, |
| 531 | ); |
| 532 | }); |
| 533 | |
| 534 | describe("queued task whose launch reply is lost", () => { |
| 535 | const queuedTask = (creation: Partial<NonNullable<QueuedThreadMessage["creation"]>> = {}) => |
| 536 | message({ |
| 537 | threadId: ThreadId.make("new-thread"), |
| 538 | text: "My dictated idea", |
| 539 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, |
| 540 | creation: { |
| 541 | projectId: ProjectId.make("project"), |
| 542 | projectCwd: "/repo", |
| 543 | workspaceMode: "local", |
| 544 | branch: null, |
| 545 | worktreePath: null, |
| 546 | ...creation, |
| 547 | }, |
| 548 | }); |
| 549 | |
| 550 | /** The server creates the thread, but the launch reply is lost; the thread then shows up. */ |
| 551 | async function loseLaunchReply(queued: QueuedThreadMessage, edit?: string): Promise<void> { |
| 552 | setOperateGrant("secondary", true); |
| 553 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); |
| 554 | state.cleanups.push(() => vi.useRealTimers()); |
| 555 | await state.manager.enqueue(queued); |
| 556 | state.start.mockImplementationOnce(async () => { |
| 557 | if (edit !== undefined) await state.manager.update({ ...queued, text: edit }); |
| 558 | return AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))); |
| 559 | }); |
| 560 | await runDrain(); |
| 561 | expect(remaining()).toHaveLength(1); |
| 562 | appAtomRegistry.set(state.threadShells, [state.thread, { ...state.thread, id: "new-thread" }]); |
| 563 | } |
| 564 | |
| 565 | async function fireRetry(): Promise<void> { |
| 566 | const settled = Promise.withResolvers<void>(); |
| 567 | const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { |
| 568 | if (Object.keys(ids).length === 0) settled.resolve(); |
| 569 | }); |
| 570 | vi.advanceTimersByTime(threadOutboxRetryDelayMs(1)); |
| 571 | await settled.promise.finally(release); |
| 572 | } |
| 573 | |
| 574 | it("resends an unedited launch instead of handing its text back", async () => { |
| 575 | await loseLaunchReply(queuedTask()); |
| 576 | await fireRetry(); |
| 577 | |
| 578 | expect(state.draftText).toBe("Keep this draft separate"); |
| 579 | // The resend reuses the launch's command and message ids, so the server replays it. |
| 580 | const [first, resent] = state.start.mock.calls.map(([call]) => call.input); |
| 581 | expect(state.start).toHaveBeenCalledTimes(2); |
| 582 | expect(resent.commandId).toBe(first.commandId); |
| 583 | expect(resent.message.messageId).toBe(first.message.messageId); |
| 584 | expect(remaining()).toEqual([]); |
| 585 | }); |
| 586 | |
| 587 | it("hands back a task edited while its launch was in flight", async () => { |
| 588 | await loseLaunchReply(queuedTask(), "Edited idea"); |
| 589 | await fireRetry(); |
| 590 | |
| 591 | expect(state.draftText).toBe("Keep this draft separate\nEdited idea"); |
| 592 | expect(state.start).toHaveBeenCalledOnce(); |
| 593 | expect(remaining()).toEqual([]); |
| 594 | }); |
| 595 | |
| 596 | it("holds the resend while operation access is missing", async () => { |
| 597 | await loseLaunchReply(queuedTask()); |
| 598 | setOperateGrant("secondary", false); |
| 599 | vi.advanceTimersByTime(threadOutboxRetryDelayMs(1)); |
| 600 | expect(sendingMessageIds()).toEqual([]); |
| 601 | expect(state.start).toHaveBeenCalledOnce(); |
| 602 | expect(remaining()).toHaveLength(1); |
| 603 | |
| 604 | setOperateGrant("secondary", true); |
| 605 | await runDrain(); |
| 606 | expect(state.start).toHaveBeenCalledTimes(2); |
| 607 | expect(state.draftText).toBe("Keep this draft separate"); |
| 608 | expect(remaining()).toEqual([]); |
| 609 | }); |
| 610 | |
| 611 | it("resends a pull request task in its launched worktree without checking out again", async () => { |
| 612 | state.checkout.mockResolvedValueOnce( |
| 613 | AsyncResult.success({ |
| 614 | branch: "pr-123", |
| 615 | worktreePath: "/repo/.t3/worktrees/pr-123", |
| 616 | isOnPullRequestHead: true, |
| 617 | }), |
| 618 | ); |
| 619 | await loseLaunchReply( |
| 620 | queuedTask({ |
| 621 | workspaceMode: "worktree", |
| 622 | branch: "fork/feature", |
| 623 | pullRequestReference: "https://github.com/acme/repo/pull/123", |
| 624 | }), |
| 625 | ); |
| 626 | await fireRetry(); |
| 627 | |
| 628 | expect(state.checkout).toHaveBeenCalledOnce(); |
| 629 | const [first, resent] = state.start.mock.calls.map(([call]) => call.input); |
| 630 | expect(resent.bootstrap.createThread.worktreePath).toBe("/repo/.t3/worktrees/pr-123"); |
| 631 | expect(resent.bootstrap).toEqual(first.bootstrap); |
| 632 | expect(remaining()).toEqual([]); |
| 633 | }); |
| 634 | }); |
| 635 | |
| 636 | describe("compaction before a queued send", () => { |
| 637 | const compactTurn = { |
| 638 | commandId: "command:compact", |
| 639 | message: { |
| 640 | messageId: "message:compact", |
| 641 | role: "user", |
| 642 | text: "/compact", |
| 643 | attachments: [], |
| 644 | idleCompaction: "onReturn", |
| 645 | }, |
| 646 | dispatchMode: "queue", |
| 647 | }; |
| 648 | |
| 649 | it("queues /compact ahead of the message and resends the same /compact on a retry", async () => { |
| 650 | setOperateGrant("secondary", true); |
| 651 | const queued = message({ compactBeforeSend: true, dispatchMode: "queue" }); |
| 652 | await state.manager.enqueue(queued); |
| 653 | state.start |
| 654 | .mockResolvedValueOnce(AsyncResult.success({})) |
| 655 | .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Socket is not connected")))); |
| 656 | await runDrain(); |
| 657 | expect(remaining()).toEqual([queued]); |
| 658 | |
| 659 | // A restarted app delivers the persisted message again. |
| 660 | state.cleanups.splice(0).forEach((cleanup) => cleanup()); |
| 661 | await runDrain(); |
| 662 | expect(state.start.mock.calls.map(([call]) => call.input)).toEqual([ |
| 663 | expect.objectContaining(compactTurn), |
| 664 | expect.objectContaining({ commandId: "command", dispatchMode: "queue" }), |
| 665 | expect.objectContaining(compactTurn), |
| 666 | expect.objectContaining({ commandId: "command", dispatchMode: "queue" }), |
| 667 | ]); |
| 668 | expect(remaining()).toEqual([]); |
| 669 | }); |
| 670 | |
| 671 | it("holds the message when its /compact cannot be sent", async () => { |
| 672 | setOperateGrant("secondary", true); |
| 673 | const queued = message({ compactBeforeSend: true, dispatchMode: "queue" }); |
| 674 | await state.manager.enqueue(queued); |
| 675 | state.start.mockResolvedValueOnce( |
| 676 | AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))), |
| 677 | ); |
| 678 | await runDrain(); |
| 679 | expect(state.start).toHaveBeenCalledOnce(); |
| 680 | expect(state.start.mock.calls[0]?.[0].input).toMatchObject(compactTurn); |
| 681 | expect(remaining()).toEqual([queued]); |
| 682 | }); |
| 683 | }); |
| 684 | |
| 685 | describe("queued delivery timing", () => { |
| 686 | /** Runs `change`, then resolves once the delivery it starts has settled. */ |
| 687 | async function deliveryAfter(change: () => void): Promise<void> { |
| 688 | const started = Promise.withResolvers<void>(); |
| 689 | const settled = Promise.withResolvers<void>(); |
| 690 | const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdsAtom, (ids) => { |
| 691 | if (Object.keys(ids).length > 0) started.resolve(); |
| 692 | else settled.resolve(); |
| 693 | }); |
| 694 | change(); |
| 695 | await started.promise; |
| 696 | await settled.promise.finally(release); |
| 697 | } |
| 698 | |
| 699 | it("starts a thread's next message only after its interrupted send has finished", async () => { |
| 700 | setOperateGrant("secondary", true); |
| 701 | const firstStarted = Promise.withResolvers<void>(); |
| 702 | const finishFirst = Promise.withResolvers<AsyncResult.AsyncResult<object, never>>(); |
| 703 | state.start.mockImplementationOnce(async () => { |
| 704 | firstStarted.resolve(); |
| 705 | return finishFirst.promise; |
| 706 | }); |
| 707 | const first = message(); |
| 708 | await state.manager.enqueue(first); |
| 709 | startDelivery(); |
| 710 | await firstStarted.promise; |
| 711 | // The queue empties under the running send, then the thread gets its next message. |
| 712 | await state.manager.remove(first); |
| 713 | const allDelivered = Promise.withResolvers<void>(); |
| 714 | const release = appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, () => { |
| 715 | if (remaining().length === 0) allDelivered.resolve(); |
| 716 | }); |
| 717 | await state.manager.enqueue( |
| 718 | message({ messageId: MessageId.make("next"), commandId: CommandId.make("next-command") }), |
| 719 | ); |
| 720 | // The next message waits; only the interrupted send is still marked as sending. |
| 721 | expect(sendingMessageIds()).toEqual(["message"]); |
| 722 | expect(state.start).toHaveBeenCalledOnce(); |
| 723 | finishFirst.resolve(AsyncResult.success({})); |
| 724 | await allDelivered.promise.finally(release); |
| 725 | expect(state.start).toHaveBeenCalledTimes(2); |
| 726 | }); |
| 727 | |
| 728 | it("sends another thread's message while one thread's send is still running", async () => { |
| 729 | setOperateGrant("secondary", true); |
| 730 | const other = { ...state.thread, id: "other" }; |
| 731 | appAtomRegistry.set(state.threadShells, [state.thread, other]); |
| 732 | const slowStarted = Promise.withResolvers<void>(); |
| 733 | const finishSlow = Promise.withResolvers<AsyncResult.AsyncResult<object, never>>(); |
| 734 | state.start.mockImplementation(async ({ input }: { input: { threadId: string } }) => { |
| 735 | if (input.threadId !== "thread") return AsyncResult.success({}); |
| 736 | slowStarted.resolve(); |
| 737 | return finishSlow.promise; |
| 738 | }); |
| 739 | /** Resolves once only these message ids are still queued. */ |
| 740 | const queuedBecomes = (ids: ReadonlyArray<string>) => { |
| 741 | const reached = Promise.withResolvers<void>(); |
| 742 | const release = appAtomRegistry.subscribe(state.manager.queuedMessagesByThreadKeyAtom, () => { |
| 743 | if ( |
| 744 | remaining() |
| 745 | .map((queued) => queued.messageId) |
| 746 | .join() === ids.join() |
| 747 | ) { |
| 748 | reached.resolve(); |
| 749 | } |
| 750 | }); |
| 751 | return reached.promise.finally(release); |
| 752 | }; |
| 753 | await state.manager.enqueue(message()); |
| 754 | startDelivery(); |
| 755 | await slowStarted.promise; |
| 756 | const otherDelivered = queuedBecomes(["message"]); |
| 757 | await state.manager.enqueue( |
| 758 | message({ |
| 759 | threadId: ThreadId.make("other"), |
| 760 | messageId: MessageId.make("other-message"), |
| 761 | commandId: CommandId.make("other-command"), |
| 762 | }), |
| 763 | ); |
| 764 | await otherDelivered; |
| 765 | const allDelivered = queuedBecomes([]); |
| 766 | finishSlow.resolve(AsyncResult.success({})); |
| 767 | await allDelivered; |
| 768 | expect(state.start).toHaveBeenCalledTimes(2); |
| 769 | }); |
| 770 | |
| 771 | it("sends at once when its environment reconnects instead of waiting out the backoff", async () => { |
| 772 | setOperateGrant("secondary", true); |
| 773 | vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); |
| 774 | state.cleanups.push(() => vi.useRealTimers()); |
| 775 | const environments = workspaceConnections.environmentsAtom as unknown as Atom.Writable< |
| 776 | ReadonlyArray<{ environmentId: string; connectionState: string }> |
| 777 | >; |
| 778 | const connected = [{ environmentId: "secondary", connectionState: "connected" }]; |
| 779 | state.cleanups.push(() => appAtomRegistry.set(environments, connected)); |
| 780 | await state.manager.enqueue(message()); |
| 781 | state.start.mockResolvedValueOnce( |
| 782 | AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))), |
| 783 | ); |
| 784 | await runDrain(); |
| 785 | expect(state.start).toHaveBeenCalledOnce(); |
| 786 | |
| 787 | appAtomRegistry.set(environments, [ |
| 788 | { environmentId: "secondary", connectionState: "disconnected" }, |
| 789 | ]); |
| 790 | await deliveryAfter(() => appAtomRegistry.set(environments, connected)); |
| 791 | expect(state.start).toHaveBeenCalledTimes(2); |
| 792 | expect(remaining()).toEqual([]); |
| 793 | }); |
| 794 | }); |