The best way to control Claude Code, Codex and more from any computer or phone

main
ts 404 lines 14.5 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import {
3 EventId,
4 MessageId,
5 NodeId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ProviderSessionId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 RuntimeRequestId,
15 ThreadId,
16 type OrchestrationV2DomainEvent,
17 type OrchestrationV2StoredEvent,
18 } from "@t3tools/contracts";
19 import * as DateTime from "effect/DateTime";
20 import * as Effect from "effect/Effect";
21 import * as Fiber from "effect/Fiber";
22 import * as Layer from "effect/Layer";
23 import * as Queue from "effect/Queue";
24 import * as Stream from "effect/Stream";
25 import * as TestClock from "effect/testing/TestClock";
26 import * as SqlClient from "effect/sql/SqlClient";
27 import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
28 import * as SqlitePersistence from "../persistence/Sqlite.ts";
29 import * as EventSink from "./EventSink.ts";
30 import * as ProjectionStore from "./ProjectionStore.ts";
31 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
32 import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
33 import * as RuntimeRequestService from "./RuntimeRequestService.ts";
34
35 const threadId = ThreadId.make("thread:control-reads");
36 const providerThreadId = ProviderThreadId.make("provider-thread:control-reads");
37 const providerTurnId = ProviderTurnId.make("provider-turn:control-reads");
38 const providerSessionId = ProviderSessionId.make("session:control-reads");
39 const attemptId = RunAttemptId.make("attempt:control-reads");
40 const runId = RunId.make("run:control-reads");
41 const messageId = MessageId.make("message:control-reads");
42 const requestId = RuntimeRequestId.make("request:control-reads");
43 const nodeId = NodeId.make("node:control-reads");
44 const providerInstanceId = ProviderInstanceId.make("codex");
45 const driver = ProviderDriverKind.make("codex");
46 const modelSelection = { instanceId: providerInstanceId, model: "gpt-6" };
47
48 function fixtureEvents(now: DateTime.Utc): ReadonlyArray<OrchestrationV2DomainEvent> {
49 const common = { threadId, occurredAt: now };
50 return [
51 {
52 ...common,
53 id: EventId.make("control:thread"),
54 type: "thread.created",
55 payload: {
56 id: threadId,
57 projectId: ProjectId.make("project:control-reads"),
58 title: "Control reads",
59 providerInstanceId,
60 modelSelection,
61 createdBy: "user",
62 creationSource: "web",
63 runtimeMode: "full-access",
64 interactionMode: "default",
65 branch: null,
66 worktreePath: "/workspace",
67 activeProviderThreadId: providerThreadId,
68 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
69 forkedFrom: null,
70 createdAt: now,
71 updatedAt: now,
72 archivedAt: null,
73 settledOverride: null,
74 settledAt: null,
75 lastVisitedAt: null,
76 deletedAt: null,
77 },
78 },
79 {
80 ...common,
81 id: EventId.make("control:provider-thread"),
82 type: "provider-thread.updated",
83 payload: {
84 id: providerThreadId,
85 driver,
86 providerInstanceId,
87 providerSessionId,
88 appThreadId: threadId,
89 ownerNodeId: null,
90 nativeThreadRef: { driver, nativeId: "native-control-thread", strength: "strong" },
91 nativeConversationHeadRef: null,
92 status: "active",
93 firstRunOrdinal: 1,
94 lastRunOrdinal: 1,
95 handoffIds: [],
96 forkedFrom: null,
97 createdAt: now,
98 updatedAt: now,
99 },
100 },
101 {
102 ...common,
103 id: EventId.make("control:run"),
104 type: "run.created",
105 payload: {
106 id: runId,
107 threadId,
108 ordinal: 1,
109 providerInstanceId,
110 modelSelection,
111 providerThreadId,
112 userMessageId: messageId,
113 rootNodeId: nodeId,
114 activeAttemptId: attemptId,
115 status: "running",
116 requestedAt: now,
117 startedAt: now,
118 completedAt: null,
119 checkpointId: null,
120 contextHandoffId: null,
121 },
122 },
123 {
124 ...common,
125 id: EventId.make("control:attempt"),
126 type: "run-attempt.created",
127 payload: {
128 id: attemptId,
129 runId,
130 attemptOrdinal: 1,
131 rootNodeId: nodeId,
132 providerInstanceId,
133 providerThreadId,
134 providerTurnId,
135 reason: "initial",
136 status: "running",
137 startedAt: now,
138 completedAt: null,
139 },
140 },
141 {
142 ...common,
143 id: EventId.make("control:turn"),
144 type: "provider-turn.updated",
145 payload: {
146 id: providerTurnId,
147 providerThreadId,
148 nodeId,
149 runAttemptId: attemptId,
150 nativeTurnRef: { driver, nativeId: "native-control-turn", strength: "strong" },
151 ordinal: 1,
152 status: "running",
153 startedAt: now,
154 completedAt: null,
155 },
156 },
157 {
158 ...common,
159 id: EventId.make("control:message"),
160 type: "message.updated",
161 payload: {
162 id: messageId,
163 threadId,
164 runId,
165 nodeId,
166 role: "user",
167 text: "Use the smaller fix.",
168 attachments: [],
169 streaming: false,
170 createdBy: "user",
171 creationSource: "web",
172 createdAt: now,
173 updatedAt: now,
174 },
175 },
176 {
177 ...common,
178 id: EventId.make("control:request"),
179 type: "runtime-request.updated",
180 payload: {
181 id: requestId,
182 nodeId,
183 providerTurnId,
184 nativeRequestRef: null,
185 kind: "command",
186 status: "resolved",
187 responseCapability: { type: "live", providerSessionId },
188 createdAt: now,
189 resolvedAt: now,
190 },
191 },
192 ];
193 }
194
195 const storageCases = [
196 {
197 storage: "sqlite" as const,
198 storeLayer: ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
199 },
200 ];
201
202 it.effect.each(storageCases)(
203 "$storage: finds the active root turn without an attempt reverse link",
204 ({ storeLayer }) =>
205 Effect.gen(function* () {
206 const store = yield* ProjectionStore.ProjectionStoreV2;
207 const now = yield* DateTime.now;
208 const events = fixtureEvents(now).map((event) =>
209 event.type === "run-attempt.created"
210 ? { ...event, payload: { ...event.payload, providerTurnId: null } }
211 : event,
212 );
213 yield* Effect.forEach(events, (event) => store.apply(event), { discard: true });
214 const running = yield* store.getRunningTurnContext(threadId);
215 assert.equal(running.providerTurn?.id, providerTurnId);
216 const turnEvent = events.find((event) => event.type === "provider-turn.updated")!;
217 yield* store.apply({
218 ...turnEvent,
219 payload: { ...turnEvent.payload, status: "completed", completedAt: now },
220 });
221 assert.isUndefined((yield* store.getRunningTurnContext(threadId)).providerTurn);
222 }).pipe(Effect.provide(storeLayer)),
223 );
224 it.effect.each(storageCases)(
225 "$storage: controls and replies read only their exact durable targets",
226 ({ storage, storeLayer }) =>
227 Effect.gen(function* () {
228 const store = yield* ProjectionStore.ProjectionStoreV2;
229 const now = yield* DateTime.now;
230 const events = fixtureEvents(now);
231 yield* Effect.forEach(events, (event) => store.apply(event), { discard: true });
232 if (storage === "sqlite") {
233 const sql = yield* SqlClient.SqlClient;
234 yield* sql`INSERT INTO orchestration_v2_projection_messages
235 (message_id, thread_id, run_id, node_id, role, streaming, created_at, updated_at, payload_json)
236 VALUES ('message:unrelated-obsolete', ${threadId}, ${runId}, ${nodeId}, 'assistant', 0,
237 ${DateTime.formatIso(now)}, ${DateTime.formatIso(now)}, '{"obsolete":"transcript"}')`;
238 assert.equal((yield* Effect.exit(store.getThreadProjection(threadId)))._tag, "Failure");
239 const queryPlan = yield* sql<{ detail: string }>`EXPLAIN QUERY PLAN
240 SELECT payload_json FROM orchestration_v2_projection_turn_items
241 WHERE thread_id = ${threadId} AND node_id = ${nodeId}
242 AND type IN ('approval_request', 'user_input_request')
243 AND json_extract(payload_json, '$.requestId') = ${requestId}
244 ORDER BY ordinal ASC LIMIT 1`;
245 assert.isTrue(queryPlan.some((row) => row.detail.includes("turn_items_node_ordinal_idx")));
246 }
247 const running = yield* store.getRunningTurnContext(threadId);
248 assert.equal(running.run?.id, runId);
249 assert.equal(running.providerThread?.id, providerThreadId);
250 assert.equal(running.providerTurn?.id, providerTurnId);
251 const providerContext = yield* store.getThreadProviderContext(threadId, providerInstanceId);
252 assert.equal(providerContext.thread.id, threadId);
253 assert.deepEqual(
254 providerContext.providerThreads.map((thread) => thread.id),
255 [providerThreadId],
256 );
257 const responseContext = yield* store.getRuntimeResponseContext(threadId, requestId);
258 assert.equal(responseContext.request?.id, requestId);
259 const target = { providerThreadId, providerTurnId, attemptId, messageId };
260 const context = yield* store.getProviderControlContext(threadId, target);
261 assert.equal(context.providerThread?.id, providerThreadId);
262 assert.equal(context.providerTurn?.id, providerTurnId);
263 assert.equal(context.attempt?.id, attemptId);
264 assert.equal(context.message?.text, "Use the smaller fix.");
265 assert.equal(context.run?.id, runId);
266 assert.equal((yield* store.getRuntimeRequest(threadId, requestId))?.status, "resolved");
267 assert.isUndefined(
268 yield* store.getRuntimeRequest(threadId, RuntimeRequestId.make("request:missing")),
269 );
270 const absent = yield* store.getProviderControlContext(threadId, {
271 providerThreadId: ProviderThreadId.make("provider-thread:missing"),
272 providerTurnId: ProviderTurnId.make("provider-turn:missing"),
273 });
274 assert.isUndefined(absent.providerThread);
275 assert.isUndefined(absent.providerTurn);
276 const missingThread = yield* store
277 .getRuntimeRequest(ThreadId.make("thread:missing"), requestId)
278 .pipe(Effect.flip);
279 assert.instanceOf(missingThread, ProjectionStore.ProjectionStoreThreadNotFoundError);
280
281 const calls: string[] = [];
282 const layerSessions = Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
283 get: () =>
284 Effect.succeedSome({
285 interruptTurn: () =>
286 Effect.sync(() => {
287 calls.push("interrupt");
288 }),
289 steerTurn: (input: {
290 message: {
291 text: string;
292 };
293 runId: RunId;
294 }) =>
295 Effect.sync(() => {
296 assert.equal(input.runId, runId);
297 calls.push(input.message.text);
298 }),
299 respondToRuntimeRequest: () =>
300 Effect.sync(() => {
301 calls.push("reply");
302 }),
303 } as never),
304 });
305 // Each pull is announced, so a second pull proves Stop judged the first event.
306 const pulls = yield* Queue.unbounded<void>();
307 const committed = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
308 const layerEvents = Layer.mock(EventSink.EventSinkV2)({
309 latestSequence: () => Effect.succeed(0),
310 stream: () =>
311 Stream.fromEffectRepeat(
312 Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(committed))),
313 ),
314 });
315 yield* Effect.gen(function* () {
316 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
317 const reply = yield* RuntimeRequestService.RuntimeRequestServiceV2;
318 const interrupt = control.interrupt({
319 threadId,
320 providerThreadId,
321 providerTurnId,
322 providerSessionId,
323 });
324 // The provider never reports the turn settled, so Stop returns at the bound.
325 const unconfirmed = yield* Effect.forkChild(interrupt);
326 yield* Queue.take(pulls);
327 yield* TestClock.adjust("2 seconds");
328 yield* Fiber.join(unconfirmed);
329 yield* control.steer({
330 threadId,
331 providerThreadId,
332 providerTurnId,
333 providerSessionId,
334 messageId,
335 });
336 yield* reply.respond({ threadId, providerSessionId, requestId, decision: "accept" });
337 assert.deepEqual(calls, ["interrupt", "Use the smaller fix.", "reply"]);
338 const wrongSession = ProviderSessionId.make("session:wrong");
339 assert.equal(
340 (yield* Effect.exit(
341 control.interrupt({
342 threadId,
343 providerThreadId,
344 providerTurnId,
345 providerSessionId: wrongSession,
346 }),
347 ))._tag,
348 "Failure",
349 );
350 assert.equal(
351 (yield* Effect.exit(
352 reply.respond({
353 threadId,
354 providerSessionId: wrongSession,
355 requestId,
356 decision: "accept",
357 }),
358 ))._tag,
359 "Failure",
360 );
361 assert.lengthOf(calls, 3);
362 const confirmed = yield* Effect.forkChild(interrupt);
363 yield* Queue.take(pulls);
364 const ingest = (sequence: number, event: OrchestrationV2DomainEvent) =>
365 store
366 .apply(event)
367 .pipe(Effect.andThen(Queue.offer(committed, { sequence, commandId: null, event })));
368 yield* ingest(1, {
369 id: EventId.make("control:turn-completed"),
370 type: "provider-turn.updated",
371 threadId,
372 occurredAt: now,
373 payload: { ...context.providerTurn!, status: "completed", completedAt: now },
374 });
375 // A settled provider turn is not enough; Stop waits for its attempt to finalize.
376 yield* Queue.take(pulls);
377 assert.isUndefined(confirmed.pollUnsafe());
378 yield* ingest(2, {
379 id: EventId.make("control:attempt-completed"),
380 type: "run-attempt.updated",
381 threadId,
382 occurredAt: now,
383 payload: { ...context.attempt!, status: "completed", completedAt: now },
384 });
385 yield* Fiber.join(confirmed);
386 yield* interrupt;
387 assert.deepEqual(calls, [
388 "interrupt",
389 "Use the smaller fix.",
390 "reply",
391 "interrupt",
392 "interrupt",
393 ]);
394 }).pipe(
395 Effect.provide(
396 Layer.merge(ProviderTurnControlService.layer, RuntimeRequestService.layer).pipe(
397 Layer.provide(
398 Layer.mergeAll(layerSessions, layerEvents, McpAppModelContext.layerEmpty),
399 ),
400 ),
401 ),
402 );
403 }).pipe(Effect.provide(Layer.merge(storeLayer, SqlitePersistence.layerMemory))),
404 );