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

DispatchModeLimit.test.ts

363 lines13.9 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
14import * as Layer from "effect/Layer";
15import * as SqlitePersistence from "../persistence/Sqlite.ts";
16import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
17import { DispatchModeLimit } from "./DispatchModeLimit.ts";
18import * as EventSink from "./EventSink.ts";
19import * as Orchestrator from "./Orchestrator.ts";
20import * as ProjectionStore from "./ProjectionStore.ts";
21import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
22import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
23import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
24​
25const instanceId = ProviderInstanceId.make("codex");
26const adapter = {
27 instanceId,
28 driver: ProviderDriverKind.make("codex"),
29 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
30 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
31 openSession: () => Effect.die("No provider process needed for metadata commands"),
32} as ProviderAdapter.ProviderAdapterV2["Service"];
33const layerDatabase = SqlitePersistence.layerMemory;
34const layerTest = Layer.mergeAll(
35 layerDatabase,
36 ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layerDigest), Layer.provide(layerDatabase)),
37 ProviderReplayHarness.layerWithRegistry(
38 { name: "dispatch-mode-limit" },
39 ProviderAdapterRegistry.layerFromAdapters([adapter]),
40 { databaseLayer: layerDatabase, runEffectWorker: false },
41 ),
42);
43​
44const supervised = { runtimeMode: "approval-required", interactionMode: "default" } as const;
45​
46const createThread = (threadId: ThreadId) =>
47 Effect.gen(function* () {
48 const orchestrator = yield* Orchestrator.OrchestratorV2;
49 yield* orchestrator.dispatch({
50 type: "thread.create",
51 commandId: CommandId.make(`create:${threadId}`),
52 threadId,
53 projectId: ProjectId.make("project:dispatch-mode-limit"),
54 title: "Before",
55 modelSelection: { instanceId, model: "gpt-5" },
56 ...supervised,
57 branch: null,
58 worktreePath: null,
59 createdBy: "user",
60 creationSource: "web",
61 });
62 });
63​
64it.layer(layerTest)("DispatchModeLimit", (it) => {
65 it.effect("refuses a limited command on a thread its user raised, and records nothing", () =>
66 Effect.gen(function* () {
67 const orchestrator = yield* Orchestrator.OrchestratorV2;
68 const projections = yield* ProjectionStore.ProjectionStoreV2;
69 const threadId = ThreadId.make("thread:limit-raised");
70 yield* createThread(threadId);
71 yield* orchestrator.dispatch({
72 type: "thread.runtime-mode.set",
73 commandId: CommandId.make("raise"),
74 threadId,
75 runtimeMode: "full-access",
76 });
77 const rename = {
78 type: "thread.metadata.update",
79 commandId: CommandId.make("rename"),
80 threadId,
81 title: "After",
82 } as const;
83 const refused = yield* orchestrator
84 .dispatch(rename)
85 .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip);
86 assert.equal(refused._tag, "OrchestratorThreadAboveModeLimitError");
87 assert.equal((yield* projections.getThreadShell(threadId))?.title, "Before");
88​
89 yield* orchestrator.dispatch({
90 type: "thread.runtime-mode.set",
91 commandId: CommandId.make("lower"),
92 threadId,
93 runtimeMode: "approval-required",
94 });
95 yield* orchestrator
96 .dispatch(rename)
97 .pipe(Effect.provideService(DispatchModeLimit, supervised));
98 assert.equal((yield* projections.getThreadShell(threadId))?.title, "After");
99 }),
100 );
101​
102 it.effect("refuses to fork a source thread its user raised", () =>
103 Effect.gen(function* () {
104 const orchestrator = yield* Orchestrator.OrchestratorV2;
105 const projections = yield* ProjectionStore.ProjectionStoreV2;
106 const sourceThreadId = ThreadId.make("thread:limit-fork-source");
107 const targetThreadId = ThreadId.make("thread:limit-fork-target");
108 yield* createThread(sourceThreadId);
109 yield* orchestrator.dispatch({
110 type: "thread.runtime-mode.set",
111 commandId: CommandId.make("raise-source"),
112 threadId: sourceThreadId,
113 runtimeMode: "full-access",
114 });
115 const fork = {
116 type: "thread.fork",
117 commandId: CommandId.make("fork"),
118 sourceThreadId,
119 targetThreadId,
120 sourcePoint: { type: "latest_stable" },
121 createdBy: "agent",
122 creationSource: "mcp",
123 } as const;
124 const refused = yield* orchestrator
125 .dispatch(fork)
126 .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip);
127 assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError");
128 assert.equal(refused.threadId, sourceThreadId);
129 assert.isNull(yield* projections.getThreadShell(targetThreadId));
130​
131 yield* orchestrator.dispatch({
132 type: "thread.runtime-mode.set",
133 commandId: CommandId.make("lower-source"),
134 threadId: sourceThreadId,
135 runtimeMode: "approval-required",
136 });
137 const retried = yield* orchestrator
138 .dispatch(fork)
139 .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip);
140 assert.equal(retried._tag, "OrchestratorDispatchError");
141 }),
142 );
143});
144​
145const layerPolicyDatabase = SqlitePersistence.layerMemory;
146const layerWithCeiling = Layer.mergeAll(
147 layerPolicyDatabase,
148 ProjectionStore.layer.pipe(
149 Layer.provide(NodeCrypto.layerDigest),
150 Layer.provide(layerPolicyDatabase),
151 ),
152 ProviderReplayHarness.layerWithRegistry(
153 { name: "runtime-mode-ceiling" },
154 ProviderAdapterRegistry.layerFromAdapters([adapter]),
155 {
156 databaseLayer: layerPolicyDatabase,
157 runEffectWorker: false,
158 managedPolicy: {
159 schemaVersion: 1,
160 organization: "Example Corp",
161 limits: { maxRuntimeMode: "auto-accept-edits" },
162 },
163 },
164 ),
165);
166​
167const sendMessage = (threadId: ThreadId, id: string) => ({
168 type: "message.dispatch" as const,
169 commandId: CommandId.make(`send:${id}`),
170 threadId,
171 messageId: MessageId.make(`message:${id}`),
172 text: id,
173 attachments: [],
174 dispatchMode: { type: "start_immediately" as const },
175 createdBy: "user" as const,
176 creationSource: "web" as const,
177});
178​
179/** A thread that ran in full access before the policy arrived, as an import or an older build leaves it. */
180const raiseBehindPolicy = (threadId: ThreadId) =>
181 Effect.gen(function* () {
182 const orchestrator = yield* Orchestrator.OrchestratorV2;
183 const sink = yield* EventSink.EventSinkV2;
184 yield* createThread(threadId);
185 const { thread } = yield* orchestrator.getThreadRecords(threadId, []);
186 yield* sink.write({
187 events: [
188 {
189 id: EventId.make(`event:raise-behind-policy:${threadId}`),
190 type: "thread.runtime-mode-updated",
191 threadId,
192 occurredAt: yield* DateTime.now,
193 payload: { ...thread, runtimeMode: "full-access" },
194 },
195 ],
196 });
197 });
198​
199it.layer(layerWithCeiling)("runtime mode ceiling", (it) => {
200 it.effect("refuses the user's own thread and mode changes above the ceiling", () =>
201 Effect.gen(function* () {
202 const orchestrator = yield* Orchestrator.OrchestratorV2;
203 const projections = yield* ProjectionStore.ProjectionStoreV2;
204 const threadId = ThreadId.make("thread:ceiling-user");
205 const create = {
206 type: "thread.create",
207 commandId: CommandId.make("create:ceiling-user:full"),
208 threadId,
209 projectId: ProjectId.make("project:dispatch-mode-limit"),
210 title: "Full",
211 modelSelection: { instanceId, model: "gpt-5" },
212 runtimeMode: "full-access",
213 interactionMode: "default",
214 branch: null,
215 worktreePath: null,
216 createdBy: "user",
217 creationSource: "web",
218 } as const;
219 const refusedCreate = yield* orchestrator.dispatch(create).pipe(Effect.flip);
220 assert.ok(refusedCreate._tag === "OrchestratorRuntimeModeAboveCeilingError");
221 assert.equal(refusedCreate.refused, "mode");
222 assert.equal(refusedCreate.message, "Example Corp limits threads to Auto-accept edits.");
223 assert.isNull(yield* projections.getThreadShell(threadId));
224​
225 yield* createThread(threadId);
226 const raise = yield* orchestrator
227 .dispatch({
228 type: "thread.runtime-mode.set",
229 commandId: CommandId.make("raise:ceiling-user"),
230 threadId,
231 runtimeMode: "auto",
232 })
233 .pipe(Effect.flip);
234 assert.equal(raise._tag, "OrchestratorRuntimeModeAboveCeilingError");
235 yield* orchestrator.dispatch({
236 type: "thread.runtime-mode.set",
237 commandId: CommandId.make("raise-to-ceiling:ceiling-user"),
238 threadId,
239 runtimeMode: "auto-accept-edits",
240 });
241 assert.equal((yield* projections.getThreadShell(threadId))?.runtimeMode, "auto-accept-edits");
242 }),
243 );
244​
245 it.effect("narrows an MCP caller's limit to the ceiling inside the lock", () =>
246 Effect.gen(function* () {
247 const orchestrator = yield* Orchestrator.OrchestratorV2;
248 const projections = yield* ProjectionStore.ProjectionStoreV2;
249 const threadId = ThreadId.make("thread:ceiling-mcp");
250 yield* createThread(threadId);
251 const fullAccessCaller = { runtimeMode: "full-access", interactionMode: "default" } as const;
252 const raise = yield* orchestrator
253 .dispatch({
254 type: "thread.runtime-mode.set",
255 commandId: CommandId.make("raise:ceiling-mcp"),
256 threadId,
257 runtimeMode: "full-access",
258 })
259 .pipe(Effect.provideService(DispatchModeLimit, fullAccessCaller), Effect.flip);
260 assert.equal(raise._tag, "OrchestratorRuntimeModeAboveCeilingError");
261​
262 const raisedThreadId = ThreadId.make("thread:ceiling-mcp-raised");
263 yield* raiseBehindPolicy(raisedThreadId);
264 const rename = yield* orchestrator
265 .dispatch({
266 type: "thread.metadata.update",
267 commandId: CommandId.make("rename:ceiling-mcp"),
268 threadId: raisedThreadId,
269 title: "After",
270 })
271 .pipe(Effect.provideService(DispatchModeLimit, fullAccessCaller), Effect.flip);
272 assert.equal(rename._tag, "OrchestratorThreadAboveModeLimitError");
273 assert.equal((yield* projections.getThreadShell(raisedThreadId))?.title, "Before");
274 }),
275 );
276​
277 it.effect("refuses turns on a thread above the ceiling until its mode is lowered", () =>
278 Effect.gen(function* () {
279 const orchestrator = yield* Orchestrator.OrchestratorV2;
280 const projections = yield* ProjectionStore.ProjectionStoreV2;
281 const threadId = ThreadId.make("thread:ceiling-raised");
282 yield* raiseBehindPolicy(threadId);
283​
284 const refused = yield* orchestrator
285 .dispatch(sendMessage(threadId, "first"))
286 .pipe(Effect.flip);
287 assert.ok(refused._tag === "OrchestratorRuntimeModeAboveCeilingError");
288 assert.equal(refused.refused, "turn");
289 assert.equal(
290 refused.message,
291 "Example Corp limits threads to Auto-accept edits. Switch this thread's mode to continue.",
292 );
293 assert.lengthOf((yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs, 0);
294​
295 // The user's own housekeeping and the way back down stay open.
296 yield* orchestrator.dispatch({
297 type: "thread.metadata.update",
298 commandId: CommandId.make("rename:ceiling-raised"),
299 threadId,
300 title: "After",
301 });
302 yield* orchestrator.dispatch({
303 type: "thread.runtime-mode.set",
304 commandId: CommandId.make("lower:ceiling-raised"),
305 threadId,
306 runtimeMode: "approval-required",
307 });
308 // Refusals record no receipt, so the same command goes through once the mode is lowered.
309 yield* orchestrator.dispatch(sendMessage(threadId, "first"));
310 assert.lengthOf((yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs, 1);
311 assert.equal((yield* projections.getThreadShell(threadId))?.title, "After");
312 }),
313 );
314​
315 it.effect("starts a queue that waited above the ceiling once the mode is lowered", () =>
316 Effect.gen(function* () {
317 const orchestrator = yield* Orchestrator.OrchestratorV2;
318 const sink = yield* EventSink.EventSinkV2;
319 const threadId = ThreadId.make("thread:ceiling-queue");
320 yield* createThread(threadId);
321 yield* orchestrator.dispatch(sendMessage(threadId, "running"));
322 yield* orchestrator.dispatch({
323 ...sendMessage(threadId, "waiting"),
324 dispatchMode: { type: "queue_after_active" },
325 });
326 // The policy arrives with the thread above it and its first run ending.
327 const { thread, runs } = yield* orchestrator.getThreadRecords(threadId, ["runs"]);
328 const [running, waiting] = runs;
329 const occurredAt = yield* DateTime.now;
330 yield* sink.write({
331 events: [
332 {
333 id: EventId.make("event:ceiling-queue:raise"),
334 type: "thread.runtime-mode-updated",
335 threadId,
336 occurredAt,
337 payload: { ...thread, runtimeMode: "full-access" },
338 },
339 {
340 id: EventId.make("event:ceiling-queue:complete"),
341 type: "run.updated",
342 threadId,
343 runId: running!.id,
344 providerInstanceId: running!.providerInstanceId,
345 occurredAt,
346 payload: { ...running!, status: "completed" },
347 },
348 ],
349 });
350​
351 yield* orchestrator.dispatch({
352 type: "thread.runtime-mode.set",
353 commandId: CommandId.make("lower:ceiling-queue"),
354 threadId,
355 runtimeMode: "approval-required",
356 });
357 const started = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs.find(
358 (run) => run.id === waiting!.id,
359 );
360 assert.notEqual(started?.status, "queued");
361 }),
362 );
363});