Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

thread-task-permissions.test.ts

817 lines31.1 KB

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