The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | AuthOrchestrationOperateScope, |
| 3 | DEFAULT_SERVER_SETTINGS, |
| 4 | EnvironmentId, |
| 5 | MessageId, |
| 6 | ProjectId, |
| 7 | ProviderDriverKind, |
| 8 | ProviderInstanceId, |
| 9 | RunId, |
| 10 | RuntimeRequestId, |
| 11 | ThreadId, |
| 12 | TurnItemId, |
| 13 | type ModelSelection, |
| 14 | type OrchestrationMessageContext, |
| 15 | type OrchestrationV2ThreadProjection, |
| 16 | type RuntimeMode, |
| 17 | type ServerConfig, |
| 18 | } from "@t3tools/contracts"; |
| 19 | import { |
| 20 | v2Now, |
| 21 | v2Projection, |
| 22 | } from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; |
| 23 | import type { DraftComposerImageAttachment } from "../lib/composerImages"; |
| 24 | import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; |
| 25 | import { |
| 26 | makeThreadRequestsResolvedAnnouncer, |
| 27 | sendApprovalFeedback, |
| 28 | } from "@t3tools/client-runtime/state/thread-requests"; |
| 29 | import { DateTime } from "effect"; |
| 30 | import { AsyncResult, type Atom } from "effect/reactivity"; |
| 31 | import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; |
| 32 | |
| 33 | const state = vi.hoisted(() => ({ |
| 34 | grantedEnvironments: new Set<string>(), |
| 35 | connectionState: "connected", |
| 36 | draft: { |
| 37 | text: "Keep my draft", |
| 38 | attachments: [] as DraftComposerImageAttachment[], |
| 39 | context: undefined as OrchestrationMessageContext | undefined, |
| 40 | modelSelection: undefined as ModelSelection | undefined, |
| 41 | runtimeMode: undefined as RuntimeMode | undefined, |
| 42 | }, |
| 43 | serverConfig: null as ServerConfig | null, |
| 44 | projection: null as OrchestrationV2ThreadProjection | null, |
| 45 | pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests, |
| 46 | enqueue: vi.fn(async () => undefined), |
| 47 | freshPending: false, |
| 48 | compactModel: null as string | null, |
| 49 | compactDueAt: "", |
| 50 | setFreshPending: vi.fn(), |
| 51 | clearDraft: vi.fn(), |
| 52 | appendAttachments: vi.fn(), |
| 53 | mergeDraft: vi.fn(), |
| 54 | fileHolds: [] as string[], |
| 55 | questionDrafts: {} as Record< |
| 56 | string, |
| 57 | { text: string; attachments: DraftComposerImageAttachment[] } |
| 58 | >, |
| 59 | approve: vi.fn(), |
| 60 | answer: vi.fn(), |
| 61 | feedback: vi.fn(), |
| 62 | updateSettings: vi.fn(), |
| 63 | question: { |
| 64 | id: "language", |
| 65 | header: "Language", |
| 66 | question: "Which language?", |
| 67 | options: [{ label: "TypeScript", description: "Use the existing code" }], |
| 68 | multiSelect: false, |
| 69 | }, |
| 70 | thread: { |
| 71 | id: "thread", |
| 72 | environmentId: "secondary", |
| 73 | lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null }, |
| 74 | projectId: "project", |
| 75 | modelSelection: { instanceId: "codex", model: "gpt-5.4" }, |
| 76 | runtimeMode: "full-access", |
| 77 | interactionMode: "default", |
| 78 | runtime: null, |
| 79 | latestRun: null as unknown, |
| 80 | }, |
| 81 | })); |
| 82 | |
| 83 | vi.mock("react", () => ({ |
| 84 | useCallback: <A>(callback: A) => callback, |
| 85 | useEffect: () => {}, |
| 86 | useLayoutEffect: () => {}, |
| 87 | useRef: <A>(current: A) => ({ current }), |
| 88 | useMemo: <A>(factory: () => A) => factory(), |
| 89 | useState: <A>(initial: A | (() => A)) => [ |
| 90 | typeof initial === "function" ? (initial as () => A)() : initial, |
| 91 | vi.fn(), |
| 92 | ], |
| 93 | })); |
| 94 | vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" })); |
| 95 | vi.mock("gt-react-native", async (importOriginal) => { |
| 96 | const gt = await importOriginal<typeof import("gt-react-native")>(); |
| 97 | return { |
| 98 | ...gt, |
| 99 | useGT: () => gt.mFallback, |
| 100 | useLocale: () => "en", |
| 101 | useMessages: () => gt.mFallback, |
| 102 | }; |
| 103 | }); |
| 104 | vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) => ({ |
| 105 | ...(await importOriginal<typeof import("@t3tools/client-runtime/state/context-window")>()), |
| 106 | compactBeforeSendTokens: (input: { readonly selection: ModelSelection; readonly now: string }) => |
| 107 | input.selection.model === state.compactModel && input.now >= state.compactDueAt |
| 108 | ? 248_000 |
| 109 | : null, |
| 110 | })); |
| 111 | vi.mock("../lib/clock", () => ({ useNowMinuteMs: () => 0 })); |
| 112 | vi.mock("../lib/attachmentUpload", async () => { |
| 113 | const { Effect } = await import("effect"); |
| 114 | return { |
| 115 | prepareTurnAttachments: vi.fn( |
| 116 | (input: { readonly attachments: ReadonlyArray<{ readonly id: string }> }) => |
| 117 | Effect.succeed({ |
| 118 | status: "ready", |
| 119 | attachments: input.attachments.map((attachment) => ({ |
| 120 | type: "image", |
| 121 | id: `uploaded-${attachment.id}`, |
| 122 | name: "shot.png", |
| 123 | mimeType: "image/png", |
| 124 | sizeBytes: 1, |
| 125 | })), |
| 126 | }), |
| 127 | ), |
| 128 | }; |
| 129 | }); |
| 130 | vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" })); |
| 131 | vi.mock("../lib/composerAttachmentPreviewRetention", () => ({ |
| 132 | retainComposerAttachmentFileForPreview: (attachment: { readonly fileUri: string }) => { |
| 133 | state.fileHolds.push(attachment.fileUri); |
| 134 | return () => { |
| 135 | state.fileHolds.splice(state.fileHolds.indexOf(attachment.fileUri), 1); |
| 136 | }; |
| 137 | }, |
| 138 | })); |
| 139 | vi.mock("./queued-run-edit", () => ({ |
| 140 | useQueuedRunEdit: () => null, |
| 141 | getQueuedRunEdit: () => null, |
| 142 | })); |
| 143 | vi.mock("./preferences", async () => { |
| 144 | const { Atom, AsyncResult } = await import("effect/reactivity"); |
| 145 | return { mobilePreferencesAtom: Atom.make(AsyncResult.success({})) }; |
| 146 | }); |
| 147 | vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } })); |
| 148 | vi.mock("@effect/atom-react", async () => { |
| 149 | const { appAtomRegistry } = await import("./atom-registry"); |
| 150 | return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) }; |
| 151 | }); |
| 152 | vi.mock("./entities", () => ({ useServerConfigs: () => new Map() })); |
| 153 | vi.mock("./session", () => ({ |
| 154 | readEnvironmentScope: (environmentId: string, scope: string) => |
| 155 | scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId), |
| 156 | })); |
| 157 | vi.mock("./use-thread-selection", () => ({ |
| 158 | useThreadSelection: () => ({ |
| 159 | selectedThread: state.thread, |
| 160 | selectedThreadCreation: null, |
| 161 | selectedEnvironmentRuntime: { |
| 162 | connectionState: state.connectionState, |
| 163 | serverConfig: state.serverConfig, |
| 164 | }, |
| 165 | }), |
| 166 | })); |
| 167 | vi.mock("./use-thread-detail", () => ({ |
| 168 | useSelectedThreadProjection: () => |
| 169 | state.projection === null ? null : { projection: state.projection }, |
| 170 | useSelectedThreadVisibleTurnItems: () => [], |
| 171 | useSelectedThreadPendingRequests: () => state.pendingRequests, |
| 172 | })); |
| 173 | vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command })); |
| 174 | vi.mock("./threads", async () => { |
| 175 | const { Atom } = await import("effect/reactivity"); |
| 176 | return { |
| 177 | environmentThreadDetails: { |
| 178 | queueWorkflowAtom: () => Atom.make(null), |
| 179 | checkpointSummariesAtom: () => Atom.make([]), |
| 180 | sequenceAtom: () => Atom.make(0), |
| 181 | pendingRequestsAtom: () => Atom.make(state.pendingRequests), |
| 182 | }, |
| 183 | threadEnvironment: { |
| 184 | respondToApproval: state.approve, |
| 185 | respondToUserInput: state.answer, |
| 186 | uploadFeedback: state.feedback, |
| 187 | }, |
| 188 | }; |
| 189 | }); |
| 190 | vi.mock("./use-thread-outbox", async () => { |
| 191 | const { Atom } = await import("effect/reactivity"); |
| 192 | return { dispatchingQueuedMessageIdsAtom: Atom.make({}), useThreadOutboxMessages: () => ({}) }; |
| 193 | }); |
| 194 | vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue })); |
| 195 | vi.mock("./composer-attachment-uploads", async () => { |
| 196 | const { Atom } = await import("effect/reactivity"); |
| 197 | return { |
| 198 | composerAttachmentUploadsAtom: Atom.make({}), |
| 199 | composerAttachmentUploadBlockReason: () => null, |
| 200 | composerAttachmentsStillUploading: () => false, |
| 201 | uploadComposerAttachmentShared: vi.fn(), |
| 202 | }; |
| 203 | }); |
| 204 | vi.mock("./use-composer-drafts", async () => { |
| 205 | const { Atom } = await import("effect/reactivity"); |
| 206 | return { |
| 207 | composerDraftsAtom: Atom.make({}), |
| 208 | composerContextImportsAtom: Atom.make({}), |
| 209 | getComposerDraftSnapshot: () => state.draft, |
| 210 | isFreshSessionPending: () => state.freshPending, |
| 211 | setFreshSessionPending: state.setFreshPending, |
| 212 | clearComposerDraftContent: state.clearDraft, |
| 213 | clearComposerDraft: state.clearDraft, |
| 214 | setComposerDraftText: (_key: string, text: string) => { |
| 215 | state.draft.text = text; |
| 216 | }, |
| 217 | updateComposerDraftSettings: state.updateSettings, |
| 218 | ensureComposerDraftsLoaded: () => {}, |
| 219 | scheduleUnusedComposerAttachmentCleanup: () => {}, |
| 220 | appendComposerDraftAttachments: state.appendAttachments, |
| 221 | appendComposerDraftText: vi.fn(), |
| 222 | mergeComposerDraftContent: state.mergeDraft, |
| 223 | removeComposerDraftAttachment: vi.fn(), |
| 224 | useComposerDraft: () => state.draft, |
| 225 | useComposerDraftSettings: () => state.draft, |
| 226 | questionAttachmentDraftsAtom: () => Atom.make(state.questionDrafts), |
| 227 | }; |
| 228 | }); |
| 229 | vi.mock("../lib/composerImages", () => ({ |
| 230 | isFileBackedComposerAttachment: (attachment: { readonly fileUri?: string }) => |
| 231 | attachment.fileUri !== undefined, |
| 232 | convertPastedImagesToAttachments: vi.fn(), |
| 233 | pickComposerFiles: vi.fn(), |
| 234 | pickComposerMedia: vi.fn(), |
| 235 | })); |
| 236 | vi.mock("../lib/commandMetadata", () => ({ |
| 237 | makeQueuedMessageMetadata: () => ({ |
| 238 | messageId: "message", |
| 239 | commandId: "command", |
| 240 | createdAt: "2026-09-05T00:00:00.000Z", |
| 241 | }), |
| 242 | })); |
| 243 | vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() })); |
| 244 | vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() })); |
| 245 | |
| 246 | import { Alert } from "react-native"; |
| 247 | import { useThreadComposerState } from "./use-thread-composer-state"; |
| 248 | import { useSelectedThreadRequests } from "./use-selected-thread-requests"; |
| 249 | import { questionAttachmentDraftKey } from "./question-attachments"; |
| 250 | import { startQuestionImagePreparation } from "./question-attachment-preparation"; |
| 251 | import { abortComposerDraftOperations } from "./composerDraftOperations"; |
| 252 | |
| 253 | const NO_SIDE_CHATS = { startSideChat: async () => false }; |
| 254 | |
| 255 | beforeEach(() => { |
| 256 | state.grantedEnvironments = new Set(["primary"]); |
| 257 | state.connectionState = "connected"; |
| 258 | state.draft = { |
| 259 | text: "Keep my draft", |
| 260 | attachments: [], |
| 261 | context: undefined, |
| 262 | modelSelection: undefined, |
| 263 | runtimeMode: undefined, |
| 264 | }; |
| 265 | state.freshPending = false; |
| 266 | state.questionDrafts = {}; |
| 267 | state.compactModel = null; |
| 268 | state.compactDueAt = ""; |
| 269 | state.thread.latestRun = null; |
| 270 | state.projection = null; |
| 271 | state.serverConfig = { |
| 272 | providers: [{ instanceId: "codex", driver: "codex", enabled: true }], |
| 273 | environment: { capabilities: {} }, |
| 274 | } as unknown as ServerConfig; |
| 275 | state.pendingRequests = { |
| 276 | approvals: [ |
| 277 | { |
| 278 | requestId: RuntimeRequestId.make("approval"), |
| 279 | requestKind: "command", |
| 280 | createdAt: "2026-09-05T00:00:00.000Z", |
| 281 | responseCapability: "live", |
| 282 | }, |
| 283 | ], |
| 284 | userInputs: [], |
| 285 | }; |
| 286 | vi.clearAllMocks(); |
| 287 | state.approve.mockResolvedValue(AsyncResult.success(undefined)); |
| 288 | state.answer.mockResolvedValue(AsyncResult.success(undefined)); |
| 289 | state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" })); |
| 290 | }); |
| 291 | |
| 292 | describe("mobile task permissions", () => { |
| 293 | it("consumes an approval reply without queueing a parent message", async () => { |
| 294 | state.grantedEnvironments.add("secondary"); |
| 295 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 296 | const requests = useSelectedThreadRequests(); |
| 297 | const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true }; |
| 298 | const messageId = await composer.onSendMessage(undefined, async (text) => |
| 299 | (await sendApprovalFeedback(approval, text, requests.onRespondToApproval)) |
| 300 | ? "responded" |
| 301 | : false, |
| 302 | ); |
| 303 | expect(messageId).toBeNull(); |
| 304 | expect(state.approve).toHaveBeenCalledWith({ |
| 305 | environmentId: "secondary", |
| 306 | input: { |
| 307 | threadId: "thread", |
| 308 | requestId: "approval", |
| 309 | decision: "decline", |
| 310 | feedback: "Keep my draft", |
| 311 | }, |
| 312 | }); |
| 313 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 314 | expect(state.clearDraft).toHaveBeenCalledOnce(); |
| 315 | }); |
| 316 | |
| 317 | it("preserves a draft changed during an approval reply and never sends it to the parent", async () => { |
| 318 | state.grantedEnvironments.add("secondary"); |
| 319 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 320 | const beforeDispatch = async () => { |
| 321 | state.draft = { ...state.draft, text: "New feedback" }; |
| 322 | return "responded" as const; |
| 323 | }; |
| 324 | expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull(); |
| 325 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 326 | expect(state.clearDraft).not.toHaveBeenCalled(); |
| 327 | expect(state.draft.text).toBe("New feedback"); |
| 328 | }); |
| 329 | |
| 330 | it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => { |
| 331 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 332 | expect(await composer.onSendMessage()).toBeNull(); |
| 333 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 334 | expect(state.clearDraft).not.toHaveBeenCalled(); |
| 335 | composer.onChangeDraftMessage("Edited locally"); |
| 336 | expect(state.draft.text).toBe("Edited locally"); |
| 337 | }); |
| 338 | |
| 339 | it("keeps an armed fresh session for the message after an approval redirect", async () => { |
| 340 | state.grantedEnvironments.add("secondary"); |
| 341 | state.freshPending = true; |
| 342 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 343 | expect(await composer.onSendMessage(undefined, async () => true)).toBe("message"); |
| 344 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 345 | expect.not.objectContaining({ freshContext: true }), |
| 346 | ); |
| 347 | expect(state.setFreshPending).not.toHaveBeenCalled(); |
| 348 | expect(await composer.onSendMessage()).toBe("message"); |
| 349 | expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true })); |
| 350 | expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false); |
| 351 | }); |
| 352 | |
| 353 | it("compacts a stale thread before sending unless kept or a fresh session is armed", async () => { |
| 354 | state.grantedEnvironments.add("secondary"); |
| 355 | state.projection = { |
| 356 | thread: { |
| 357 | ...state.thread, |
| 358 | activeProviderThreadId: null, |
| 359 | lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null }, |
| 360 | }, |
| 361 | runs: [], |
| 362 | attempts: [], |
| 363 | nodes: [], |
| 364 | subagents: [], |
| 365 | providerSessions: [], |
| 366 | providerThreads: [], |
| 367 | providerTurns: [], |
| 368 | runtimeRequests: [], |
| 369 | messages: [], |
| 370 | plans: [], |
| 371 | turnItems: [], |
| 372 | checkpointScopes: [], |
| 373 | checkpoints: [], |
| 374 | contextHandoffs: [], |
| 375 | contextTransfers: [], |
| 376 | visibleTurnItems: [], |
| 377 | updatedAt: DateTime.makeUnsafe(0), |
| 378 | } as unknown as OrchestrationV2ThreadProjection; |
| 379 | state.compactModel = "gpt-5.4"; |
| 380 | // The notice's minute clock (the epoch here) trails a deadline the send's exact time has passed. |
| 381 | state.compactDueAt = "2026-01-01T00:00:00.000Z"; |
| 382 | const unannounced = useThreadComposerState(NO_SIDE_CHATS); |
| 383 | expect(unannounced.compactBeforeSend).toBeNull(); |
| 384 | await unannounced.onSendMessage(); |
| 385 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 386 | expect.not.objectContaining({ compactBeforeSend: true }), |
| 387 | ); |
| 388 | state.compactDueAt = ""; |
| 389 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 390 | expect(composer.compactBeforeSend?.tokens).toBe(248_000); |
| 391 | await composer.onSendMessage(); |
| 392 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 393 | expect.objectContaining({ compactBeforeSend: true }), |
| 394 | ); |
| 395 | // A model picked after the last render still decides the send. |
| 396 | state.draft = { |
| 397 | ...state.draft, |
| 398 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" }, |
| 399 | }; |
| 400 | await composer.onSendMessage(); |
| 401 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 402 | expect.not.objectContaining({ compactBeforeSend: true }), |
| 403 | ); |
| 404 | state.draft = { ...state.draft, modelSelection: undefined }; |
| 405 | composer.compactBeforeSend?.toggleKeepFullHistory(); |
| 406 | const kept = useThreadComposerState(NO_SIDE_CHATS); |
| 407 | expect(kept.compactBeforeSend?.keepFullHistory).toBe(true); |
| 408 | kept.compactBeforeSend?.toggleKeepFullHistory(); |
| 409 | const compactAgain = useThreadComposerState(NO_SIDE_CHATS); |
| 410 | expect(compactAgain.compactBeforeSend?.keepFullHistory).toBe(false); |
| 411 | await compactAgain.onSendMessage(); |
| 412 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 413 | expect.objectContaining({ compactBeforeSend: true }), |
| 414 | ); |
| 415 | compactAgain.compactBeforeSend?.toggleKeepFullHistory(); |
| 416 | await useThreadComposerState(NO_SIDE_CHATS).onSendMessage(); |
| 417 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 418 | expect.not.objectContaining({ compactBeforeSend: true }), |
| 419 | ); |
| 420 | // Keeping covers one send, as on web. |
| 421 | expect(useThreadComposerState(NO_SIDE_CHATS).compactBeforeSend?.keepFullHistory).toBe(false); |
| 422 | state.freshPending = true; |
| 423 | await composer.onSendMessage(); |
| 424 | expect(state.enqueue).toHaveBeenLastCalledWith( |
| 425 | expect.not.objectContaining({ compactBeforeSend: true }), |
| 426 | ); |
| 427 | expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true })); |
| 428 | }); |
| 429 | |
| 430 | it("sends a typed /clear with an approval redirect as that reply's text", async () => { |
| 431 | state.grantedEnvironments.add("secondary"); |
| 432 | state.serverConfig = { |
| 433 | ...state.serverConfig, |
| 434 | environment: { capabilities: { freshContext: true } }, |
| 435 | } as ServerConfig; |
| 436 | state.thread.latestRun = { runId: "run" }; |
| 437 | state.draft = { ...state.draft, text: "/clear" }; |
| 438 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 439 | const beforeDispatch = vi.fn(async () => "responded" as const); |
| 440 | expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull(); |
| 441 | expect(beforeDispatch).toHaveBeenCalledWith("/clear", false); |
| 442 | expect(state.setFreshPending).not.toHaveBeenCalled(); |
| 443 | }); |
| 444 | |
| 445 | it("starts a side chat for /side instead of sending to the thread", async () => { |
| 446 | state.grantedEnvironments.add("secondary"); |
| 447 | state.serverConfig = { |
| 448 | ...state.serverConfig, |
| 449 | environment: { capabilities: { sideChats: true } }, |
| 450 | } as ServerConfig; |
| 451 | // The thread gets the composer's mode and model only on its next send. |
| 452 | const selection: ModelSelection = { |
| 453 | instanceId: ProviderInstanceId.make("codex"), |
| 454 | model: "gpt-5.4", |
| 455 | options: [{ id: "reasoningEffort", value: "xhigh" }], |
| 456 | }; |
| 457 | state.draft = { |
| 458 | ...state.draft, |
| 459 | text: "/side why does this fail?", |
| 460 | modelSelection: selection, |
| 461 | runtimeMode: "approval-required", |
| 462 | }; |
| 463 | const startSideChat = vi.fn(async () => true); |
| 464 | const composer = useThreadComposerState({ startSideChat }); |
| 465 | expect(composer.sideChatUnavailableReason).toBeNull(); |
| 466 | expect(await composer.onSendMessage()).toBeNull(); |
| 467 | expect(startSideChat).toHaveBeenCalledExactlyOnceWith( |
| 468 | { environmentId: "secondary", threadId: "thread" }, |
| 469 | { text: "why does this fail?", attachments: [], titleSeed: "why does this fail?" }, |
| 470 | { runtimeMode: "approval-required", modelSelection: selection }, |
| 471 | ); |
| 472 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 473 | expect(state.clearDraft).toHaveBeenCalled(); |
| 474 | |
| 475 | // Attachments and context go to the side chat, bound to their uploaded ids. |
| 476 | vi.clearAllMocks(); |
| 477 | const imageRecord = { |
| 478 | version: 1, |
| 479 | kind: "image", |
| 480 | contextId: "image-shot", |
| 481 | label: "shot.png", |
| 482 | attachmentId: "shot", |
| 483 | name: "shot.png", |
| 484 | mimeType: "image/png", |
| 485 | sizeBytes: 1, |
| 486 | } as OrchestrationMessageContext["records"][number]; |
| 487 | state.draft = { |
| 488 | ...state.draft, |
| 489 | text: "/side what is this?", |
| 490 | attachments: [ |
| 491 | { id: "shot", type: "image", name: "shot.png" } as DraftComposerImageAttachment, |
| 492 | ], |
| 493 | context: { version: 1, records: [imageRecord] }, |
| 494 | }; |
| 495 | expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull(); |
| 496 | expect(startSideChat).toHaveBeenCalledExactlyOnceWith( |
| 497 | { environmentId: "secondary", threadId: "thread" }, |
| 498 | expect.objectContaining({ |
| 499 | text: "what is this?", |
| 500 | attachments: [expect.objectContaining({ id: "uploaded-shot" })], |
| 501 | context: { version: 1, records: [{ ...imageRecord, attachmentId: "uploaded-shot" }] }, |
| 502 | }), |
| 503 | expect.anything(), |
| 504 | ); |
| 505 | expect(state.clearDraft).toHaveBeenCalled(); |
| 506 | state.draft = { ...state.draft, context: undefined }; |
| 507 | |
| 508 | // A failed start restores the draft: text first, since the merge caps attachments, then |
| 509 | // the uncapped attachments. The local file stays on disk meanwhile, and no send runs from |
| 510 | // the half-restored draft. |
| 511 | vi.clearAllMocks(); |
| 512 | let heldDuringStart: string[] = []; |
| 513 | startSideChat.mockImplementationOnce(async () => { |
| 514 | heldDuringStart = [...state.fileHolds]; |
| 515 | return false; |
| 516 | }); |
| 517 | const shot = { id: "shot", fileUri: "file:///shot.png" } as DraftComposerImageAttachment; |
| 518 | const sent = { ...state.draft, attachments: [shot] }; |
| 519 | state.draft = sent; |
| 520 | const restoring = useThreadComposerState({ startSideChat }); |
| 521 | const restoreOrder: string[] = []; |
| 522 | state.mergeDraft.mockImplementationOnce(async (_key, content) => { |
| 523 | state.draft = { ...sent, text: "new text" }; |
| 524 | await restoring.onSendMessage(); |
| 525 | restoreOrder.push(`merge ${content.text}`); |
| 526 | }); |
| 527 | state.appendAttachments.mockImplementationOnce((_key, attachments, options) => |
| 528 | restoreOrder.push(`append ${attachments.length} restore=${options.restore}`), |
| 529 | ); |
| 530 | expect(await restoring.onSendMessage()).toBeNull(); |
| 531 | expect(restoreOrder).toEqual(["merge /side what is this?", "append 1 restore=true"]); |
| 532 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 533 | expect(heldDuringStart).toEqual(["file:///shot.png"]); |
| 534 | expect(state.fileHolds).toEqual([]); |
| 535 | // A model the send would refuse does not start a side chat either. |
| 536 | vi.clearAllMocks(); |
| 537 | state.serverConfig = { |
| 538 | ...state.serverConfig, |
| 539 | providers: [{ instanceId: "codex", driver: "codex", enabled: false }], |
| 540 | } as unknown as ServerConfig; |
| 541 | state.draft = { ...state.draft, attachments: [] }; |
| 542 | expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull(); |
| 543 | expect(startSideChat).not.toHaveBeenCalled(); |
| 544 | expect(Alert.alert).toHaveBeenCalledOnce(); |
| 545 | }); |
| 546 | |
| 547 | it("rechecks a retained send callback before clearing or queueing the draft", async () => { |
| 548 | state.grantedEnvironments.add("secondary"); |
| 549 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 550 | state.grantedEnvironments.delete("secondary"); |
| 551 | expect(await composer.onSendMessage()).toBeNull(); |
| 552 | expect(state.clearDraft).not.toHaveBeenCalled(); |
| 553 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 554 | state.grantedEnvironments.add("secondary"); |
| 555 | expect(await composer.onSendMessage()).toBe("message"); |
| 556 | expect(state.enqueue).toHaveBeenCalledWith( |
| 557 | expect.objectContaining({ |
| 558 | environmentId: "secondary", |
| 559 | threadId: "thread", |
| 560 | text: "Keep my draft", |
| 561 | }), |
| 562 | ); |
| 563 | }); |
| 564 | |
| 565 | it("queues a goal command with the thread's settings and leaves the draft alone", async () => { |
| 566 | state.grantedEnvironments.add("secondary"); |
| 567 | state.draft.modelSelection = { |
| 568 | instanceId: ProviderInstanceId.make("claudeAgent"), |
| 569 | model: "claude-sonnet-5-5", |
| 570 | }; |
| 571 | Object.assign(state.draft, { runtimeMode: "approval-required" }); |
| 572 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 573 | expect(await composer.onSendCommand("/goal clear")).toBe("message"); |
| 574 | expect(state.enqueue).toHaveBeenCalledExactlyOnceWith( |
| 575 | expect.objectContaining({ |
| 576 | environmentId: "secondary", |
| 577 | threadId: "thread", |
| 578 | text: "/goal clear", |
| 579 | restoreToDraft: false, |
| 580 | attachments: [], |
| 581 | modelSelection: state.thread.modelSelection, |
| 582 | runtimeMode: state.thread.runtimeMode, |
| 583 | }), |
| 584 | ); |
| 585 | expect(state.clearDraft).not.toHaveBeenCalled(); |
| 586 | expect(state.draft.text).toBe("Keep my draft"); |
| 587 | }); |
| 588 | |
| 589 | it("rechecks the operate grant before queueing a command", async () => { |
| 590 | state.grantedEnvironments.add("secondary"); |
| 591 | const composer = useThreadComposerState(NO_SIDE_CHATS); |
| 592 | state.grantedEnvironments.delete("secondary"); |
| 593 | expect(await composer.onSendCommand("/goal clear")).toBeNull(); |
| 594 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 595 | }); |
| 596 | |
| 597 | it("rechecks the target environment before an approval response", async () => { |
| 598 | state.grantedEnvironments.add("secondary"); |
| 599 | const requests = useSelectedThreadRequests(); |
| 600 | state.grantedEnvironments.delete("secondary"); |
| 601 | await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept"); |
| 602 | expect(state.approve).not.toHaveBeenCalled(); |
| 603 | state.grantedEnvironments.add("secondary"); |
| 604 | await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept"); |
| 605 | expect(state.approve).toHaveBeenCalledWith({ |
| 606 | environmentId: "secondary", |
| 607 | input: { threadId: "thread", requestId: "approval", decision: "accept" }, |
| 608 | }); |
| 609 | }); |
| 610 | |
| 611 | it("keeps answer drafts editable after revocation while blocking their submission", async () => { |
| 612 | state.pendingRequests = { |
| 613 | approvals: [], |
| 614 | userInputs: [ |
| 615 | { |
| 616 | requestId: RuntimeRequestId.make("input"), |
| 617 | createdAt: "2026-09-05T00:00:00.000Z", |
| 618 | responseCapability: "live", |
| 619 | dismissible: false, |
| 620 | questions: [state.question], |
| 621 | }, |
| 622 | ], |
| 623 | }; |
| 624 | const requestId = RuntimeRequestId.make("input"); |
| 625 | useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript"); |
| 626 | state.grantedEnvironments.add("secondary"); |
| 627 | const requests = useSelectedThreadRequests(); |
| 628 | expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" }); |
| 629 | state.grantedEnvironments.delete("secondary"); |
| 630 | await requests.onSubmitUserInput(); |
| 631 | expect(state.answer).not.toHaveBeenCalled(); |
| 632 | expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({ |
| 633 | language: "TypeScript", |
| 634 | }); |
| 635 | state.grantedEnvironments.add("secondary"); |
| 636 | await requests.onSubmitUserInput(); |
| 637 | expect(state.answer).toHaveBeenCalledWith({ |
| 638 | environmentId: "secondary", |
| 639 | input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } }, |
| 640 | }); |
| 641 | }); |
| 642 | }); |
| 643 | |
| 644 | it.each(["cancelled", "expired"] as const)( |
| 645 | "returns unsent attachments to the thread composer when a question is %s", |
| 646 | (status) => { |
| 647 | const environmentId = EnvironmentId.make("secondary"); |
| 648 | const threadId = ThreadId.make("thread"); |
| 649 | const unanswered = RuntimeRequestId.make("input"); |
| 650 | const answered = RuntimeRequestId.make("input-other"); |
| 651 | const questionKey = questionAttachmentDraftKey(environmentId, threadId, unanswered, "language"); |
| 652 | const preparing = startQuestionImagePreparation(questionKey); |
| 653 | const preparingAnswered = startQuestionImagePreparation( |
| 654 | questionAttachmentDraftKey(environmentId, threadId, answered, "language"), |
| 655 | ); |
| 656 | using _preparations = { |
| 657 | [Symbol.dispose]: () => { |
| 658 | preparing.finish(); |
| 659 | preparingAnswered.finish(); |
| 660 | }, |
| 661 | }; |
| 662 | const notes = { |
| 663 | id: "notes", |
| 664 | type: "file", |
| 665 | name: "notes.txt", |
| 666 | mimeType: "text/plain", |
| 667 | sizeBytes: 5, |
| 668 | } as unknown as DraftComposerImageAttachment; |
| 669 | state.questionDrafts = { |
| 670 | [questionKey]: { |
| 671 | text: "", |
| 672 | attachments: [notes], |
| 673 | }, |
| 674 | }; |
| 675 | makeThreadRequestsResolvedAnnouncer( |
| 676 | environmentId, |
| 677 | threadId, |
| 678 | )([ |
| 679 | { id: unanswered, status }, |
| 680 | { id: answered, status: "resolved" }, |
| 681 | ]); |
| 682 | expect(state.appendAttachments).toHaveBeenCalledWith( |
| 683 | "secondary:thread", |
| 684 | [notes], |
| 685 | expect.objectContaining({ appendReference: true }), |
| 686 | ); |
| 687 | expect(preparing.destination()).toBe("secondary:thread"); |
| 688 | expect(preparingAnswered.destination()).toBeNull(); |
| 689 | abortComposerDraftOperations("secondary:thread"); |
| 690 | expect(preparing.destination()).toBeNull(); |
| 691 | }, |
| 692 | ); |
| 693 | |
| 694 | describe("mobile handoff preview and submission", () => { |
| 695 | it("follows project enablement and provider availability for the selected destination", async () => { |
| 696 | state.grantedEnvironments.add("secondary"); |
| 697 | const instanceId = ProviderInstanceId.make("antigravity"); |
| 698 | const projectId = ProjectId.make(state.thread.projectId); |
| 699 | const selection = { instanceId, model: "gemini" }; |
| 700 | const provider = { |
| 701 | instanceId, |
| 702 | driver: ProviderDriverKind.make("antigravity"), |
| 703 | enabled: false, |
| 704 | installed: true, |
| 705 | auth: { status: "authenticated" as const }, |
| 706 | availability: "available" as "available" | "unavailable", |
| 707 | models: [{ slug: selection.model }], |
| 708 | slashCommands: [], |
| 709 | }; |
| 710 | const projectOverride = { enabled: false }; |
| 711 | state.serverConfig = { |
| 712 | ...state.serverConfig, |
| 713 | providers: [provider], |
| 714 | settings: { |
| 715 | ...DEFAULT_SERVER_SETTINGS, |
| 716 | providerInstances: { [instanceId]: { driver: provider.driver, enabled: false } }, |
| 717 | projectSettingsOverrides: { |
| 718 | [projectId]: { providerInstances: { [instanceId]: projectOverride } }, |
| 719 | }, |
| 720 | }, |
| 721 | } as unknown as ServerConfig; |
| 722 | state.draft.modelSelection = selection; |
| 723 | const source = v2Projection.thread.modelSelection; |
| 724 | state.projection = { |
| 725 | ...v2Projection, |
| 726 | runs: [ |
| 727 | { |
| 728 | id: RunId.make("source-run"), |
| 729 | threadId: v2Projection.thread.id, |
| 730 | ordinal: 1, |
| 731 | providerInstanceId: source.instanceId, |
| 732 | modelSelection: source, |
| 733 | providerThreadId: null, |
| 734 | userMessageId: MessageId.make("source-message"), |
| 735 | rootNodeId: null, |
| 736 | activeAttemptId: null, |
| 737 | status: "completed", |
| 738 | requestedAt: v2Now, |
| 739 | startedAt: v2Now, |
| 740 | completedAt: v2Now, |
| 741 | checkpointId: null, |
| 742 | contextHandoffId: null, |
| 743 | }, |
| 744 | ], |
| 745 | visibleTurnItems: [ |
| 746 | { |
| 747 | position: 0, |
| 748 | visibility: "local", |
| 749 | sourceThreadId: v2Projection.thread.id, |
| 750 | sourceItemId: TurnItemId.make("reply"), |
| 751 | item: { |
| 752 | id: TurnItemId.make("reply"), |
| 753 | threadId: v2Projection.thread.id, |
| 754 | runId: RunId.make("source-run"), |
| 755 | nodeId: null, |
| 756 | providerThreadId: null, |
| 757 | providerTurnId: null, |
| 758 | nativeItemRef: null, |
| 759 | parentItemId: null, |
| 760 | ordinal: 1, |
| 761 | type: "assistant_message", |
| 762 | messageId: MessageId.make("reply"), |
| 763 | status: "completed", |
| 764 | title: null, |
| 765 | text: "Task started", |
| 766 | streaming: false, |
| 767 | startedAt: v2Now, |
| 768 | completedAt: v2Now, |
| 769 | updatedAt: v2Now, |
| 770 | }, |
| 771 | }, |
| 772 | ], |
| 773 | }; |
| 774 | |
| 775 | const disabled = useThreadComposerState(NO_SIDE_CHATS); |
| 776 | expect(disabled.pendingHandoff).toBeNull(); |
| 777 | expect(await disabled.onSendMessage()).toBeNull(); |
| 778 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 779 | expect(state.clearDraft).not.toHaveBeenCalled(); |
| 780 | |
| 781 | projectOverride.enabled = true; |
| 782 | expect(useThreadComposerState(NO_SIDE_CHATS).pendingHandoff).toEqual({ |
| 783 | from: [source], |
| 784 | to: selection, |
| 785 | }); |
| 786 | |
| 787 | provider.availability = "unavailable"; |
| 788 | const unavailable = useThreadComposerState(NO_SIDE_CHATS); |
| 789 | expect(unavailable.pendingHandoff).toBeNull(); |
| 790 | expect(await unavailable.onSendMessage()).toBeNull(); |
| 791 | expect(state.enqueue).not.toHaveBeenCalled(); |
| 792 | expect(state.clearDraft).not.toHaveBeenCalled(); |
| 793 | |
| 794 | provider.availability = "available"; |
| 795 | const available = useThreadComposerState(NO_SIDE_CHATS); |
| 796 | expect(available.pendingHandoff).toEqual({ from: [source], to: selection }); |
| 797 | expect(await available.onSendMessage()).toBe("message"); |
| 798 | expect(state.enqueue).toHaveBeenCalledExactlyOnceWith( |
| 799 | expect.objectContaining({ |
| 800 | modelSelection: selection, |
| 801 | text: "Keep my draft", |
| 802 | }), |
| 803 | ); |
| 804 | expect(state.clearDraft).toHaveBeenCalledTimes(1); |
| 805 | }); |
| 806 | }); |