The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 09:30 UTC
perf(server): avoid unused history when acknowledging tasks (#27803)
Co-authored-by: maria-rcks <maria@kuuro.net>
Adamulek123 committed
Nov 1, 2026 at 03:18 UTC
8f1e61cc7f355a996b658d3924da2196fc855940
3 files changed
+168
-6
apps/server/src/mcp/OrchestratorMcpService.ts
+11
-1
@@ -1703,7 +1703,17 @@ const make = Effect.gen(function* () {
1703
task.completionDelivery?.state !== "acknowledged" &&
1704
task.completionDelivery?.state !== "disposed"
1705
) {
1706
- const parentProjection = yield* loadProjection(scope.thread.threadId);
1706
+ const parentThreadId = scope.thread.threadId;
1707
+ const parentProjection = yield* threadManagement
1708
+ .getThreadRecords(parentThreadId, ["runs"])
1709
+ .pipe(
1710
+ Effect.mapError((error) =>
1711
+ failure(
1712
+ "orchestration_error",
1713
+ `Unable to read thread ${parentThreadId}: ${errorMessage(error)}`,
1714
+ ),
1715
+ ),
1716
+ );
1717
const observingRun = ThreadManagementService.latestActiveRun(parentProjection);
1718
yield* threadManagement
1719
.dispatch({
apps/server/src/orchestration-v2/Orchestrator.ts
+15
-4
@@ -2378,8 +2378,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2378
const projection = yield* projectionStore
2379
.getThreadRecords(
2380
command.parentThreadId,
2381
- ["subagents", "runs", "messages", "nodes", "attempts", "turnItems"],
2382
- { turnItemTypes: [], messageRoles: ["user"] },
2381
+ ["subagents", "runs", "nodes", "attempts", "turnItems"],
2382
+ { turnItemTypes: [] },
2383
)
2384
.pipe(
2385
Effect.mapError(
@@ -2467,8 +2467,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2467
return;
2468
}
2469
2470
+ const { messages } = yield* projectionStore
2471
+ .getThreadRecords(command.parentThreadId, ["messages"], {
2472
+ messageRoles: ["user"],
2473
+ messageIds: [delivery.messageId],
2474
+ })
2475
+ .pipe(
2476
+ Effect.mapError(
2477
+ (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),
2478
+ ),
2479
+ );
2480
+ const deliveryProjection = { ...projection, messages };
2481
const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id);
2471
- const deliveryRun = completionDeliveryRun(projection, delivery);
2482
+ const deliveryRun = completionDeliveryRun(deliveryProjection, delivery);
2483
const clearDelivery =
2484
remainingTaskIds.length === 0 &&
2485
(deliveryRun === undefined || deliveryRun.status === "queued");
@@ -2505,7 +2516,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2516
});
2517
return parentRun.id;
2518
}
2508
- const message = completionDeliveryMessage(projection, delivery);
2519
+ const message = completionDeliveryMessage(deliveryProjection, delivery);
2520
if (message !== undefined) {
2521
yield* emitEvent({
2522
type: "message.updated",
apps/server/src/peer/RemoteDelegation.test.ts
+142
-1
@@ -29,6 +29,7 @@ import * as Queue from "effect/Queue";
29
import * as Ref from "effect/Ref";
30
import * as Schedule from "effect/Schedule";
31
import * as Stream from "effect/Stream";
32
+import * as Tracer from "effect/Tracer";
33
import * as SubscriptionRef from "effect/SubscriptionRef";
34
import type * as SqlClient from "effect/sql/SqlClient";
35
import { McpSchema, McpServer } from "effect/ai";
@@ -845,15 +846,155 @@ it.effect("a task delegated to the box wakes the laptop's parent when it ends th
846
);
847
expect(Option.isSome(offered)).toBe(true);
848
848
- const status = yield* a.call("task_status", { taskId: delegated.taskId });
849
+ const messageReads: Array<string> = [];
850
+ const tracer = Tracer.make({
851
+ span(options) {
852
+ const span = new Tracer.NativeSpan(options);
853
+ const end = span.end.bind(span);
854
+ span.end = (endTime, exit) => {
855
+ end(endTime, exit);
856
+ const query = span.attributes.get("db.query.text");
857
+ if (
858
+ typeof query === "string" &&
859
+ /SELECT[\s\S]*FROM orchestration_v2_projection_messages/i.test(query)
860
+ ) {
861
+ messageReads.push(query);
862
+ }
863
+ };
864
+ return span;
865
+ },
866
+ });
867
+ const status = yield* a
868
+ .call("task_status", { taskId: delegated.taskId })
869
+ .pipe(Effect.withTracer(tracer));
870
expect(status.structuredContent).toMatchObject({
871
status: "completed",
872
summary: "All 412 tests pass on the box.",
873
});
874
+ // Delivery validation still reads messages; choosing the observer does not need another read.
875
+ expect(messageReads).toHaveLength(2);
876
+ expect(messageReads.filter((query) => !/\bmessage_id\s+IN\b/i.test(query))).toHaveLength(1);
877
+ const acknowledged = yield* a.projections.getThreadRecords(parentThreadId, ["subagents"], {
878
+ subagentIds: [delegated.taskId],
879
+ });
880
+ expect(acknowledged.subagents[0]?.completionDelivery).toEqual({
881
+ state: "acknowledged",
882
+ observedByRunId: parentRunId,
883
+ });
884
}),
885
).pipe(Effect.provide(NodeHttpServer.layerTest)),
886
);
887
888
+it.effect.each(["no active parent run", "a newer run owned by another provider"] as const)(
889
+ "preserves remote observation guards with %s",
890
+ (observer) =>
891
+ Effect.scoped(
892
+ Effect.gen(function* () {
893
+ const thread = yield* makeBoxThread;
894
+ const b = yield* serveBox(thread);
895
+ const offers = yield* SubscriptionRef.make<
896
+ ReadonlyArray<ProviderContinuationRequests.ProviderContinuationRequest>
897
+ >([]);
898
+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
899
+ const a = yield* makeLaptop(database, offers);
900
+ yield* linkTo(a.links, b, "full-access");
901
+ yield* seedParent(a);
902
+ const delegated = yield* delegateToBox(a);
903
+
904
+ yield* Ref.set(thread.reply, "Remote result remains available.");
905
+ yield* Ref.set(thread.status, "completed");
906
+ yield* Deferred.succeed(thread.finished, undefined);
907
+ yield* taskResult(a, delegated.taskId);
908
+ yield* SubscriptionRef.changes(offers).pipe(
909
+ Stream.filter((seen) => seen.some((offer) => offer.threadId === parentThreadId)),
910
+ Stream.runHead,
911
+ );
912
+
913
+ const parent = yield* a.projections.getThreadRecords(
914
+ parentThreadId,
915
+ ["runs", "subagents"],
916
+ {
917
+ subagentIds: [delegated.taskId],
918
+ },
919
+ );
920
+ expect(parent.subagents[0]?.completionDelivery?.state).not.toBe("acknowledged");
921
+ const parentRun = parent.runs.find((run) => run.id === parentRunId);
922
+ if (parentRun === undefined) return yield* Effect.die("The parent run was not seeded.");
923
+ const now = yield* DateTime.now;
924
+ const otherInstanceId = ProviderInstanceId.make("codex-other");
925
+ const observingRun: OrchestrationV2Run =
926
+ observer === "no active parent run"
927
+ ? { ...parentRun, status: "completed", completedAt: now }
928
+ : {
929
+ id: RunId.make("run:laptop-other-provider"),
930
+ threadId: parentThreadId,
931
+ ordinal: parentRun.ordinal + 1,
932
+ providerInstanceId: otherInstanceId,
933
+ modelSelection: { instanceId: otherInstanceId, model: "gpt-5.4" },
934
+ providerThreadId: null,
935
+ userMessageId: MessageId.make("message:laptop-other-provider"),
936
+ rootNodeId: null,
937
+ activeAttemptId: null,
938
+ status: "preparing",
939
+ requestedAt: now,
940
+ startedAt: null,
941
+ completedAt: null,
942
+ checkpointId: null,
943
+ contextHandoffId: null,
944
+ };
945
+ yield* a.sink.write({
946
+ commandId: CommandId.make("command:change-remote-result-observer"),
947
+ events: [
948
+ {
949
+ id: EventId.make("event:change-remote-result-observer"),
950
+ type: "run.updated",
951
+ threadId: parentThreadId,
952
+ runId: observingRun.id,
953
+ providerInstanceId: observingRun.providerInstanceId,
954
+ occurredAt: now,
955
+ payload: observingRun,
956
+ },
957
+ ],
958
+ });
959
+
960
+ const status = yield* a.call("task_status", { taskId: delegated.taskId });
961
+ if (observer === "no active parent run") {
962
+ expect(status.isError).toBe(true);
963
+ expect(status.content).toEqual([
964
+ {
965
+ type: "text",
966
+ text: JSON.stringify({
967
+ _tag: "OrchestratorMcpFailure",
968
+ code: "parent_not_active",
969
+ message: "The calling provider no longer owns an active thread run.",
970
+ }),
971
+ },
972
+ ]);
973
+ const unacknowledged = yield* a.projections.getThreadRecords(
974
+ parentThreadId,
975
+ ["subagents"],
976
+ { subagentIds: [delegated.taskId] },
977
+ );
978
+ expect(unacknowledged.subagents[0]?.result).toBe("Remote result remains available.");
979
+ expect(unacknowledged.subagents[0]?.completionDelivery?.state).not.toBe("acknowledged");
980
+ return;
981
+ }
982
+ expect(status.isError, JSON.stringify(status.content)).not.toBe(true);
983
+ expect(status.structuredContent).toMatchObject({
984
+ status: "completed",
985
+ summary: "Remote result remains available.",
986
+ });
987
+ const acknowledged = yield* a.projections.getThreadRecords(parentThreadId, ["subagents"], {
988
+ subagentIds: [delegated.taskId],
989
+ });
990
+ expect(acknowledged.subagents[0]?.completionDelivery).toEqual({
991
+ state: "acknowledged",
992
+ observedByRunId: null,
993
+ });
994
+ }),
995
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
996
+);
997
+
998
it.effect(
999
"with the beta off here, a task already running there still ends, and no new one starts",
1000
() =>