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