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

thread-task-permissions.test.ts

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