Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ export function useComposerCommandMenu({
: [];
const selectedProviderInstanceId = selectedProviderStatus?.instanceId;
const refreshWorkspaceSnapshot = useAtomRefresh(
environmentId && projectCwd && selectedProviderInstanceId
environmentId && selectedProviderInstanceId
? providerWorkspaceSnapshotRefresh({
environmentId,
instanceId: selectedProviderInstanceId,
Expand Down
28 changes: 27 additions & 1 deletion apps/server/src/delivery/DeliveryService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,31 @@ const bind = (
const CLAUDE_HERE = { driver: "claudeAgent", cwd: REPO };

describe("DeliveryService", () => {
it.effect(
"refuses native completion through the public relay before contacting the engine",
() => {
const fake = engine();
return Effect.gen(function* () {
const delivery = yield* DeliveryService.DeliveryService;
for (const path of [
"/api/native-builds/att-one/complete",
"/api/tasks/../native-builds/att-one/complete",
"/api/tasks/%2e%2e/native-builds/att-one/complete",
"/api/tasks\\..\\native-builds\\att-one\\complete",
]) {
const failure = yield* delivery
.act({ path, body: { state: "completed", text: "fabricated" } })
.pipe(Effect.flip);
expect(failure.reason).toBe("refused");
}
const invalid = yield* delivery
.nativeBuildAct({ path: "/api/tasks", body: {} })
.pipe(Effect.flip);
expect(invalid.reason).toBe("invalid");
expect(fake.requests).toEqual([]);
}).pipe(Effect.provide(layer(fake, { prefix: "native-relay-guard-" })));
},
);
it.effect("refuses reads and writes into another account profile's engine", () => {
const fake = engine();
return Effect.gen(function* () {
Expand Down Expand Up @@ -681,7 +706,8 @@ describe("DeliveryService", () => {
}).pipe(Effect.provide(shared("t3-delivery-unreadable-")));
});

it.effect("fails the binding when it cannot be saved, and asks nothing of the engine", () => {
// Atomic replacement retries transient Windows filesystem errors on the real clock.
it.live("fails the binding when it cannot be saved, and asks nothing of the engine", () => {
const fake = engine();
return Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
Expand Down
48 changes: 47 additions & 1 deletion apps/server/src/delivery/DeliveryService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ export class DeliveryService extends Context.Service<
{
readonly read: (input: DeliveryReadInput) => Effect.Effect<DeliveryResponse, DeliveryError>;
readonly act: (input: DeliveryActInput) => Effect.Effect<DeliveryResponse, DeliveryError>;
/** Internal coordinator writes. Never expose this method as a generic client relay. */
readonly nativeBuildAct: (
input: DeliveryActInput,
) => Effect.Effect<DeliveryResponse, DeliveryError>;
readonly bindThread: (
input: DeliveryBindThreadInput,
) => Effect.Effect<DeliveryThreadBinding, DeliveryError>;
Expand All @@ -132,6 +136,28 @@ export class DeliveryService extends Context.Service<
}
>()("t3/delivery/DeliveryService") {}

const disabled = () =>
Effect.fail(new DeliveryError({ reason: "disabled", detail: "Delivery is turned off." }));

/** Inert service, for suites that only need the RPC surface to resolve. */
export const layerTest = Layer.succeed(
DeliveryService,
DeliveryService.of({
read: disabled,
act: disabled,
nativeBuildAct: disabled,
bindThread: disabled,
threadState: Effect.fn("DeliveryService.threadState")(() =>
Effect.succeed({ binding: null, pending: null }),
),
releaseThread: Effect.fn("DeliveryService.releaseThread")(() =>
Effect.succeed({ binding: null, pending: null }),
),
prepareThread: Effect.fn("DeliveryService.prepareThread")(() => Effect.succeed(false)),
terminalEntryScript: Effect.succeed(null),
}),
);

const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
Expand Down Expand Up @@ -673,7 +699,27 @@ const make = Effect.gen(function* () {

return DeliveryService.of({
read: Effect.fn("DeliveryService.read")((input) => request("GET", input.path)),
act: Effect.fn("DeliveryService.act")((input) => request("POST", input.path, input.body)),
act: Effect.fn("DeliveryService.act")((input) =>
new URL(input.path, "http://delivery.invalid").pathname.startsWith("/api/native-builds/")
? Effect.fail(
new DeliveryError({
reason: "refused",
detail:
"Native build receipts can only be written by the server's native coordinator.",
}),
)
: request("POST", input.path, input.body),
),
nativeBuildAct: Effect.fn("DeliveryService.nativeBuildAct")((input) =>
/^\/api\/native-builds\/att-[A-Za-z0-9-]+\/(claim|attach|complete)$/.test(input.path)
? request("POST", input.path, input.body)
: Effect.fail(
new DeliveryError({
reason: "invalid",
detail: "Invalid native coordinator mutation path.",
}),
),
),
bindThread,
threadState: Effect.fn("DeliveryService.threadState")((threadId) =>
storeReadable.pipe(Effect.as(stateOf(threadId))),
Expand Down
227 changes: 227 additions & 0 deletions apps/server/src/delivery/NativeBuildExecution.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
import { DeliveryService } from "./DeliveryService.ts";
import { OrchestratorMcpService } from "../mcp/OrchestratorMcpService.ts";
import type { McpInvocationScope } from "../mcp/McpInvocationContext.ts";
import { make } from "./NativeBuildExecution.ts";

const scope: McpInvocationScope = {
environmentId: EnvironmentId.make("environment"),
capabilities: new Set(["orchestration"]),
issuedAt: 0,
requestNamespace: "session-one",
thread: {
threadId: ThreadId.make("parent"),
providerSessionId: "session",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
};

function setup({
mismatch = false,
attachFailure = false,
paged = false,
claimedCancellation = false,
cancelOnClaim = false,
} = {}) {
let build = {
version: 1,
id: "att-one",
worktree: "C:/build/worktree",
harness: "codex",
model: "model",
prompt: "Build and return JSON.",
access: "full",
state: claimedCancellation ? "claimed" : "queued",
owner: (claimedCancellation ? `${scope.environmentId}:${scope.thread?.threadId}` : null) as
| string
| null,
cancelRequested: claimedCancellation,
native: null as { taskId: string; childThreadId: string } | null,
};
let nativeState = "running";
const admissions = new Set<string>();
const readThread = vi.fn(
(_caller: McpInvocationScope, input: { threadId: string; afterPosition?: number }) =>
Effect.succeed(
input.threadId === "parent"
? { thread: { worktreePath: mismatch ? "C:/another/worktree" : build.worktree } }
: paged && input.afterPosition === undefined
? { hasMore: true, nextPosition: 100, items: [] }
: {
hasMore: false,
items: [
{
runId: "native-run",
type: "assistant_message",
textTruncated: false,
text: '{"summary":"done"}',
},
],
},
),
);
const delegateTask = vi.fn((caller: McpInvocationScope, input: { clientRequestId: string }) => {
admissions.add(`${caller.requestNamespace}:${input.clientRequestId}`);
return Effect.succeed({ taskId: "native-task", childThreadId: "native-thread" });
});
const cancelTask = vi.fn(() => {
nativeState = "cancelled";
return Effect.succeed({ taskId: "native-task", status: "cancelled" });
});
const orchestrator = {
readThread,
delegateTask,
cancelTask,
capabilities: () =>
Effect.succeed({
inheritedModel: "model",
runtimeMode: "full-access",
providers: [{ providerInstanceId: "codex", driverKind: "codex", canRunChildTask: true }],
}),
taskStatus: () =>
Effect.succeed({
workState: nativeState === "running" ? "working" : "result_available",
hasPendingChildRuns: false,
latestTerminalStatus: nativeState === "running" ? null : nativeState,
latestTerminalRunId: "native-run",
}),
} as unknown as OrchestratorMcpService["Service"];
const completed: unknown[] = [];
const delivery = {
read: () => Effect.succeed({ body: build }),
nativeBuildAct: ({
path,
body,
}: {
path: string;
body: { owner: string; taskId: string; childThreadId: string; state: string };
}) => {
if (path.endsWith("/claim"))
build = cancelOnClaim
? { ...build, cancelRequested: true, state: "cancelled" }
: { ...build, owner: body.owner, state: "claimed" };
if (path.endsWith("/attach")) {
if (attachFailure) {
attachFailure = false;
return Effect.fail({ detail: "lost attach response" });
}
build = { ...build, native: { taskId: body.taskId, childThreadId: body.childThreadId } };
}
if (path.endsWith("/complete")) {
completed.push(body);
build = { ...build, state: body.state };
}
return Effect.succeed({ body: build });
},
} as unknown as DeliveryService["Service"];
const service = () =>
make.pipe(
Effect.provideService(DeliveryService, delivery),
Effect.provideService(OrchestratorMcpService, orchestrator),
Effect.provideService(HostProcess.Platform, "win32"),
);
return {
service,
delegateTask,
cancelTask,
admissions,
completed,
setNativeState: (state: string) => {
nativeState = state;
},
requestCancel: () => {
build = { ...build, cancelRequested: true };
},
};
}

it.effect("rejects checkout mismatch before native admission", () =>
Effect.gen(function* () {
const fixture = setup({ mismatch: true });
const service = yield* fixture.service();
const failure = yield* service.step(scope, { attemptId: "att-one" }).pipe(Effect.flip);
expect(failure.message).toMatch(/existing worktree/);
expect(fixture.delegateTask).not.toHaveBeenCalled();
}),
);
it.effect(
"recovers uncertain dispatch with a stable native receipt across coordinator sessions",
() =>
Effect.gen(function* () {
const fixture = setup({ attachFailure: true });
const first = yield* fixture.service();
const failure = yield* first.step(scope, { attemptId: "att-one" }).pipe(Effect.flip);
expect(failure.message).toMatch(/lost attach/);
const recovered = yield* fixture.service();
const nextScope = { ...scope, requestNamespace: "session-two" };
expect((yield* recovered.step(nextScope, { attemptId: "att-one" })).state).toBe("working");
expect(fixture.admissions.size).toBe(1);
fixture.setNativeState("completed");
expect((yield* recovered.step(nextScope, { attemptId: "att-one" })).state).toBe("completed");
expect(fixture.completed).toEqual([
expect.objectContaining({
state: "completed",
text: '{"summary":"done"}',
taskId: "native-task",
}),
]);
}),
);
it.effect(
"reconciles engine cancellation using native cancellation and native terminal state",
() =>
Effect.gen(function* () {
const fixture = setup();
const service = yield* fixture.service();
yield* service.step(scope, { attemptId: "att-one" });
fixture.requestCancel();
expect((yield* service.step(scope, { attemptId: "att-one" })).state).toBe("cancelled");
expect(fixture.cancelTask).toHaveBeenCalledOnce();
expect(fixture.completed).toEqual([
expect.objectContaining({ state: "cancelled", text: "" }),
]);
}),
);

it.effect("rejects an unsafe attempt id before relaying any native operation", () =>
Effect.gen(function* () {
const fixture = setup();
const service = yield* fixture.service();
const failure = yield* service.step(scope, { attemptId: "../tasks" }).pipe(Effect.flip);
expect(failure.message).toMatch(/Invalid native attempt/);
expect(fixture.delegateTask).not.toHaveBeenCalled();
}),
);
it.effect("pages the native transcript to obtain the authoritative final result", () =>
Effect.gen(function* () {
const fixture = setup({ paged: true });
const service = yield* fixture.service();
yield* service.step(scope, { attemptId: "att-one" });
fixture.setNativeState("completed");
expect((yield* service.step(scope, { attemptId: "att-one" })).state).toBe("completed");
expect(fixture.completed).toEqual([expect.objectContaining({ text: '{"summary":"done"}' })]);
}),
);

it.effect("does not launch an uncertain claimed build after cancellation", () =>
Effect.gen(function* () {
const fixture = setup({ claimedCancellation: true });
const service = yield* fixture.service();
const failure = yield* service.step(scope, { attemptId: "att-one" }).pipe(Effect.flip);
expect(failure.message).toMatch(/No new child will be launched/);
expect(fixture.delegateTask).not.toHaveBeenCalled();
}),
);
it.effect("does not launch when cancellation wins between read and claim", () =>
Effect.gen(function* () {
const fixture = setup({ cancelOnClaim: true });
const service = yield* fixture.service();
expect((yield* service.step(scope, { attemptId: "att-one" })).state).toBe("cancelled");
expect(fixture.delegateTask).not.toHaveBeenCalled();
}),
);
Loading
Loading