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

thread-task-permissions.test.ts

262 lines10.2 KB

1import { AuthOrchestrationOperateScope, RuntimeRequestId } from "@t3tools/contracts";
2import type { DraftComposerImageAttachment } from "../lib/composerImages";
3import type { PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
4import { AsyncResult, type Atom } from "effect/reactivity";
5import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
6​
7const state = vi.hoisted(() => ({
8 grantedEnvironments: new Set<string>(),
9 connectionState: "connected",
10 draft: { text: "Keep my draft", attachments: [] as DraftComposerImageAttachment[] },
11 pendingRequests: { approvals: [], userInputs: [] } as PendingThreadRequests,
12 enqueue: vi.fn(async () => undefined),
13 clearDraft: vi.fn(),
14 approve: vi.fn(),
15 answer: vi.fn(),
16 feedback: vi.fn(),
17 updateSettings: vi.fn(),
18 question: {
19 id: "language",
20 header: "Language",
21 question: "Which language?",
22 options: [{ label: "TypeScript", description: "Use the existing code" }],
23 multiSelect: false,
24 },
25 thread: {
26 id: "thread",
27 environmentId: "secondary",
28 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
29 runtimeMode: "full-access",
30 interactionMode: "default",
31 runtime: null,
32 latestRun: null,
33 },
34}));
35​
36vi.mock("react", () => ({
37 useCallback: <A>(callback: A) => callback,
38 useEffect: () => {},
39 useRef: <A>(current: A) => ({ current }),
40 useMemo: <A>(factory: () => A) => factory(),
41 useState: <A>(initial: A | (() => A)) => [
42 typeof initial === "function" ? (initial as () => A)() : initial,
43 vi.fn(),
44 ],
45}));
46vi.mock("expo-crypto", () => ({ randomUUID: () => "uuid" }));
47vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: vi.fn() }));
48vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid" }));
49vi.mock("./queued-run-edit", () => ({
50 useQueuedRunEdit: () => null,
51 getQueuedRunEdit: () => null,
52}));
53vi.mock("./preferences", async () => {
54 const { Atom, AsyncResult } = await import("effect/reactivity");
55 return { mobilePreferencesAtom: Atom.make(AsyncResult.success({})) };
56});
57vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
58vi.mock("@effect/atom-react", async () => {
59 const { appAtomRegistry } = await import("./atom-registry");
60 return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
61});
62vi.mock("./entities", () => ({ useServerConfigs: () => new Map() }));
63vi.mock("./session", () => ({
64 readEnvironmentScope: (environmentId: string, scope: string) =>
65 scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
66}));
67vi.mock("./use-thread-selection", () => ({
68 useThreadSelection: () => ({
69 selectedThread: state.thread,
70 selectedThreadCreation: null,
71 selectedEnvironmentRuntime: {
72 connectionState: state.connectionState,
73 serverConfig: {
74 providers: [{ instanceId: "codex", driver: "codex" }],
75 environment: { capabilities: {} },
76 },
77 },
78 }),
79}));
80vi.mock("./use-thread-detail", () => ({
81 useSelectedThreadProjection: () => null,
82 useSelectedThreadVisibleTurnItems: () => [],
83 useSelectedThreadPendingRequests: () => state.pendingRequests,
84}));
85vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
86vi.mock("./threads", async () => {
87 const { Atom } = await import("effect/reactivity");
88 return {
89 environmentThreadDetails: { queueWorkflowAtom: () => Atom.make(null) },
90 threadEnvironment: {
91 respondToApproval: state.approve,
92 respondToUserInput: state.answer,
93 uploadFeedback: state.feedback,
94 },
95 };
96});
97vi.mock("./use-thread-outbox", async () => {
98 const { Atom } = await import("effect/reactivity");
99 return { dispatchingQueuedMessageIdAtom: Atom.make(null), useThreadOutboxMessages: () => ({}) };
100});
101vi.mock("./thread-outbox", () => ({ enqueueThreadOutboxMessage: state.enqueue }));
102vi.mock("./composer-attachment-uploads", async () => {
103 const { Atom } = await import("effect/reactivity");
104 return {
105 composerAttachmentUploadsAtom: Atom.make({}),
106 composerAttachmentUploadBlockReason: () => null,
107 composerAttachmentsStillUploading: () => false,
108 };
109});
110vi.mock("./use-composer-drafts", async () => {
111 const { Atom } = await import("effect/reactivity");
112 return {
113 composerDraftsAtom: Atom.make({}),
114 composerContextImportsAtom: Atom.make({}),
115 getComposerDraftSnapshot: () => state.draft,
116 clearComposerDraftContent: state.clearDraft,
117 clearComposerDraft: state.clearDraft,
118 setComposerDraftText: (_key: string, text: string) => {
119 state.draft.text = text;
120 },
121 updateComposerDraftSettings: state.updateSettings,
122 ensureComposerDraftsLoaded: () => {},
123 scheduleUnusedComposerAttachmentCleanup: () => {},
124 appendComposerDraftAttachments: vi.fn(),
125 appendComposerDraftText: vi.fn(),
126 mergeComposerDraftContent: vi.fn(),
127 removeComposerDraftAttachment: vi.fn(),
128 useComposerDraft: () => state.draft,
129 useComposerDraftSettings: () => ({}),
130 questionAttachmentDraftsAtom: () => Atom.make({}),
131 };
132});
133vi.mock("../lib/composerImages", () => ({
134 convertPastedImagesToAttachments: vi.fn(),
135 pasteComposerClipboard: vi.fn(),
136 pickComposerFiles: vi.fn(),
137 pickComposerMedia: vi.fn(),
138}));
139vi.mock("../lib/commandMetadata", () => ({
140 makeQueuedMessageMetadata: () => ({
141 messageId: "message",
142 commandId: "command",
143 createdAt: "2026-09-05T00:00:00.000Z",
144 }),
145}));
146vi.mock("../lib/copyTextWithHaptic", () => ({ copyTextWithHaptic: vi.fn() }));
147vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false }));
148vi.mock("./use-remote-environment-registry", () => ({ setPendingConnectionError: vi.fn() }));
149​
150import { useThreadComposerState } from "./use-thread-composer-state";
151import { useSelectedThreadRequests } from "./use-selected-thread-requests";
152​
153beforeEach(() => {
154 state.grantedEnvironments = new Set(["primary"]);
155 state.connectionState = "connected";
156 state.draft = { text: "Keep my draft", attachments: [] };
157 state.pendingRequests = {
158 approvals: [
159 {
160 requestId: RuntimeRequestId.make("approval"),
161 requestKind: "command",
162 createdAt: "2026-09-05T00:00:00.000Z",
163 responseCapability: "live",
164 },
165 ],
166 userInputs: [],
167 };
168 vi.clearAllMocks();
169 state.approve.mockResolvedValue(AsyncResult.success(undefined));
170 state.answer.mockResolvedValue(AsyncResult.success(undefined));
171 state.feedback.mockResolvedValue(AsyncResult.success({ feedbackId: "feedback" }));
172});
173​
174describe("mobile task permissions", () => {
175 it("keeps a connected read-only task's draft instead of queueing it with another environment's grant", async () => {
176 const composer = useThreadComposerState();
177 expect(await composer.onSendMessage()).toBeNull();
178 expect(state.enqueue).not.toHaveBeenCalled();
179 expect(state.clearDraft).not.toHaveBeenCalled();
180 composer.onChangeDraftMessage("Edited locally");
181 composer.onUpdateInteractionMode("plan");
182 expect(state.draft.text).toBe("Edited locally");
183 expect(state.updateSettings).toHaveBeenCalledWith("secondary:thread", {
184 interactionMode: "plan",
185 });
186 });
187​
188 it("rechecks a retained send callback before clearing or queueing the draft", async () => {
189 state.grantedEnvironments.add("secondary");
190 const composer = useThreadComposerState();
191 state.grantedEnvironments.delete("secondary");
192 expect(await composer.onSendMessage()).toBeNull();
193 expect(state.clearDraft).not.toHaveBeenCalled();
194 expect(state.enqueue).not.toHaveBeenCalled();
195 state.grantedEnvironments.add("secondary");
196 expect(await composer.onSendMessage()).toBe("message");
197 expect(state.enqueue).toHaveBeenCalledWith(
198 expect.objectContaining({
199 environmentId: "secondary",
200 threadId: "thread",
201 text: "Keep my draft",
202 }),
203 );
204 });
205​
206 it("preserves offline queueing without dispatching feedback through the queue action", async () => {
207 state.connectionState = "disconnected";
208 expect(await useThreadComposerState().onSendMessage()).toBe("message");
209 expect(state.enqueue).toHaveBeenCalledTimes(1);
210 state.draft.text = "/feedback The agent stopped early.";
211 expect(await useThreadComposerState().onSendMessage()).toBeNull();
212 expect(state.feedback).not.toHaveBeenCalled();
213 expect(state.enqueue).toHaveBeenCalledTimes(1);
214 expect(state.clearDraft).toHaveBeenCalledTimes(1);
215 });
216​
217 it("rechecks the target environment before an approval response", async () => {
218 state.grantedEnvironments.add("secondary");
219 const requests = useSelectedThreadRequests();
220 state.grantedEnvironments.delete("secondary");
221 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
222 expect(state.approve).not.toHaveBeenCalled();
223 state.grantedEnvironments.add("secondary");
224 await requests.onRespondToApproval(RuntimeRequestId.make("approval"), "accept");
225 expect(state.approve).toHaveBeenCalledWith({
226 environmentId: "secondary",
227 input: { threadId: "thread", requestId: "approval", decision: "accept" },
228 });
229 });
230​
231 it("keeps answer drafts editable after revocation while blocking their submission", async () => {
232 state.pendingRequests = {
233 approvals: [],
234 userInputs: [
235 {
236 requestId: RuntimeRequestId.make("input"),
237 createdAt: "2026-09-05T00:00:00.000Z",
238 responseCapability: "live",
239 dismissible: false,
240 questions: [state.question],
241 },
242 ],
243 };
244 const requestId = RuntimeRequestId.make("input");
245 useSelectedThreadRequests().onSelectUserInputOption(requestId, state.question, "TypeScript");
246 state.grantedEnvironments.add("secondary");
247 const requests = useSelectedThreadRequests();
248 expect(requests.activePendingUserInputAnswers).toEqual({ language: "TypeScript" });
249 state.grantedEnvironments.delete("secondary");
250 await requests.onSubmitUserInput();
251 expect(state.answer).not.toHaveBeenCalled();
252 expect(useSelectedThreadRequests().activePendingUserInputAnswers).toEqual({
253 language: "TypeScript",
254 });
255 state.grantedEnvironments.add("secondary");
256 await requests.onSubmitUserInput();
257 expect(state.answer).toHaveBeenCalledWith({
258 environmentId: "secondary",
259 input: { threadId: "thread", requestId: "input", answers: { language: "TypeScript" } },
260 });
261 });
262});