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

use-thread-outbox-drain.permissions.test.ts

318 lines11.7 KB

1import {
2 AuthOrchestrationOperateScope,
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import { AsyncResult, type Atom } from "effect/reactivity";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13import type { QueuedThreadMessage } from "./thread-outbox-model";
14​
15const state = vi.hoisted(() => ({
16 grantedEnvironments: new Set<string>(),
17 draftText: "Keep this draft separate",
18 cleanups: [] as Array<() => void>,
19 start: vi.fn(),
20 metadata: vi.fn(),
21 runtime: vi.fn(),
22 interaction: vi.fn(),
23 prepare: vi.fn(),
24 manager: null as unknown as ReturnType<
25 typeof import("./thread-outbox-manager").createThreadOutboxManager
26 >,
27 thread: {
28 environmentId: "secondary",
29 id: "thread",
30 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
31 runtimeMode: "full-access",
32 interactionMode: "default",
33 session: null,
34 },
35 config: {
36 providers: [{ instanceId: "codex", driver: "codex" }],
37 environment: { capabilities: {} },
38 },
39}));
40vi.mock("react", () => ({
41 useCallback: <A>(callback: A) => callback,
42 useEffect: (effect: () => void | (() => void)) => {
43 const cleanup = effect();
44 if (cleanup) state.cleanups.push(cleanup);
45 },
46 useRef: <A>(value: A) => ({ current: value }),
47 useState: <A>(initial: A) => [initial, vi.fn()],
48}));
49vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
50vi.mock("@effect/atom-react", async () => {
51 const { appAtomRegistry } = await import("./atom-registry");
52 return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
53});
54vi.mock("./session", () => ({
55 readEnvironmentScope: (environmentId: string, scope: string) =>
56 scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
57 useEnvironmentsWithScope: () => state.grantedEnvironments,
58}));
59vi.mock("./entities", () => ({
60 useProjects: () => [],
61 useThreadShells: () => [state.thread],
62 useServerConfigs: () => new Map([["secondary", state.config]]),
63}));
64vi.mock("./server", async () => {
65 const { Atom } = await import("effect/reactivity");
66 return {
67 serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) },
68 };
69});
70vi.mock("./threads", async () => {
71 const { Atom } = await import("effect/reactivity");
72 return {
73 threadEnvironment: {
74 startTurn: state.start,
75 updateMetadata: state.metadata,
76 setRuntimeMode: state.runtime,
77 setInteractionMode: state.interaction,
78 },
79 environmentThreadShells: { threadShellsAtom: Atom.make([state.thread]) },
80 };
81});
82vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
83vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false }));
84vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
85vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
86vi.mock("./use-remote-environment-registry", () => ({
87 setPendingConnectionError: vi.fn(),
88 useRemoteConnectionStatus: () => ({
89 connectedEnvironments: [{ environmentId: "secondary", connectionState: "connected" }],
90 }),
91}));
92vi.mock("./thread-outbox", async () => {
93 const { createThreadOutboxManager } = await import("./thread-outbox-manager");
94 const { appAtomRegistry } = await import("./atom-registry");
95 state.manager = createThreadOutboxManager({
96 registry: appAtomRegistry,
97 storage: {
98 load: async () => ({ messages: [], errors: [] }),
99 write: async () => {},
100 remove: async () => {},
101 },
102 });
103 return {
104 threadOutboxManager: state.manager,
105 threadOutboxRevision: (id: MessageId) => state.manager.revisionOf(id),
106 confirmThreadOutboxMessageQueued: (message: QueuedThreadMessage) =>
107 state.manager.confirmQueued(message),
108 updateThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
109 state.manager.update(message, revision),
110 };
111});
112vi.mock("./thread-outbox-removal", () => ({
113 removeThreadOutboxMessage: (message: QueuedThreadMessage, revision?: number) =>
114 state.manager.remove(message, revision),
115}));
116vi.mock("./use-thread-outbox", async () => {
117 const { Atom } = await import("effect/reactivity");
118 const { appAtomRegistry } = await import("./atom-registry");
119 await import("./thread-outbox");
120 return {
121 editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
122 dispatchingQueuedMessageIdAtom: Atom.make<MessageId | null>(null).pipe(Atom.keepAlive),
123 useThreadOutboxMessages: () => appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom),
124 useThreadOutboxShellStatuses: () => new Map([["secondary", "live"]]),
125 };
126});
127vi.mock("./use-composer-drafts", async () => {
128 const { Atom } = await import("effect/reactivity");
129 return {
130 composerDraftsAtom: Atom.make({}),
131 removeDeliveredCloudQueuedMessage: async () => {},
132 appendComposerDraftAttachments: vi.fn(),
133 flushComposerDrafts: vi.fn(),
134 getComposerDraftSnapshot: vi.fn(() => ({ text: state.draftText, attachments: [] })),
135 mergeComposerDraftContent: vi.fn(async (_key: string, input: { text: string }) => {
136 state.draftText += `\n${input.text}`;
137 }),
138 replaceComposerDraftAttachments: vi.fn(),
139 undoComposerDraftMerge: vi.fn(),
140 updateComposerDraftSettings: vi.fn(),
141 waitForComposerDraftsLoaded: vi.fn(),
142 };
143});
144​
145import { appAtomRegistry } from "./atom-registry";
146import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox";
147import { useThreadOutboxDrain } from "./use-thread-outbox-drain";
148​
149const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({
150 environmentId: EnvironmentId.make("secondary"),
151 threadId: ThreadId.make("thread"),
152 commandId: CommandId.make("command"),
153 messageId: MessageId.make("message"),
154 text: "Keep this queued",
155 attachments: [],
156 createdAt: "2026-09-05T00:00:00.000Z",
157 ...overrides,
158});
159const remaining = () =>
160 Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat();
161​
162function runDrain() {
163 const settled = Promise.withResolvers<void>();
164 const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
165 if (id === null) settled.resolve();
166 });
167 useThreadOutboxDrain();
168 return settled.promise.finally(release);
170​
171beforeEach(() => {
172 state.grantedEnvironments = new Set(["primary"]);
173 state.draftText = "Keep this draft separate";
174 appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {});
175 appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null);
176 for (const command of [state.start, state.metadata, state.runtime, state.interaction]) {
177 command.mockReset().mockResolvedValue(AsyncResult.success(undefined));
178 }
179 state.prepare.mockReset().mockImplementation(async ({ attachments }) => ({
180 status: "ready",
181 attachments: [],
182 draftAttachments: attachments,
183 pendingAttachmentIds: [],
184 }));
185});
186afterEach(() => {
187 state.cleanups.splice(0).forEach((cleanup) => cleanup());
188});
189​
190describe("queued task operation access", () => {
191 it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
192 const queued = message();
193 await state.manager.enqueue(queued);
194 useThreadOutboxDrain();
195 expect(state.start).not.toHaveBeenCalled();
196 expect(state.prepare).not.toHaveBeenCalled();
197 expect(remaining()).toEqual([queued]);
198 state.grantedEnvironments.add("secondary");
199 await runDrain();
200 expect(state.start).toHaveBeenCalledOnce();
201 expect(remaining()).toEqual([]);
202 });
203​
204 it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
205 state.grantedEnvironments.add("secondary");
206 const queued = message({
207 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
208 runtimeMode: "approval-required",
209 interactionMode: "plan",
210 });
211 await state.manager.enqueue(queued);
212 state.runtime.mockImplementationOnce(async () => {
213 state.grantedEnvironments.delete("secondary");
214 return AsyncResult.success(undefined);
215 });
216 await runDrain();
217 expect(state.runtime).toHaveBeenCalledOnce();
218 expect(state.interaction).not.toHaveBeenCalled();
219 expect(state.prepare).not.toHaveBeenCalled();
220 expect(state.start).not.toHaveBeenCalled();
221 expect(remaining()).toEqual([queued]);
222 });
223​
224 it.each([
225 { isCreation: false, accepted: false },
226 { isCreation: true, accepted: false },
227 { isCreation: false, accepted: true },
228 { isCreation: true, accepted: true },
229 ])(
230 "preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
231 async ({ isCreation, accepted }) => {
232 state.grantedEnvironments.add("secondary");
233 const queued = message(
234 isCreation
235 ? {
236 threadId: ThreadId.make("new-thread"),
237 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
238 creation: {
239 projectId: ProjectId.make("project"),
240 projectCwd: "/repo",
241 workspaceMode: "local",
242 branch: null,
243 worktreePath: null,
244 },
245 }
246 : {},
247 );
248 await state.manager.enqueue(queued);
249 const started = Promise.withResolvers<void>();
250 const delivery = Promise.withResolvers<AsyncResult.AsyncResult<void, Error>>();
251 state.start.mockImplementationOnce(() => {
252 started.resolve();
253 return delivery.promise;
254 });
255 const drained = runDrain();
256 await started.promise;
257 state.grantedEnvironments.delete("secondary");
258 delivery.resolve(
259 accepted
260 ? AsyncResult.success(undefined)
261 : AsyncResult.failure(Cause.fail(new Error("This connection cannot control this task."))),
262 );
263 await drained;
264​
265 expect(remaining()).toEqual(accepted ? [] : [queued]);
266 expect(state.draftText).toBe("Keep this draft separate");
267 if (!accepted) {
268 state.grantedEnvironments.add("secondary");
269 await runDrain();
270 expect(state.start).toHaveBeenCalledTimes(2);
271 expect(remaining()).toEqual([]);
272 expect(state.draftText).toBe("Keep this draft separate");
273 }
274 },
275 );
276​
277 it.each([
278 { isCreation: false, uploadFails: false },
279 { isCreation: true, uploadFails: false },
280 { isCreation: false, uploadFails: true },
281 { isCreation: true, uploadFails: true },
282 ])(
283 "keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
284 async ({ isCreation, uploadFails }) => {
285 state.grantedEnvironments.add("secondary");
286 const queued = message(
287 isCreation
288 ? {
289 threadId: ThreadId.make("new-thread"),
290 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
291 creation: {
292 projectId: ProjectId.make("project"),
293 projectCwd: "/repo",
294 workspaceMode: "local",
295 branch: null,
296 worktreePath: null,
297 },
298 }
299 : {},
300 );
301 await state.manager.enqueue(queued);
302 state.prepare.mockImplementationOnce(async ({ attachments }) => {
303 state.grantedEnvironments.delete("secondary");
304 if (uploadFails) throw new Error("This connection cannot upload attachments.");
305 return {
306 status: "ready",
307 attachments: [],
308 draftAttachments: attachments,
309 pendingAttachmentIds: [],
310 };
311 });
312 await runDrain();
313 expect(state.prepare).toHaveBeenCalledOnce();
314 expect(state.start).not.toHaveBeenCalled();
315 expect(remaining()).toEqual([queued]);
316 },
317 );
318});