Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 DEFAULT_SERVER_SETTINGS,
4 MessageId,
5 ProjectId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 RunId,
9 RuntimeRequestId,
10 TurnItemId,
11 type ModelSelection,
12 type OrchestrationV2ThreadProjection,
13 type ServerConfig,
14} from "@t3tools/contracts";
15import {
16 v2Now,
17 v2Projection,
18} from "../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
19import type { DraftComposerImageAttachment } from "../lib/composerImages";
20import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
21import { sendApprovalFeedback } from "@t3tools/client-runtime/state/thread-requests";
22import { AsyncResult, type Atom } from "effect/reactivity";
23import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
24
25const state = vi.hoisted(() => ({
26 grantedEnvironments: new Set<string>(),
27 connectionState: "connected",
28 draft: {
29 text: "Keep my draft",
30 attachments: [] as DraftComposerImageAttachment[],
31 modelSelection: undefined as ModelSelection | undefined,
32 },
33 serverConfig: null as ServerConfig | null,
34 projection: null as OrchestrationV2ThreadProjection | null,
35 pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
36 enqueue: vi.fn(async () => undefined),
37 clearDraft: vi.fn(),
38 approve: vi.fn(),
39 answer: vi.fn(),
40 feedback: vi.fn(),
41 updateSettings: vi.fn(),
42 question: {
43 id: "language",
44 header: "Language",
45 question: "Which language?",
46 options: [{ label: "TypeScript", description: "Use the existing code" }],
47 multiSelect: false,
48 },
49 thread: {
50 id: "thread",
51 environmentId: "secondary",
52 projectId: "project",
53 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 runtime: null,
57 latestRun: null,
58 },
59}));
60
61vi.mock("react", () => ({
62 useCallback: <A>(callback: A) => callback,
63 useEffect: () => {},
64 useLayoutEffect: () => {},
65 useRef: <A>(current: A) => ({ current }),
66 useMemo: <A>(factory: () => A) => factory(),
67 useState: <A>(initial: A | (() => A)) => [
68 typeof initial === "function" ? (initial as () => A)() : initial,
69 vi.fn(),
70 ],
71}));
72vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
73vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
74vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
75vi.mock("./queued-run-edit", () => ({
76 useQueuedRunEdit: () => null,
77 getQueuedRunEdit: () => null,
78}));
79vi.mock("./preferences", async () => {
80 const { Atom, AsyncResult } = await import("effect/reactivity");
81 return { mobilePreferencesAtom: Atom.make(AsyncResult.success({})) };
82});
83vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
84vi.mock("@effect/atom-react", async () => {
85 const { appAtomRegistry } = await import("./atom-registry");
86 return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
87});
88vi.mock("./entities", () => ({ useServerConfigs: () => new Map() }));
89vi.mock("./session", () => ({
90 readEnvironmentScope: (environmentId: string, scope: string) =>
91 scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
92}));
93vi.mock("./use-thread-selection", () => ({
94 useThreadSelection: () => ({
95 selectedThread: state.thread,
96 selectedThreadCreation: null,
97 selectedEnvironmentRuntime: {
98 connectionState: state.connectionState,
99 serverConfig: state.serverConfig,
100 },
101 }),
102}));
103vi.mock("./use-thread-detail", () => ({
104 useSelectedThreadProjection: () =>
105 state.projection === null ? null : { projection: state.projection },
106 useSelectedThreadVisibleTurnItems: () => [],
107 useSelectedThreadPendingRequests: () => state.pendingRequests,
108}));
109vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
110vi.mock("./threads", async () => {
111 const { Atom } = await import("effect/reactivity");
112 return {
113 environmentThreadDetails: {
114 queueWorkflowAtom: () => Atom.make(null),
115 checkpointSummariesAtom: () => Atom.make([]),
116 },
117 threadEnvironment: {
118 respondToApproval: state.approve,
119 respondToUserInput: state.answer,
120 uploadFeedback: state.feedback,
121 },
122 };
123});
124vi.mock("./use-thread-outbox", async () => {
125 const { Atom } = await import("effect/reactivity");
126 return { dispatchingQueuedMessageIdAtom: Atom.make(null), useThreadOutboxMessages: () => ({}) };
127});
128vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue }));
129vi.mock("./composer-attachment-uploads", async () => {
130 const { Atom } = await import("effect/reactivity");
131 return {
132 composerAttachmentUploadsAtom: Atom.make({}),
133 composerAttachmentUploadBlockReason: () => null,
134 composerAttachmentsStillUploading: () => false,
135 };
136});
137vi.mock("./use-composer-drafts", async () => {
138 const { Atom } = await import("effect/reactivity");
139 return {
140 composerDraftsAtom: Atom.make({}),
141 composerContextImportsAtom: Atom.make({}),
142 getComposerDraftSnapshot: () => state.draft,
143 clearComposerDraftContent: state.clearDraft,
144 clearComposerDraft: state.clearDraft,
145 setComposerDraftText: (_key: string, text: string) => {
146 state.draft.text = text;
147 },
148 updateComposerDraftSettings: state.updateSettings,
149 ensureComposerDraftsLoaded: () => {},
150 scheduleUnusedComposerAttachmentCleanup: () => {},
151 appendComposerDraftAttachments: vi.fn(),
152 appendComposerDraftText: vi.fn(),
153 mergeComposerDraftContent: vi.fn(),
154 removeComposerDraftAttachment: vi.fn(),
155 useComposerDraft: () => state.draft,
156 useComposerDraftSettings: () => state.draft,
157 questionAttachmentDraftsAtom: () => Atom.make({}),
158 };
159});
160vi.mock("../lib/composerImages", () => ({
161 convertPastedImagesToAttachments: vi.fn(),
162 pasteComposerClipboard: vi.fn(),
163 pickComposerFiles: vi.fn(),
164 pickComposerMedia: vi.fn(),
165}));
166vi.mock("../lib/commandMetadata", () => ({
167 makeQueuedMessageMetadata: () => ({
168 messageId: "message",
169 commandId: "command",
170 createdAt: "2026-09-05T00:00:00.000Z",
171 }),
172}));
173vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
174vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
175
176import { useThreadComposerState } from "./use-thread-composer-state";
177import { useSelectedThreadRequests } from "./use-selected-thread-requests";
178
179beforeEach(() => {
180 state.grantedEnvironments = new Set(["primary"]);
181 state.connectionState = "connected";
182 state.draft = { text: "Keep my draft", attachments: [], modelSelection: undefined };
183 state.projection = null;
184 state.serverConfig = {
185 providers: [{ instanceId: "codex", driver: "codex", enabled: true }],
186 environment: { capabilities: {} },
187 } as unknown as ServerConfig;
188 state.pendingRequests = {
189 approvals: [
190 {
191 requestId: RuntimeRequestId.make("approval"),
192 requestKind: "command",
193 createdAt: "2026-09-05T00:00:00.000Z",
194 responseCapability: "live",
195 },
196 ],
197 userInputs: [],
198 };
199 vi.clearAllMocks();
200 state.approve.mockResolvedValue(AsyncResult.success(undefined));
201 state.answer.mockResolvedValue(AsyncResult.success(undefined));
202 state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" }));
203});
204
205describe("mobile task permissions", () => {
206 it("consumes an approval reply without queueing a parent message", async () => {
207 state.grantedEnvironments.add("secondary");
208 const composer = useThreadComposerState();
209 const requests = useSelectedThreadRequests();
210 const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
211 const messageId = await composer.onSendMessage(undefined, async (text) =>
212 (await sendApprovalFeedback(approval, text, requests.onRespondToApproval))
213 ? "responded"
214 : false,
215 );
216 expect(messageId).toBeNull();
217 expect(state.approve).toHaveBeenCalledWith({
218 environmentId: "secondary",
219 input: {
220 threadId: "thread",
221 requestId: "approval",
222 decision: "decline",
223 feedback: "Keep my draft",
224 },
225 });
226 expect(state.enqueue).not.toHaveBeenCalled();
227 expect(state.clearDraft).toHaveBeenCalledOnce();
228 });
229
230 it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
231 state.grantedEnvironments.add("secondary");
232 const composer = useThreadComposerState();
233 const beforeDispatch = async () => {
234 state.draft = { ...state.draft, text: "New feedback" };
235 return "responded" as const;
236 };
237 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
238 expect(state.enqueue).not.toHaveBeenCalled();
239 expect(state.clearDraft).not.toHaveBeenCalled();
240 expect(state.draft.text).toBe("New feedback");
241 });
242
243 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
244 const composer = useThreadComposerState();
245 expect(await composer.onSendMessage()).toBeNull();
246 expect(state.enqueue).not.toHaveBeenCalled();
247 expect(state.clearDraft).not.toHaveBeenCalled();
248 composer.onChangeDraftMessage("Edited locally");
249 composer.onUpdateInteractionMode("plan");
250 expect(state.draft.text).toBe("Edited locally");
251 expect(state.updateSettings).toHaveBeenCalledWith("secondary:thread", {
252 interactionMode: "plan",
253 });
254 });
255
256 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
257 state.grantedEnvironments.add("secondary");
258 const composer = useThreadComposerState();
259 state.grantedEnvironments.delete("secondary");
260 expect(await composer.onSendMessage()).toBeNull();
261 expect(state.clearDraft).not.toHaveBeenCalled();
262 expect(state.enqueue).not.toHaveBeenCalled();
263 state.grantedEnvironments.add("secondary");
264 expect(await composer.onSendMessage()).toBe("message");
265 expect(state.enqueue).toHaveBeenCalledWith(
266 expect.objectContaining({
267 environmentId: "secondary",
268 threadId: "thread",
269 text: "Keep my draft",
270 }),
271 );
272 });
273
274 it("rechecks the target environment before an approval response", async () => {
275 state.grantedEnvironments.add("secondary");
276 const requests = useSelectedThreadRequests();
277 state.grantedEnvironments.delete("secondary");
278 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
279 expect(state.approve).not.toHaveBeenCalled();
280 state.grantedEnvironments.add("secondary");
281 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
282 expect(state.approve).toHaveBeenCalledWith({
283 environmentId: "secondary",
284 input: { threadId: "thread", requestId: "approval", decision: "accept" },
285 });
286 });
287
288 it("keeps answer drafts editable after revocation while blocking their submission", async () => {
289 state.pendingRequests = {
290 approvals: [],
291 userInputs: [
292 {
293 requestId: RuntimeRequestId.make("input"),
294 createdAt: "2026-09-05T00:00:00.000Z",
295 responseCapability: "live",
296 dismissible: false,
297 questions: [state.question],
298 },
299 ],
300 };
301 const requestId = RuntimeRequestId.make("input");
302 useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript");
303 state.grantedEnvironments.add("secondary");
304 const requests = useSelectedThreadRequests();
305 expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" });
306 state.grantedEnvironments.delete("secondary");
307 await requests.onSubmitUserInput();
308 expect(state.answer).not.toHaveBeenCalled();
309 expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({
310 language: "TypeScript",
311 });
312 state.grantedEnvironments.add("secondary");
313 await requests.onSubmitUserInput();
314 expect(state.answer).toHaveBeenCalledWith({
315 environmentId: "secondary",
316 input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } },
317 });
318 });
319});
320
321describe("mobile handoff preview and submission", () => {
322 it("follows project enablement and provider availability for the selected destination", async () => {
323 state.grantedEnvironments.add("secondary");
324 const instanceId = ProviderInstanceId.make("antigravity");
325 const projectId = ProjectId.make(state.thread.projectId);
326 const selection = { instanceId, model: "gemini" };
327 const provider = {
328 instanceId,
329 driver: ProviderDriverKind.make("antigravity"),
330 enabled: false,
331 installed: true,
332 auth: { status: "authenticated" as const },
333 availability: "available" as "available" | "unavailable",
334 models: [{ slug: selection.model }],
335 };
336 const projectOverride = { enabled: false };
337 state.serverConfig = {
338 ...state.serverConfig,
339 providers: [provider],
340 settings: {
341 ...DEFAULT_SERVER_SETTINGS,
342 providerInstances: { [instanceId]: { driver: provider.driver, enabled: false } },
343 projectSettingsOverrides: {
344 [projectId]: { providerInstances: { [instanceId]: projectOverride } },
345 },
346 },
347 } as unknown as ServerConfig;
348 state.draft.modelSelection = selection;
349 const source = v2Projection.thread.modelSelection;
350 state.projection = {
351 ...v2Projection,
352 runs: [
353 {
354 id: RunId.make("source-run"),
355 threadId: v2Projection.thread.id,
356 ordinal: 1,
357 providerInstanceId: source.instanceId,
358 modelSelection: source,
359 providerThreadId: null,
360 userMessageId: MessageId.make("source-message"),
361 rootNodeId: null,
362 activeAttemptId: null,
363 status: "completed",
364 requestedAt: v2Now,
365 startedAt: v2Now,
366 completedAt: v2Now,
367 checkpointId: null,
368 contextHandoffId: null,
369 },
370 ],
371 visibleTurnItems: [
372 {
373 position: 0,
374 visibility: "local",
375 sourceThreadId: v2Projection.thread.id,
376 sourceItemId: TurnItemId.make("reply"),
377 item: {
378 id: TurnItemId.make("reply"),
379 threadId: v2Projection.thread.id,
380 runId: RunId.make("source-run"),
381 nodeId: null,
382 providerThreadId: null,
383 providerTurnId: null,
384 nativeItemRef: null,
385 parentItemId: null,
386 ordinal: 1,
387 type: "assistant_message",
388 messageId: MessageId.make("reply"),
389 status: "completed",
390 title: null,
391 text: "Task started",
392 streaming: false,
393 startedAt: v2Now,
394 completedAt: v2Now,
395 updatedAt: v2Now,
396 },
397 },
398 ],
399 };
400
401 const disabled = useThreadComposerState();
402 expect(disabled.pendingHandoff).toBeNull();
403 expect(await disabled.onSendMessage()).toBeNull();
404 expect(state.enqueue).not.toHaveBeenCalled();
405 expect(state.clearDraft).not.toHaveBeenCalled();
406
407 projectOverride.enabled = true;
408 expect(useThreadComposerState().pendingHandoff).toEqual({ from: [source], to: selection });
409
410 provider.availability = "unavailable";
411 const unavailable = useThreadComposerState();
412 expect(unavailable.pendingHandoff).toBeNull();
413 expect(await unavailable.onSendMessage()).toBeNull();
414 expect(state.enqueue).not.toHaveBeenCalled();
415 expect(state.clearDraft).not.toHaveBeenCalled();
416
417 provider.availability = "available";
418 const available = useThreadComposerState();
419 expect(available.pendingHandoff).toEqual({ from: [source], to: selection });
420 expect(await available.onSendMessage()).toBe("message");
421 expect(state.enqueue).toHaveBeenCalledExactlyOnceWith(
422 expect.objectContaining({
423 modelSelection: selection,
424 text: "Keep my draft",
425 }),
426 );
427 expect(state.clearDraft).toHaveBeenCalledTimes(1);
428 });
429});