Open History to see the last commit
1import {
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";
19import {
20 v2Now,
21 v2Projection,
22} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
23import type { DraftComposerImageAttachment } from "../lib/composerImages";
24import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
25import {
26 makeThreadRequestsResolvedAnnouncer,
27 sendApprovalFeedback,
28} from "@t3tools/client-runtime/state/thread-requests";
29import { DateTime } from "effect";
30import { AsyncResult, type Atom } from "effect/reactivity";
31import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
32
33const 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
83vi.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}));
94vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
95vi.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});
104vi.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}));
111vi.mock("../lib/clock", () => ({ useNowMinuteMs: () => 0 }));
112vi.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});
130vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
131vi.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}));
139vi.mock("./queued-run-edit", () => ({
140 useQueuedRunEdit: () => null,
141 getQueuedRunEdit: () => null,
142}));
143vi.mock("./preferences", async () => {
144 const { Atom, AsyncResult } = await import("effect/reactivity");
145 return { mobilePreferencesAtom: Atom.make(AsyncResult.success({})) };
146});
147vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
148vi.mock("@effect/atom-react", async () => {
149 const { appAtomRegistry } = await import("./atom-registry");
150 return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
151});
152vi.mock("./entities", () => ({ useServerConfigs: () => new Map() }));
153vi.mock("./session", () => ({
154 readEnvironmentScope: (environmentId: string, scope: string) =>
155 scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
156}));
157vi.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}));
167vi.mock("./use-thread-detail", () => ({
168 useSelectedThreadProjection: () =>
169 state.projection === null ? null : { projection: state.projection },
170 useSelectedThreadVisibleTurnItems: () => [],
171 useSelectedThreadPendingRequests: () => state.pendingRequests,
172}));
173vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
174vi.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});
190vi.mock("./use-thread-outbox", async () => {
191 const { Atom } = await import("effect/reactivity");
192 return { dispatchingQueuedMessageIdsAtom: Atom.make({}), useThreadOutboxMessages: () => ({}) };
193});
194vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue }));
195vi.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});
204vi.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});
229vi.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}));
236vi.mock("../lib/commandMetadata", () => ({
237 makeQueuedMessageMetadata: () => ({
238 messageId: "message",
239 commandId: "command",
240 createdAt: "2026-09-05T00:00:00.000Z",
241 }),
242}));
243vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
244vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
245
246import { Alert } from "react-native";
247import { useThreadComposerState } from "./use-thread-composer-state";
248import { useSelectedThreadRequests } from "./use-selected-thread-requests";
249import { questionAttachmentDraftKey } from "./question-attachments";
250
251const NO_SIDE_CHATS = { startSideChat: async () => false };
252
253beforeEach(() => {
254 state.grantedEnvironments = new Set(["primary"]);
255 state.connectionState = "connected";
256 state.draft = {
257 text: "Keep my draft",
258 attachments: [],
259 context: undefined,
260 modelSelection: undefined,
261 runtimeMode: undefined,
262 };
263 state.freshPending = false;
264 state.questionDrafts = {};
265 state.compactModel = null;
266 state.compactDueAt = "";
267 state.thread.latestRun = null;
268 state.projection = null;
269 state.serverConfig = {
270 providers: [{ instanceId: "codex", driver: "codex", enabled: true }],
271 environment: { capabilities: {} },
272 } as unknown as ServerConfig;
273 state.pendingRequests = {
274 approvals: [
275 {
276 requestId: RuntimeRequestId.make("approval"),
277 requestKind: "command",
278 createdAt: "2026-09-05T00:00:00.000Z",
279 responseCapability: "live",
280 },
281 ],
282 userInputs: [],
283 };
284 vi.clearAllMocks();
285 state.approve.mockResolvedValue(AsyncResult.success(undefined));
286 state.answer.mockResolvedValue(AsyncResult.success(undefined));
287 state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" }));
288});
289
290describe("mobile task permissions", () => {
291 it("consumes an approval reply without queueing a parent message", async () => {
292 state.grantedEnvironments.add("secondary");
293 const composer = useThreadComposerState(NO_SIDE_CHATS);
294 const requests = useSelectedThreadRequests();
295 const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
296 const messageId = await composer.onSendMessage(undefined, async (text) =>
297 (await sendApprovalFeedback(approval, text, requests.onRespondToApproval))
298 ? "responded"
299 : false,
300 );
301 expect(messageId).toBeNull();
302 expect(state.approve).toHaveBeenCalledWith({
303 environmentId: "secondary",
304 input: {
305 threadId: "thread",
306 requestId: "approval",
307 decision: "decline",
308 feedback: "Keep my draft",
309 },
310 });
311 expect(state.enqueue).not.toHaveBeenCalled();
312 expect(state.clearDraft).toHaveBeenCalledOnce();
313 });
314
315 it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
316 state.grantedEnvironments.add("secondary");
317 const composer = useThreadComposerState(NO_SIDE_CHATS);
318 const beforeDispatch = async () => {
319 state.draft = { ...state.draft, text: "New feedback" };
320 return "responded" as const;
321 };
322 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
323 expect(state.enqueue).not.toHaveBeenCalled();
324 expect(state.clearDraft).not.toHaveBeenCalled();
325 expect(state.draft.text).toBe("New feedback");
326 });
327
328 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
329 const composer = useThreadComposerState(NO_SIDE_CHATS);
330 expect(await composer.onSendMessage()).toBeNull();
331 expect(state.enqueue).not.toHaveBeenCalled();
332 expect(state.clearDraft).not.toHaveBeenCalled();
333 composer.onChangeDraftMessage("Edited locally");
334 expect(state.draft.text).toBe("Edited locally");
335 });
336
337 it("keeps an armed fresh session for the message after an approval redirect", async () => {
338 state.grantedEnvironments.add("secondary");
339 state.freshPending = true;
340 const composer = useThreadComposerState(NO_SIDE_CHATS);
341 expect(await composer.onSendMessage(undefined, async () => true)).toBe("message");
342 expect(state.enqueue).toHaveBeenLastCalledWith(
343 expect.not.objectContaining({ freshContext: true }),
344 );
345 expect(state.setFreshPending).not.toHaveBeenCalled();
346 expect(await composer.onSendMessage()).toBe("message");
347 expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
348 expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false);
349 });
350
351 it("compacts a stale thread before sending unless kept or a fresh session is armed", async () => {
352 state.grantedEnvironments.add("secondary");
353 state.projection = {
354 thread: {
355 ...state.thread,
356 activeProviderThreadId: null,
357 lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
358 },
359 runs: [],
360 attempts: [],
361 nodes: [],
362 subagents: [],
363 providerSessions: [],
364 providerThreads: [],
365 providerTurns: [],
366 runtimeRequests: [],
367 messages: [],
368 plans: [],
369 turnItems: [],
370 checkpointScopes: [],
371 checkpoints: [],
372 contextHandoffs: [],
373 contextTransfers: [],
374 visibleTurnItems: [],
375 updatedAt: DateTime.makeUnsafe(0),
376 } as unknown as OrchestrationV2ThreadProjection;
377 state.compactModel = "gpt-5.4";
378 // The notice's minute clock (the epoch here) trails a deadline the send's exact time has passed.
379 state.compactDueAt = "2026-01-01T00:00:00.000Z";
380 const unannounced = useThreadComposerState(NO_SIDE_CHATS);
381 expect(unannounced.compactBeforeSend).toBeNull();
382 await unannounced.onSendMessage();
383 expect(state.enqueue).toHaveBeenLastCalledWith(
384 expect.not.objectContaining({ compactBeforeSend: true }),
385 );
386 state.compactDueAt = "";
387 const composer = useThreadComposerState(NO_SIDE_CHATS);
388 expect(composer.compactBeforeSend?.tokens).toBe(248_000);
389 await composer.onSendMessage();
390 expect(state.enqueue).toHaveBeenLastCalledWith(
391 expect.objectContaining({ compactBeforeSend: true }),
392 );
393 // A model picked after the last render still decides the send.
394 state.draft = {
395 ...state.draft,
396 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.5" },
397 };
398 await composer.onSendMessage();
399 expect(state.enqueue).toHaveBeenLastCalledWith(
400 expect.not.objectContaining({ compactBeforeSend: true }),
401 );
402 state.draft = { ...state.draft, modelSelection: undefined };
403 composer.compactBeforeSend?.toggleKeepFullHistory();
404 const kept = useThreadComposerState(NO_SIDE_CHATS);
405 expect(kept.compactBeforeSend?.keepFullHistory).toBe(true);
406 kept.compactBeforeSend?.toggleKeepFullHistory();
407 const compactAgain = useThreadComposerState(NO_SIDE_CHATS);
408 expect(compactAgain.compactBeforeSend?.keepFullHistory).toBe(false);
409 await compactAgain.onSendMessage();
410 expect(state.enqueue).toHaveBeenLastCalledWith(
411 expect.objectContaining({ compactBeforeSend: true }),
412 );
413 compactAgain.compactBeforeSend?.toggleKeepFullHistory();
414 await useThreadComposerState(NO_SIDE_CHATS).onSendMessage();
415 expect(state.enqueue).toHaveBeenLastCalledWith(
416 expect.not.objectContaining({ compactBeforeSend: true }),
417 );
418 // Keeping covers one send, as on web.
419 expect(useThreadComposerState(NO_SIDE_CHATS).compactBeforeSend?.keepFullHistory).toBe(false);
420 state.freshPending = true;
421 await composer.onSendMessage();
422 expect(state.enqueue).toHaveBeenLastCalledWith(
423 expect.not.objectContaining({ compactBeforeSend: true }),
424 );
425 expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
426 });
427
428 it("sends a typed /clear with an approval redirect as that reply's text", async () => {
429 state.grantedEnvironments.add("secondary");
430 state.serverConfig = {
431 ...state.serverConfig,
432 environment: { capabilities: { freshContext: true } },
433 } as ServerConfig;
434 state.thread.latestRun = { runId: "run" };
435 state.draft = { ...state.draft, text: "/clear" };
436 const composer = useThreadComposerState(NO_SIDE_CHATS);
437 const beforeDispatch = vi.fn(async () => "responded" as const);
438 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
439 expect(beforeDispatch).toHaveBeenCalledWith("/clear", false);
440 expect(state.setFreshPending).not.toHaveBeenCalled();
441 });
442
443 it("starts a side chat for /side instead of sending to the thread", async () => {
444 state.grantedEnvironments.add("secondary");
445 state.serverConfig = {
446 ...state.serverConfig,
447 environment: { capabilities: { sideChats: true } },
448 } as ServerConfig;
449 // The thread gets the composer's mode and model only on its next send.
450 const selection: ModelSelection = {
451 instanceId: ProviderInstanceId.make("codex"),
452 model: "gpt-5.4",
453 options: [{ id: "reasoningEffort", value: "xhigh" }],
454 };
455 state.draft = {
456 ...state.draft,
457 text: "/side why does this fail?",
458 modelSelection: selection,
459 runtimeMode: "approval-required",
460 };
461 const startSideChat = vi.fn(async () => true);
462 const composer = useThreadComposerState({ startSideChat });
463 expect(composer.sideChatUnavailableReason).toBeNull();
464 expect(await composer.onSendMessage()).toBeNull();
465 expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
466 { environmentId: "secondary", threadId: "thread" },
467 { text: "why does this fail?", attachments: [], titleSeed: "why does this fail?" },
468 { runtimeMode: "approval-required", modelSelection: selection },
469 );
470 expect(state.enqueue).not.toHaveBeenCalled();
471 expect(state.clearDraft).toHaveBeenCalled();
472
473 // Attachments and context go to the side chat, bound to their uploaded ids.
474 vi.clearAllMocks();
475 const imageRecord = {
476 version: 1,
477 kind: "image",
478 contextId: "image-shot",
479 label: "shot.png",
480 attachmentId: "shot",
481 name: "shot.png",
482 mimeType: "image/png",
483 sizeBytes: 1,
484 } as OrchestrationMessageContext["records"][number];
485 state.draft = {
486 ...state.draft,
487 text: "/side what is this?",
488 attachments: [
489 { id: "shot", type: "image", name: "shot.png" } as DraftComposerImageAttachment,
490 ],
491 context: { version: 1, records: [imageRecord] },
492 };
493 expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
494 expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
495 { environmentId: "secondary", threadId: "thread" },
496 expect.objectContaining({
497 text: "what is this?",
498 attachments: [expect.objectContaining({ id: "uploaded-shot" })],
499 context: { version: 1, records: [{ ...imageRecord, attachmentId: "uploaded-shot" }] },
500 }),
501 expect.anything(),
502 );
503 expect(state.clearDraft).toHaveBeenCalled();
504 state.draft = { ...state.draft, context: undefined };
505
506 // A failed start restores the draft: text first, since the merge caps attachments, then
507 // the uncapped attachments. The local file stays on disk meanwhile, and no send runs from
508 // the half-restored draft.
509 vi.clearAllMocks();
510 let heldDuringStart: string[] = [];
511 startSideChat.mockImplementationOnce(async () => {
512 heldDuringStart = [...state.fileHolds];
513 return false;
514 });
515 const shot = { id: "shot", fileUri: "file:///shot.png" } as DraftComposerImageAttachment;
516 const sent = { ...state.draft, attachments: [shot] };
517 state.draft = sent;
518 const restoring = useThreadComposerState({ startSideChat });
519 const restoreOrder: string[] = [];
520 state.mergeDraft.mockImplementationOnce(async (_key, content) => {
521 state.draft = { ...sent, text: "new text" };
522 await restoring.onSendMessage();
523 restoreOrder.push(`merge ${content.text}`);
524 });
525 state.appendAttachments.mockImplementationOnce((_key, attachments, options) =>
526 restoreOrder.push(`append ${attachments.length} restore=${options.restore}`),
527 );
528 expect(await restoring.onSendMessage()).toBeNull();
529 expect(restoreOrder).toEqual(["merge /side what is this?", "append 1 restore=true"]);
530 expect(state.enqueue).not.toHaveBeenCalled();
531 expect(heldDuringStart).toEqual(["file:///shot.png"]);
532 expect(state.fileHolds).toEqual([]);
533 // A model the send would refuse does not start a side chat either.
534 vi.clearAllMocks();
535 state.serverConfig = {
536 ...state.serverConfig,
537 providers: [{ instanceId: "codex", driver: "codex", enabled: false }],
538 } as unknown as ServerConfig;
539 state.draft = { ...state.draft, attachments: [] };
540 expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
541 expect(startSideChat).not.toHaveBeenCalled();
542 expect(Alert.alert).toHaveBeenCalledOnce();
543 });
544
545 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
546 state.grantedEnvironments.add("secondary");
547 const composer = useThreadComposerState(NO_SIDE_CHATS);
548 state.grantedEnvironments.delete("secondary");
549 expect(await composer.onSendMessage()).toBeNull();
550 expect(state.clearDraft).not.toHaveBeenCalled();
551 expect(state.enqueue).not.toHaveBeenCalled();
552 state.grantedEnvironments.add("secondary");
553 expect(await composer.onSendMessage()).toBe("message");
554 expect(state.enqueue).toHaveBeenCalledWith(
555 expect.objectContaining({
556 environmentId: "secondary",
557 threadId: "thread",
558 text: "Keep my draft",
559 }),
560 );
561 });
562
563 it("rechecks the target environment before an approval response", async () => {
564 state.grantedEnvironments.add("secondary");
565 const requests = useSelectedThreadRequests();
566 state.grantedEnvironments.delete("secondary");
567 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
568 expect(state.approve).not.toHaveBeenCalled();
569 state.grantedEnvironments.add("secondary");
570 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
571 expect(state.approve).toHaveBeenCalledWith({
572 environmentId: "secondary",
573 input: { threadId: "thread", requestId: "approval", decision: "accept" },
574 });
575 });
576
577 it("keeps answer drafts editable after revocation while blocking their submission", async () => {
578 state.pendingRequests = {
579 approvals: [],
580 userInputs: [
581 {
582 requestId: RuntimeRequestId.make("input"),
583 createdAt: "2026-09-05T00:00:00.000Z",
584 responseCapability: "live",
585 dismissible: false,
586 questions: [state.question],
587 },
588 ],
589 };
590 const requestId = RuntimeRequestId.make("input");
591 useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript");
592 state.grantedEnvironments.add("secondary");
593 const requests = useSelectedThreadRequests();
594 expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" });
595 state.grantedEnvironments.delete("secondary");
596 await requests.onSubmitUserInput();
597 expect(state.answer).not.toHaveBeenCalled();
598 expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({
599 language: "TypeScript",
600 });
601 state.grantedEnvironments.add("secondary");
602 await requests.onSubmitUserInput();
603 expect(state.answer).toHaveBeenCalledWith({
604 environmentId: "secondary",
605 input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } },
606 });
607 });
608});
609
610it.each(["cancelled", "expired"] as const)(
611 "returns unsent attachments to the thread composer when a question is %s",
612 (status) => {
613 const environmentId = EnvironmentId.make("secondary");
614 const threadId = ThreadId.make("thread");
615 const notes = {
616 id: "notes",
617 type: "file",
618 name: "notes.txt",
619 mimeType: "text/plain",
620 sizeBytes: 5,
621 } as unknown as DraftComposerImageAttachment;
622 state.questionDrafts = {
623 [questionAttachmentDraftKey(environmentId, threadId, "input", "language")]: {
624 text: "",
625 attachments: [notes],
626 },
627 };
628 makeThreadRequestsResolvedAnnouncer(
629 environmentId,
630 threadId,
631 )([{ id: RuntimeRequestId.make("input"), status }]);
632 expect(state.appendAttachments).toHaveBeenCalledWith(
633 "secondary:thread",
634 [notes],
635 expect.objectContaining({ appendReference: true }),
636 );
637 },
638);
639
640describe("mobile handoff preview and submission", () => {
641 it("follows project enablement and provider availability for the selected destination", async () => {
642 state.grantedEnvironments.add("secondary");
643 const instanceId = ProviderInstanceId.make("antigravity");
644 const projectId = ProjectId.make(state.thread.projectId);
645 const selection = { instanceId, model: "gemini" };
646 const provider = {
647 instanceId,
648 driver: ProviderDriverKind.make("antigravity"),
649 enabled: false,
650 installed: true,
651 auth: { status: "authenticated" as const },
652 availability: "available" as "available" | "unavailable",
653 models: [{ slug: selection.model }],
654 slashCommands: [],
655 };
656 const projectOverride = { enabled: false };
657 state.serverConfig = {
658 ...state.serverConfig,
659 providers: [provider],
660 settings: {
661 ...DEFAULT_SERVER_SETTINGS,
662 providerInstances: { [instanceId]: { driver: provider.driver, enabled: false } },
663 projectSettingsOverrides: {
664 [projectId]: { providerInstances: { [instanceId]: projectOverride } },
665 },
666 },
667 } as unknown as ServerConfig;
668 state.draft.modelSelection = selection;
669 const source = v2Projection.thread.modelSelection;
670 state.projection = {
671 ...v2Projection,
672 runs: [
673 {
674 id: RunId.make("source-run"),
675 threadId: v2Projection.thread.id,
676 ordinal: 1,
677 providerInstanceId: source.instanceId,
678 modelSelection: source,
679 providerThreadId: null,
680 userMessageId: MessageId.make("source-message"),
681 rootNodeId: null,
682 activeAttemptId: null,
683 status: "completed",
684 requestedAt: v2Now,
685 startedAt: v2Now,
686 completedAt: v2Now,
687 checkpointId: null,
688 contextHandoffId: null,
689 },
690 ],
691 visibleTurnItems: [
692 {
693 position: 0,
694 visibility: "local",
695 sourceThreadId: v2Projection.thread.id,
696 sourceItemId: TurnItemId.make("reply"),
697 item: {
698 id: TurnItemId.make("reply"),
699 threadId: v2Projection.thread.id,
700 runId: RunId.make("source-run"),
701 nodeId: null,
702 providerThreadId: null,
703 providerTurnId: null,
704 nativeItemRef: null,
705 parentItemId: null,
706 ordinal: 1,
707 type: "assistant_message",
708 messageId: MessageId.make("reply"),
709 status: "completed",
710 title: null,
711 text: "Task started",
712 streaming: false,
713 startedAt: v2Now,
714 completedAt: v2Now,
715 updatedAt: v2Now,
716 },
717 },
718 ],
719 };
720
721 const disabled = useThreadComposerState(NO_SIDE_CHATS);
722 expect(disabled.pendingHandoff).toBeNull();
723 expect(await disabled.onSendMessage()).toBeNull();
724 expect(state.enqueue).not.toHaveBeenCalled();
725 expect(state.clearDraft).not.toHaveBeenCalled();
726
727 projectOverride.enabled = true;
728 expect(useThreadComposerState(NO_SIDE_CHATS).pendingHandoff).toEqual({
729 from: [source],
730 to: selection,
731 });
732
733 provider.availability = "unavailable";
734 const unavailable = useThreadComposerState(NO_SIDE_CHATS);
735 expect(unavailable.pendingHandoff).toBeNull();
736 expect(await unavailable.onSendMessage()).toBeNull();
737 expect(state.enqueue).not.toHaveBeenCalled();
738 expect(state.clearDraft).not.toHaveBeenCalled();
739
740 provider.availability = "available";
741 const available = useThreadComposerState(NO_SIDE_CHATS);
742 expect(available.pendingHandoff).toEqual({ from: [source], to: selection });
743 expect(await available.onSendMessage()).toBe("message");
744 expect(state.enqueue).toHaveBeenCalledExactlyOnceWith(
745 expect.objectContaining({
746 modelSelection: selection,
747 text: "Keep my draft",
748 }),
749 );
750 expect(state.clearDraft).toHaveBeenCalledTimes(1);
751 });
752});