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

thread-task-permissions.test.ts

552 lines20.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 { DateTime } from "effect";
23import { AsyncResult, type Atom } from "effect/reactivity";
24import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
25​
26const state = vi.hoisted(() => ({
27 grantedEnvironments: new Set<string>(),
28 connectionState: "connected",
29 draft: {
30 text: "Keep my draft",
31 attachments: [] as DraftComposerImageAttachment[],
32 modelSelection: undefined as ModelSelection | undefined,
33 },
34 serverConfig: null as ServerConfig | null,
35 projection: null as OrchestrationV2ThreadProjection | null,
36 pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
37 enqueue: vi.fn(async () => undefined),
38 freshPending: false,
39 compactDue: false,
40 setFreshPending: vi.fn(),
41 clearDraft: vi.fn(),
42 approve: vi.fn(),
43 answer: vi.fn(),
44 feedback: vi.fn(),
45 updateSettings: vi.fn(),
46 question: {
47 id: "language",
48 header: "Language",
49 question: "Which language?",
50 options: [{ label: "TypeScript", description: "Use the existing code" }],
51 multiSelect: false,
52 },
53 thread: {
54 id: "thread",
55 environmentId: "secondary",
56 lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
57 projectId: "project",
58 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
59 runtimeMode: "full-access",
60 interactionMode: "default",
61 runtime: null,
62 latestRun: null as unknown,
63 },
64}));
65​
66vi.mock("react", () => ({
67 useCallback: <A>(callback: A) => callback,
68 useEffect: () => {},
69 useLayoutEffect: () => {},
70 useRef: <A>(current: A) => ({ current }),
71 useMemo: <A>(factory: () => A) => factory(),
72 useState: <A>(initial: A | (() => A)) => [
73 typeof initial === "function" ? (initial as () => A)() : initial,
74 vi.fn(),
75 ],
76}));
77vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
78vi.mock("@t3tools/client-runtime/state/context-window", async (importOriginal) => ({
79 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/context-window")>()),
80 shouldCompactBeforeSend: () => state.compactDue,
81}));
82vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
83vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
84vi.mock("./queued-run-edit", () => ({
85 useQueuedRunEdit: () => null,
86 getQueuedRunEdit: () => null,
87}));
88vi.mock("./preferences", async () => {
89 const { Atom, AsyncResult } = await import("effect/reactivity");
90 return { mobilePreferencesAtom: Atom.make(AsyncResult.success({})) };
91});
92vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
93vi.mock("@effect/atom-react", async () => {
94 const { appAtomRegistry } = await import("./atom-registry");
95 return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
96});
97vi.mock("./entities", () => ({ useServerConfigs: () => new Map() }));
98vi.mock("./session", () => ({
99 readEnvironmentScope: (environmentId: string, scope: string) =>
100 scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
101}));
102vi.mock("./use-thread-selection", () => ({
103 useThreadSelection: () => ({
104 selectedThread: state.thread,
105 selectedThreadCreation: null,
106 selectedEnvironmentRuntime: {
107 connectionState: state.connectionState,
108 serverConfig: state.serverConfig,
109 },
110 }),
111}));
112vi.mock("./use-thread-detail", () => ({
113 useSelectedThreadProjection: () =>
114 state.projection === null ? null : { projection: state.projection },
115 useSelectedThreadVisibleTurnItems: () => [],
116 useSelectedThreadPendingRequests: () => state.pendingRequests,
117}));
118vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
119vi.mock("./threads", async () => {
120 const { Atom } = await import("effect/reactivity");
121 return {
122 environmentThreadDetails: {
123 queueWorkflowAtom: () => Atom.make(null),
124 checkpointSummariesAtom: () => Atom.make([]),
125 sequenceAtom: () => Atom.make(0),
126 pendingRequestsAtom: () => Atom.make(state.pendingRequests),
127 },
128 threadEnvironment: {
129 respondToApproval: state.approve,
130 respondToUserInput: state.answer,
131 uploadFeedback: state.feedback,
132 },
133 };
134});
135vi.mock("./use-thread-outbox", async () => {
136 const { Atom } = await import("effect/reactivity");
137 return { dispatchingQueuedMessageIdAtom: Atom.make(null), useThreadOutboxMessages: () => ({}) };
138});
139vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue }));
140vi.mock("./composer-attachment-uploads", async () => {
141 const { Atom } = await import("effect/reactivity");
142 return {
143 composerAttachmentUploadsAtom: Atom.make({}),
144 composerAttachmentUploadBlockReason: () => null,
145 composerAttachmentsStillUploading: () => false,
146 };
147});
148vi.mock("./use-composer-drafts", async () => {
149 const { Atom } = await import("effect/reactivity");
150 return {
151 composerDraftsAtom: Atom.make({}),
152 composerContextImportsAtom: Atom.make({}),
153 getComposerDraftSnapshot: () => state.draft,
154 isFreshSessionPending: () => state.freshPending,
155 setFreshSessionPending: state.setFreshPending,
156 clearComposerDraftContent: state.clearDraft,
157 clearComposerDraft: state.clearDraft,
158 setComposerDraftText: (_key: string, text: string) => {
159 state.draft.text = text;
160 },
161 updateComposerDraftSettings: state.updateSettings,
162 ensureComposerDraftsLoaded: () => {},
163 scheduleUnusedComposerAttachmentCleanup: () => {},
164 appendComposerDraftAttachments: vi.fn(),
165 appendComposerDraftText: vi.fn(),
166 mergeComposerDraftContent: vi.fn(),
167 removeComposerDraftAttachment: vi.fn(),
168 useComposerDraft: () => state.draft,
169 useComposerDraftSettings: () => state.draft,
170 questionAttachmentDraftsAtom: () => Atom.make({}),
171 };
172});
173vi.mock("../lib/composerImages", () => ({
174 convertPastedImagesToAttachments: vi.fn(),
175 pickComposerFiles: vi.fn(),
176 pickComposerMedia: vi.fn(),
177}));
178vi.mock("../lib/commandMetadata", () => ({
179 makeQueuedMessageMetadata: () => ({
180 messageId: "message",
181 commandId: "command",
182 createdAt: "2026-09-05T00:00:00.000Z",
183 }),
184}));
185vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
186vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
187​
188import { useThreadComposerState } from "./use-thread-composer-state";
189import { useSelectedThreadRequests } from "./use-selected-thread-requests";
190​
191const NO_SIDE_CHATS = { startSideChat: async () => false };
192​
193beforeEach(() => {
194 state.grantedEnvironments = new Set(["primary"]);
195 state.connectionState = "connected";
196 state.draft = { text: "Keep my draft", attachments: [], modelSelection: undefined };
197 state.freshPending = false;
198 state.compactDue = false;
199 state.thread.latestRun = null;
200 state.projection = null;
201 state.serverConfig = {
202 providers: [{ instanceId: "codex", driver: "codex", enabled: true }],
203 environment: { capabilities: {} },
204 } as unknown as ServerConfig;
205 state.pendingRequests = {
206 approvals: [
207 {
208 requestId: RuntimeRequestId.make("approval"),
209 requestKind: "command",
210 createdAt: "2026-09-05T00:00:00.000Z",
211 responseCapability: "live",
212 },
213 ],
214 userInputs: [],
215 };
216 vi.clearAllMocks();
217 state.approve.mockResolvedValue(AsyncResult.success(undefined));
218 state.answer.mockResolvedValue(AsyncResult.success(undefined));
219 state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" }));
220});
221​
222describe("mobile task permissions", () => {
223 it("consumes an approval reply without queueing a parent message", async () => {
224 state.grantedEnvironments.add("secondary");
225 const composer = useThreadComposerState(NO_SIDE_CHATS);
226 const requests = useSelectedThreadRequests();
227 const approval = { ...state.pendingRequests.approvals[0]!, supportsFeedback: true };
228 const messageId = await composer.onSendMessage(undefined, async (text) =>
229 (await sendApprovalFeedback(approval, text, requests.onRespondToApproval))
230 ? "responded"
231 : false,
232 );
233 expect(messageId).toBeNull();
234 expect(state.approve).toHaveBeenCalledWith({
235 environmentId: "secondary",
236 input: {
237 threadId: "thread",
238 requestId: "approval",
239 decision: "decline",
240 feedback: "Keep my draft",
241 },
242 });
243 expect(state.enqueue).not.toHaveBeenCalled();
244 expect(state.clearDraft).toHaveBeenCalledOnce();
245 });
246​
247 it("preserves a draft changed during an approval reply and never sends it to the parent", async () => {
248 state.grantedEnvironments.add("secondary");
249 const composer = useThreadComposerState(NO_SIDE_CHATS);
250 const beforeDispatch = async () => {
251 state.draft = { ...state.draft, text: "New feedback" };
252 return "responded" as const;
253 };
254 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
255 expect(state.enqueue).not.toHaveBeenCalled();
256 expect(state.clearDraft).not.toHaveBeenCalled();
257 expect(state.draft.text).toBe("New feedback");
258 });
259​
260 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
261 const composer = useThreadComposerState(NO_SIDE_CHATS);
262 expect(await composer.onSendMessage()).toBeNull();
263 expect(state.enqueue).not.toHaveBeenCalled();
264 expect(state.clearDraft).not.toHaveBeenCalled();
265 composer.onChangeDraftMessage("Edited locally");
266 composer.onUpdateInteractionMode("plan");
267 expect(state.draft.text).toBe("Edited locally");
268 expect(state.updateSettings).toHaveBeenCalledWith("secondary:thread", {
269 interactionMode: "plan",
270 });
271 });
272​
273 it("keeps an armed fresh session for the message after an approval redirect", async () => {
274 state.grantedEnvironments.add("secondary");
275 state.freshPending = true;
276 const composer = useThreadComposerState(NO_SIDE_CHATS);
277 expect(await composer.onSendMessage(undefined, async () => true)).toBe("message");
278 expect(state.enqueue).toHaveBeenLastCalledWith(
279 expect.not.objectContaining({ freshContext: true }),
280 );
281 expect(state.setFreshPending).not.toHaveBeenCalled();
282 expect(await composer.onSendMessage()).toBe("message");
283 expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
284 expect(state.setFreshPending).toHaveBeenCalledWith("secondary:thread", false);
285 });
286​
287 it("compacts a stale thread before sending unless a fresh session is armed", async () => {
288 state.grantedEnvironments.add("secondary");
289 state.projection = {
290 thread: {
291 ...state.thread,
292 activeProviderThreadId: null,
293 lineage: { rootThreadId: "thread", parentThreadId: null, relationshipToParent: null },
294 },
295 runs: [],
296 attempts: [],
297 nodes: [],
298 subagents: [],
299 providerSessions: [],
300 providerThreads: [],
301 providerTurns: [],
302 runtimeRequests: [],
303 messages: [],
304 plans: [],
305 turnItems: [],
306 checkpointScopes: [],
307 checkpoints: [],
308 contextHandoffs: [],
309 contextTransfers: [],
310 visibleTurnItems: [],
311 updatedAt: DateTime.makeUnsafe(0),
312 } as unknown as OrchestrationV2ThreadProjection;
313 state.compactDue = true;
314 const composer = useThreadComposerState(NO_SIDE_CHATS);
315 await composer.onSendMessage();
316 expect(state.enqueue).toHaveBeenLastCalledWith(
317 expect.objectContaining({ compactBeforeSend: true }),
318 );
319 state.freshPending = true;
320 await composer.onSendMessage();
321 expect(state.enqueue).toHaveBeenLastCalledWith(
322 expect.not.objectContaining({ compactBeforeSend: true }),
323 );
324 expect(state.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ freshContext: true }));
325 });
326​
327 it("sends a typed /clear with an approval redirect as that reply's text", async () => {
328 state.grantedEnvironments.add("secondary");
329 state.serverConfig = {
330 ...state.serverConfig,
331 environment: { capabilities: { freshContext: true } },
332 } as ServerConfig;
333 state.thread.latestRun = { runId: "run" };
334 state.draft = { ...state.draft, text: "/clear" };
335 const composer = useThreadComposerState(NO_SIDE_CHATS);
336 const beforeDispatch = vi.fn(async () => "responded" as const);
337 expect(await composer.onSendMessage(undefined, beforeDispatch)).toBeNull();
338 expect(beforeDispatch).toHaveBeenCalledWith("/clear", false);
339 expect(state.setFreshPending).not.toHaveBeenCalled();
340 });
341​
342 it("starts a side chat for /side instead of sending to the thread", async () => {
343 state.grantedEnvironments.add("secondary");
344 state.serverConfig = {
345 ...state.serverConfig,
346 environment: { capabilities: { sideChats: true } },
347 } as ServerConfig;
348 state.draft = { ...state.draft, text: "/side why does this fail?" };
349 const startSideChat = vi.fn(async () => true);
350 const composer = useThreadComposerState({ startSideChat });
351 expect(composer.sideChatUnavailableReason).toBeNull();
352 expect(await composer.onSendMessage()).toBeNull();
353 expect(startSideChat).toHaveBeenCalledExactlyOnceWith(
354 { environmentId: "secondary", threadId: "thread" },
355 "why does this fail?",
356 );
357 expect(state.enqueue).not.toHaveBeenCalled();
358 expect(state.clearDraft).toHaveBeenCalled();
359​
360 // An attachment added while the side chat starts stays in the draft.
361 vi.clearAllMocks();
362 startSideChat.mockImplementationOnce(async () => {
363 state.draft = {
364 ...state.draft,
365 attachments: [{ id: "added" } as DraftComposerImageAttachment],
366 };
367 return true;
368 });
369 state.draft = { ...state.draft, text: "/side again?", attachments: [] };
370 expect(await useThreadComposerState({ startSideChat }).onSendMessage()).toBeNull();
371 expect(startSideChat).toHaveBeenCalledOnce();
372 expect(state.clearDraft).not.toHaveBeenCalled();
373 });
374​
375 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
376 state.grantedEnvironments.add("secondary");
377 const composer = useThreadComposerState(NO_SIDE_CHATS);
378 state.grantedEnvironments.delete("secondary");
379 expect(await composer.onSendMessage()).toBeNull();
380 expect(state.clearDraft).not.toHaveBeenCalled();
381 expect(state.enqueue).not.toHaveBeenCalled();
382 state.grantedEnvironments.add("secondary");
383 expect(await composer.onSendMessage()).toBe("message");
384 expect(state.enqueue).toHaveBeenCalledWith(
385 expect.objectContaining({
386 environmentId: "secondary",
387 threadId: "thread",
388 text: "Keep my draft",
389 }),
390 );
391 });
392​
393 it("rechecks the target environment before an approval response", async () => {
394 state.grantedEnvironments.add("secondary");
395 const requests = useSelectedThreadRequests();
396 state.grantedEnvironments.delete("secondary");
397 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
398 expect(state.approve).not.toHaveBeenCalled();
399 state.grantedEnvironments.add("secondary");
400 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
401 expect(state.approve).toHaveBeenCalledWith({
402 environmentId: "secondary",
403 input: { threadId: "thread", requestId: "approval", decision: "accept" },
404 });
405 });
406​
407 it("keeps answer drafts editable after revocation while blocking their submission", async () => {
408 state.pendingRequests = {
409 approvals: [],
410 userInputs: [
411 {
412 requestId: RuntimeRequestId.make("input"),
413 createdAt: "2026-09-05T00:00:00.000Z",
414 responseCapability: "live",
415 dismissible: false,
416 questions: [state.question],
417 },
418 ],
419 };
420 const requestId = RuntimeRequestId.make("input");
421 useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript");
422 state.grantedEnvironments.add("secondary");
423 const requests = useSelectedThreadRequests();
424 expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" });
425 state.grantedEnvironments.delete("secondary");
426 await requests.onSubmitUserInput();
427 expect(state.answer).not.toHaveBeenCalled();
428 expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({
429 language: "TypeScript",
430 });
431 state.grantedEnvironments.add("secondary");
432 await requests.onSubmitUserInput();
433 expect(state.answer).toHaveBeenCalledWith({
434 environmentId: "secondary",
435 input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } },
436 });
437 });
438});
439​
440describe("mobile handoff preview and submission", () => {
441 it("follows project enablement and provider availability for the selected destination", async () => {
442 state.grantedEnvironments.add("secondary");
443 const instanceId = ProviderInstanceId.make("antigravity");
444 const projectId = ProjectId.make(state.thread.projectId);
445 const selection = { instanceId, model: "gemini" };
446 const provider = {
447 instanceId,
448 driver: ProviderDriverKind.make("antigravity"),
449 enabled: false,
450 installed: true,
451 auth: { status: "authenticated" as const },
452 availability: "available" as "available" | "unavailable",
453 models: [{ slug: selection.model }],
454 slashCommands: [],
455 };
456 const projectOverride = { enabled: false };
457 state.serverConfig = {
458 ...state.serverConfig,
459 providers: [provider],
460 settings: {
461 ...DEFAULT_SERVER_SETTINGS,
462 providerInstances: { [instanceId]: { driver: provider.driver, enabled: false } },
463 projectSettingsOverrides: {
464 [projectId]: { providerInstances: { [instanceId]: projectOverride } },
465 },
466 },
467 } as unknown as ServerConfig;
468 state.draft.modelSelection = selection;
469 const source = v2Projection.thread.modelSelection;
470 state.projection = {
471 ...v2Projection,
472 runs: [
473 {
474 id: RunId.make("source-run"),
475 threadId: v2Projection.thread.id,
476 ordinal: 1,
477 providerInstanceId: source.instanceId,
478 modelSelection: source,
479 providerThreadId: null,
480 userMessageId: MessageId.make("source-message"),
481 rootNodeId: null,
482 activeAttemptId: null,
483 status: "completed",
484 requestedAt: v2Now,
485 startedAt: v2Now,
486 completedAt: v2Now,
487 checkpointId: null,
488 contextHandoffId: null,
489 },
490 ],
491 visibleTurnItems: [
492 {
493 position: 0,
494 visibility: "local",
495 sourceThreadId: v2Projection.thread.id,
496 sourceItemId: TurnItemId.make("reply"),
497 item: {
498 id: TurnItemId.make("reply"),
499 threadId: v2Projection.thread.id,
500 runId: RunId.make("source-run"),
501 nodeId: null,
502 providerThreadId: null,
503 providerTurnId: null,
504 nativeItemRef: null,
505 parentItemId: null,
506 ordinal: 1,
507 type: "assistant_message",
508 messageId: MessageId.make("reply"),
509 status: "completed",
510 title: null,
511 text: "Task started",
512 streaming: false,
513 startedAt: v2Now,
514 completedAt: v2Now,
515 updatedAt: v2Now,
516 },
517 },
518 ],
519 };
520​
521 const disabled = useThreadComposerState(NO_SIDE_CHATS);
522 expect(disabled.pendingHandoff).toBeNull();
523 expect(await disabled.onSendMessage()).toBeNull();
524 expect(state.enqueue).not.toHaveBeenCalled();
525 expect(state.clearDraft).not.toHaveBeenCalled();
526​
527 projectOverride.enabled = true;
528 expect(useThreadComposerState(NO_SIDE_CHATS).pendingHandoff).toEqual({
529 from: [source],
530 to: selection,
531 });
532​
533 provider.availability = "unavailable";
534 const unavailable = useThreadComposerState(NO_SIDE_CHATS);
535 expect(unavailable.pendingHandoff).toBeNull();
536 expect(await unavailable.onSendMessage()).toBeNull();
537 expect(state.enqueue).not.toHaveBeenCalled();
538 expect(state.clearDraft).not.toHaveBeenCalled();
539​
540 provider.availability = "available";
541 const available = useThreadComposerState(NO_SIDE_CHATS);
542 expect(available.pendingHandoff).toEqual({ from: [source], to: selection });
543 expect(await available.onSendMessage()).toBe("message");
544 expect(state.enqueue).toHaveBeenCalledExactlyOnceWith(
545 expect.objectContaining({
546 modelSelection: selection,
547 text: "Keep my draft",
548 }),
549 );
550 expect(state.clearDraft).toHaveBeenCalledTimes(1);
551 });
552});