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

thread-task-permissions.test.ts

430 lines15.7 KB

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 sequenceAtom: () => Atom.make(0),
117 pendingRequestsAtom: () => Atom.make(state.pendingRequests),
118 },
119 threadEnvironment: {
120 respondToApproval: state.approve,
121 respondToUserInput: state.answer,
122 uploadFeedback: state.feedback,
123 },
124 };
125});
126vi.mock("./use-thread-outbox", async () => {
127 const { Atom } = await import("effect/reactivity");
128 return { dispatchingQueuedMessageIdAtom: Atom.make(null), useThreadOutboxMessages: () => ({}) };
129});
130vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue }));
131vi.mock("./composer-attachment-uploads", async () => {
132 const { Atom } = await import("effect/reactivity");
133 return {
134 composerAttachmentUploadsAtom: Atom.make({}),
135 composerAttachmentUploadBlockReason: () => null,
136 composerAttachmentsStillUploading: () => false,
137 };
138});
139vi.mock("./use-composer-drafts", async () => {
140 const { Atom } = await import("effect/reactivity");
141 return {
142 composerDraftsAtom: Atom.make({}),
143 composerContextImportsAtom: Atom.make({}),
144 getComposerDraftSnapshot: () => state.draft,
145 clearComposerDraftContent: state.clearDraft,
146 clearComposerDraft: state.clearDraft,
147 setComposerDraftText: (_key: string, text: string) => {
148 state.draft.text = text;
149 },
150 updateComposerDraftSettings: state.updateSettings,
151 ensureComposerDraftsLoaded: () => {},
152 scheduleUnusedComposerAttachmentCleanup: () => {},
153 appendComposerDraftAttachments: vi.fn(),
154 appendComposerDraftText: vi.fn(),
155 mergeComposerDraftContent: vi.fn(),
156 removeComposerDraftAttachment: vi.fn(),
157 useComposerDraft: () => state.draft,
158 useComposerDraftSettings: () => state.draft,
159 questionAttachmentDraftsAtom: () => Atom.make({}),
160 };
161});
162vi.mock("../lib/composerImages", () => ({
163 convertPastedImagesToAttachments: vi.fn(),
164 pickComposerFiles: vi.fn(),
165 pickComposerMedia: vi.fn(),
166}));
167vi.mock("../lib/commandMetadata", () => ({
168 makeQueuedMessageMetadata: () => ({
169 messageId: "message",
170 commandId: "command",
171 createdAt: "2026-09-05T00:00:00.000Z",
172 }),
173}));
174vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
175vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
176​
177import { useThreadComposerState } from "./use-thread-composer-state";
178import { useSelectedThreadRequests } from "./use-selected-thread-requests";
179​
180beforeEach(() => {
181 state.grantedEnvironments = new Set(["primary"]);
182 state.connectionState = "connected";
183 state.draft = { text: "Keep my draft", attachments: [], modelSelection: undefined };
184 state.projection = null;
185 state.serverConfig = {
186 providers: [{ instanceId: "codex", driver: "codex", enabled: true }],
187 environment: { capabilities: {} },
188 } as unknown as ServerConfig;
189 state.pendingRequests = {
190 approvals: [
191 {
192 requestId: RuntimeRequestId.make("approval"),
193 requestKind: "command",
194 createdAt: "2026-09-05T00:00:00.000Z",
195 responseCapability: "live",
196 },
197 ],
198 userInputs: [],
199 };
200 vi.clearAllMocks();
201 state.approve.mockResolvedValue(AsyncResult.success(undefined));
202 state.answer.mockResolvedValue(AsyncResult.success(undefined));
203 state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" }));
204});
205​
206describe("mobile task permissions", () => {
207 it("consumes an approval reply without queueing a parent message", async () => {
208 state.grantedEnvironments.add("secondary");
209 const composer = useThreadComposerState();
210 const requests = useSelectedThreadRequests();
211 const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
212 const messageId = await composer.onSendMessage(undefined, async (text) =>
213 (await sendApprovalFeedback(approval, text, requests.onRespondToApproval))
214 ? "responded"
215 : false,
216 );
217 expect(messageId).toBeNull();
218 expect(state.approve).toHaveBeenCalledWith({
219 environmentId: "secondary",
220 input: {
221 threadId: "thread",
222 requestId: "approval",
223 decision: "decline",
224 feedback: "Keep my draft",
225 },
226 });
227 expect(state.enqueue).not.toHaveBeenCalled();
228 expect(state.clearDraft).toHaveBeenCalledOnce();
229 });
230​
231 it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
232 state.grantedEnvironments.add("secondary");
233 const composer = useThreadComposerState();
234 const beforeDispatch = async () => {
235 state.draft = { ...state.draft, text: "New feedback" };
236 return "responded" as const;
237 };
238 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
239 expect(state.enqueue).not.toHaveBeenCalled();
240 expect(state.clearDraft).not.toHaveBeenCalled();
241 expect(state.draft.text).toBe("New feedback");
242 });
243​
244 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
245 const composer = useThreadComposerState();
246 expect(await composer.onSendMessage()).toBeNull();
247 expect(state.enqueue).not.toHaveBeenCalled();
248 expect(state.clearDraft).not.toHaveBeenCalled();
249 composer.onChangeDraftMessage("Edited locally");
250 composer.onUpdateInteractionMode("plan");
251 expect(state.draft.text).toBe("Edited locally");
252 expect(state.updateSettings).toHaveBeenCalledWith("secondary:thread", {
253 interactionMode: "plan",
254 });
255 });
256​
257 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
258 state.grantedEnvironments.add("secondary");
259 const composer = useThreadComposerState();
260 state.grantedEnvironments.delete("secondary");
261 expect(await composer.onSendMessage()).toBeNull();
262 expect(state.clearDraft).not.toHaveBeenCalled();
263 expect(state.enqueue).not.toHaveBeenCalled();
264 state.grantedEnvironments.add("secondary");
265 expect(await composer.onSendMessage()).toBe("message");
266 expect(state.enqueue).toHaveBeenCalledWith(
267 expect.objectContaining({
268 environmentId: "secondary",
269 threadId: "thread",
270 text: "Keep my draft",
271 }),
272 );
273 });
274​
275 it("rechecks the target environment before an approval response", async () => {
276 state.grantedEnvironments.add("secondary");
277 const requests = useSelectedThreadRequests();
278 state.grantedEnvironments.delete("secondary");
279 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
280 expect(state.approve).not.toHaveBeenCalled();
281 state.grantedEnvironments.add("secondary");
282 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
283 expect(state.approve).toHaveBeenCalledWith({
284 environmentId: "secondary",
285 input: { threadId: "thread", requestId: "approval", decision: "accept" },
286 });
287 });
288​
289 it("keeps answer drafts editable after revocation while blocking their submission", async () => {
290 state.pendingRequests = {
291 approvals: [],
292 userInputs: [
293 {
294 requestId: RuntimeRequestId.make("input"),
295 createdAt: "2026-09-05T00:00:00.000Z",
296 responseCapability: "live",
297 dismissible: false,
298 questions: [state.question],
299 },
300 ],
301 };
302 const requestId = RuntimeRequestId.make("input");
303 useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript");
304 state.grantedEnvironments.add("secondary");
305 const requests = useSelectedThreadRequests();
306 expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" });
307 state.grantedEnvironments.delete("secondary");
308 await requests.onSubmitUserInput();
309 expect(state.answer).not.toHaveBeenCalled();
310 expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({
311 language: "TypeScript",
312 });
313 state.grantedEnvironments.add("secondary");
314 await requests.onSubmitUserInput();
315 expect(state.answer).toHaveBeenCalledWith({
316 environmentId: "secondary",
317 input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } },
318 });
319 });
320});
321​
322describe("mobile handoff preview and submission", () => {
323 it("follows project enablement and provider availability for the selected destination", async () => {
324 state.grantedEnvironments.add("secondary");
325 const instanceId = ProviderInstanceId.make("antigravity");
326 const projectId = ProjectId.make(state.thread.projectId);
327 const selection = { instanceId, model: "gemini" };
328 const provider = {
329 instanceId,
330 driver: ProviderDriverKind.make("antigravity"),
331 enabled: false,
332 installed: true,
333 auth: { status: "authenticated" as const },
334 availability: "available" as "available" | "unavailable",
335 models: [{ slug: selection.model }],
336 };
337 const projectOverride = { enabled: false };
338 state.serverConfig = {
339 ...state.serverConfig,
340 providers: [provider],
341 settings: {
342 ...DEFAULT_SERVER_SETTINGS,
343 providerInstances: { [instanceId]: { driver: provider.driver, enabled: false } },
344 projectSettingsOverrides: {
345 [projectId]: { providerInstances: { [instanceId]: projectOverride } },
346 },
347 },
348 } as unknown as ServerConfig;
349 state.draft.modelSelection = selection;
350 const source = v2Projection.thread.modelSelection;
351 state.projection = {
352 ...v2Projection,
353 runs: [
354 {
355 id: RunId.make("source-run"),
356 threadId: v2Projection.thread.id,
357 ordinal: 1,
358 providerInstanceId: source.instanceId,
359 modelSelection: source,
360 providerThreadId: null,
361 userMessageId: MessageId.make("source-message"),
362 rootNodeId: null,
363 activeAttemptId: null,
364 status: "completed",
365 requestedAt: v2Now,
366 startedAt: v2Now,
367 completedAt: v2Now,
368 checkpointId: null,
369 contextHandoffId: null,
370 },
371 ],
372 visibleTurnItems: [
373 {
374 position: 0,
375 visibility: "local",
376 sourceThreadId: v2Projection.thread.id,
377 sourceItemId: TurnItemId.make("reply"),
378 item: {
379 id: TurnItemId.make("reply"),
380 threadId: v2Projection.thread.id,
381 runId: RunId.make("source-run"),
382 nodeId: null,
383 providerThreadId: null,
384 providerTurnId: null,
385 nativeItemRef: null,
386 parentItemId: null,
387 ordinal: 1,
388 type: "assistant_message",
389 messageId: MessageId.make("reply"),
390 status: "completed",
391 title: null,
392 text: "Task started",
393 streaming: false,
394 startedAt: v2Now,
395 completedAt: v2Now,
396 updatedAt: v2Now,
397 },
398 },
399 ],
400 };
401​
402 const disabled = useThreadComposerState();
403 expect(disabled.pendingHandoff).toBeNull();
404 expect(await disabled.onSendMessage()).toBeNull();
405 expect(state.enqueue).not.toHaveBeenCalled();
406 expect(state.clearDraft).not.toHaveBeenCalled();
407​
408 projectOverride.enabled = true;
409 expect(useThreadComposerState().pendingHandoff).toEqual({ from: [source], to: selection });
410​
411 provider.availability = "unavailable";
412 const unavailable = useThreadComposerState();
413 expect(unavailable.pendingHandoff).toBeNull();
414 expect(await unavailable.onSendMessage()).toBeNull();
415 expect(state.enqueue).not.toHaveBeenCalled();
416 expect(state.clearDraft).not.toHaveBeenCalled();
417​
418 provider.availability = "available";
419 const available = useThreadComposerState();
420 expect(available.pendingHandoff).toEqual({ from: [source], to: selection });
421 expect(await available.onSendMessage()).toBe("message");
422 expect(state.enqueue).toHaveBeenCalledExactlyOnceWith(
423 expect.objectContaining({
424 modelSelection: selection,
425 text: "Keep my draft",
426 }),
427 );
428 expect(state.clearDraft).toHaveBeenCalledTimes(1);
429 });
430});