Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1369,6 +1369,33 @@ describe("source control tools", () => {
}),
);

it.effect("pins a review to the head the caller read, and approves only with one", () =>
Effect.gen(function* () {
const reviews: Array<PullRequestSubmitReviewInput> = [];
const harness = yield* makeHarness({
thread: branchThread,
pullRequests: {
submitReview: (input) => Effect.sync(() => void reviews.push(input)),
},
});
yield* harness.call("pull_request_review", {
verdict: "approve",
expectedHeadSha: "abc1234def5678",
});
expect(reviews).toMatchObject([{ verdict: "approve", expectedHeadSha: "abc1234def5678" }]);

const error = yield* harness
.call("pull_request_review", { verdict: "approve" })
.pipe(Effect.flip);
expect(error.message).toContain("expectedHeadSha");
expect(reviews).toHaveLength(1);

yield* harness.call("pull_request_review", { verdict: "comment", body: "A question." });
expect(reviews).toHaveLength(2);
expect(reviews[1]).not.toHaveProperty("expectedHeadSha");
}),
);

it.effect("updates labels, requests reviewers by login, and closes the PR", () =>
Effect.gen(function* () {
const calls: Array<unknown> = [];
Expand Down
16 changes: 15 additions & 1 deletion apps/server/src/mcp/toolkits/pullRequests/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1182,10 +1182,24 @@ const make = Effect.gen(function* () {
),
pull_request_review: McpToolAccess.writesWithCapability((input) =>
Effect.gen(function* () {
if (input.verdict === "approve" && input.expectedHeadSha === undefined) {
return yield* new PullRequestForgeError({
detail:
"Approving needs expectedHeadSha: the headSha pull_request_read reported for the commits you reviewed.",
});
}
const { target, ref } = yield* locate(input);
const comments = yield* reviewComments(ref, input.comments ?? []);
yield* pullRequests
.submitReview({ ...ref, verdict: input.verdict, body: input.body ?? "", comments })
.submitReview({
...ref,
verdict: input.verdict,
body: input.body ?? "",
comments,
...(input.expectedHeadSha === undefined
? {}
: { expectedHeadSha: input.expectedHeadSha }),
})
.pipe(Effect.mapError(forgeFailure));
return identityOf(target);
}),
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/mcp/toolkits/pullRequests/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -767,10 +767,11 @@ export type ReviewLineComment = typeof ReviewLineComment.Type;

const ReviewPullRequestTool = Tool.make("pull_request_review", {
description:
"Submit a review: approve, request changes, or comment, with optional line comments.",
"Submit a review: approve, request changes, or comment, with optional line comments. Approving needs expectedHeadSha (headSha in pull_request_read). Refuses if the head moved from it.",
parameters: Schema.Struct({
...ThreadPullRequestInput.fields,
verdict: PullRequestReviewVerdict,
expectedHeadSha: Schema.optional(TrimmedNonEmptyString),
body: Schema.optional(Schema.String),
comments: Schema.optional(Schema.Array(ReviewLineComment).check(Schema.isMaxLength(50))),
}),
Expand Down
7 changes: 5 additions & 2 deletions apps/server/src/mcp/toolkits/workflow/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,9 @@ it.effect("hook paths go only to a caller at the broadest mode", () =>
it.effect("under an administrator's ceiling, a caller at the ceiling starts runs", () =>
Effect.gen(function* () {
const start = { action: "start", workflow: "release", idempotencyKey: "trial" };
const started: Array<string> = [];
const workflows = {
start: () => Effect.succeed({ runId: "run-1" }),
start: (name: string) => Effect.sync(() => (started.push(name), { runId: "run-1" })),
get: () => Effect.succeed(emptyRun),
};
const narrowedTo = (runtimeMode: "auto" | "approval-required") => ({
Expand All @@ -189,11 +190,13 @@ it.effect("under an administrator's ceiling, a caller at the ceiling starts runs
});
expect(
yield* call(start).pipe(Effect.provide(handlersWith(workflows, narrowedTo("auto")))),
).not.toMatchObject({ code: "capability_denied" });
).toEqual({ steps: [], references: [] });
expect(started).toEqual(["release"]);
expect(
yield* call(start).pipe(
Effect.provide(handlersWith(workflows, narrowedTo("approval-required"))),
),
).toMatchObject({ code: "capability_denied" });
expect(started).toEqual(["release"]);
}),
);
91 changes: 91 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import type * as EffectAcpSchema from "effect-acp/compat";
import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import {
ACP_EMPTY_OPTION_VALUE,
Expand Down Expand Up @@ -13069,6 +13070,96 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest)),
);

it.live("sends an image to an agent without image prompts as a file path", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const host = yield* ProviderHost.ProviderHost;
const selfInvocation = yield* resolveSelfInvocation();
const mockAgentPath = yield* bundledMockAgentPath;
const sent: Array<EffectAcpSchema.PromptRequest["prompt"]> = [];
const instanceId = ProviderInstanceId.make("acp-test-image-without-image-prompts");
const threadId = ThreadId.make("thread-acp-image-without-image-prompts");
const adapter = yield* makeAcpAdapterV2({
instanceId,
selfInvocation,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath,
wrapRuntime: (runtime) => ({
...runtime,
prompt: (payload, promptOptions) =>
Effect.sync(() => void sent.push(payload.prompt)).pipe(
Effect.andThen(runtime.prompt(payload, promptOptions)),
),
}),
}),
},
});
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const modelSelection = { instanceId, model: "default" } as const;
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-image-without-prompts"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const screenshot = {
type: "image",
id: "screenshot-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 8,
} as const;
const screenshotPath = host.resolveAttachmentPath(screenshot);
if (screenshotPath === null) return assert.fail("expected a screenshot path");
yield* fileSystem.writeFile(
screenshotPath,
Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a),
);
const base = makeTurnInput({
threadId,
providerThread,
instanceId,
runtimePolicy,
now: yield* DateTime.now,
messageText: "What is in this screenshot?",
});

yield* runtime.startTurn({
...base,
message: { ...base.message, attachments: [screenshot] },
});
const terminal = yield* runtime.events.pipe(
Stream.filter((event) => event.type === "turn.terminal"),
Stream.runHead,
);

assert.equal(Option.getOrThrow(terminal).status, "completed");
const blocks = sent[0] ?? [];
assert.deepEqual(
blocks.filter((block) => block.type !== "text"),
[],
);
assert.include(
blocks.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"),
`[Attached image "screenshot.png" is saved at: ${screenshotPath}]`,
);
}).pipe(Effect.provide(layerTest)),
);

it.live(
"delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer",
() =>
Expand Down
62 changes: 62 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13856,6 +13856,57 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
}),
);
// A sleep is a timer the agent ends its turn on, so a restart must wake it.
const sleeps = [
["timer", "sleep 1740; date", true],
["computed_timer", "sleep $((29 * 60)); date", true],
["quoted_timer", 'sleep "60" && date', true],
["single_quoted_timer", "sleep '60'; date", true],
["quoted_computed_timer", 'sleep "$((29 * 60))"; date', true],
["expanded_timer", 'sleep "${DELAY:-60}"; date', true],
["unit_timer", 'sleep 5m && echo "Time to check the build"', true],
["quoted_note_timer", 'sleep 60 && echo "Timer finished; check build"', true],
["endless_sleep", "sleep infinity", false],
["delayed_server", "sleep 5 && npm run dev", false],
["substituted_server", 'sleep 60; echo "$(npm run dev)"', false],
] as const;
yield* Queue.offer(
harness.sdkMessages,
claudeSdkFrame({
type: "assistant",
message: {
model: "claude-sonnet-4-6",
id: "msg_background_timer",
type: "message",
role: "assistant",
content: sleeps.map(([taskId, command]) => ({
type: "tool_use",
id: `toolu_${taskId}`,
name: "Bash",
input: { command, run_in_background: true },
})),
},
parent_tool_use_id: null,
uuid: "background-timer-launch",
session_id: WAKE_NATIVE_SESSION,
}),
);
for (const [index, [taskId]] of sleeps.entries()) {
yield* Queue.offer(
harness.sdkMessages,
claudeSdkFrame({
type: "system",
subtype: "task_started",
task_id: taskId,
tool_use_id: `toolu_${taskId}`,
description: "Wait before the next check",
is_backgrounded: true,
task_type: "local_bash",
uuid: `00000000-0000-4000-8000-00000000021${index}`,
session_id: WAKE_NATIVE_SESSION,
}),
);
}
yield* Queue.offer(harness.sdkMessages, turnOneResult);
yield* harness.awaitTerminal(1);

Expand All @@ -13866,6 +13917,17 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0];
assert.equal(started?.taskId, WAKE_TASK_ID);
assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID);
assert.deepEqual(
(afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? []).map((task) => [
task.taskId,
task.awaited === true,
]),
[
[WAKE_TASK_ID, false],
["moved-build", false],
...sleeps.map(([taskId, , awaited]) => [taskId, awaited]),
],
);

const command = harness.events.find(
(event) =>
Expand Down
76 changes: 71 additions & 5 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2434,6 +2434,67 @@ function parseClaudeInteger(text: string): number {
return Number.parseInt(value, 10);
}

const CLAUDE_SLEEP_DURATION = String.raw`(?:\d[\w.]*|\$\(\([\d\s+*/%-]+\)\)|\$\{\w+(?::?[-=]\d[\w.]*)?\}|\$\w+)`;
const CLAUDE_SLEEP_TIMER_START = new RegExp(
String.raw`^[ \t\n]*sleep[ \t]+(?:${CLAUDE_SLEEP_DURATION}|"${CLAUDE_SLEEP_DURATION}"|'\d[\w.]*')[ \t]*(?:$|;|&&|\n)`,
);
// Bash separates words only with spaces and tabs, so `\s` would read `true\rnpm` as `true`.
const CLAUDE_SLEEP_TIMER_REPORT = /^[ \t]*(?:$|(?:date|echo|printf|true|:)(?:[ \t]|$))/;

// A background command that only sleeps for a finite time, then at most prints the time or a
// note, is a timer the agent set to check back, which Claude wakes it for when it ends. Any other
// step (`sleep 5 && npm run dev`) may never end, so that command is not a timer.
function isClaudeSleepTimer(command: string | undefined): boolean {
const start = command === undefined ? null : CLAUDE_SLEEP_TIMER_START.exec(command);
if (command === undefined || start === null) return false;
const steps = splitClaudeSleepTimerSteps(command.slice(start[0].length));
return steps !== undefined && steps.every((step) => CLAUDE_SLEEP_TIMER_REPORT.test(step));
}

// Splits at unquoted `;`, `&&` and newlines. Gives up on anything a report never needs that could
// run or hide another command: pipes, `||`, a lone `&`, subshells, heredocs, substitutions, `${…}`,
// `$'…'`, comments, and unbalanced quotes or escapes.
function splitClaudeSleepTimerSteps(tail: string): string[] | undefined {
const steps: string[] = [];
let step = "";
let quote: string | undefined;
for (let index = 0; index < tail.length; index++) {
const char = tail[index] ?? "";
const next = tail[index + 1] ?? "";
if (quote === "'") {
if (char === "'") quote = undefined;
step += char;
continue;
}
if (char === "\\") {
if (next === "") return undefined;
step += char + next;
index++;
continue;
}
if (char === "`" || (char === "$" && "({'\"".includes(next) && next !== "")) return undefined;
if (quote === '"') {
if (char === '"') quote = undefined;
step += char;
continue;
}
if (char === "'" || char === '"') {
quote = char;
} else if (char === ";" || char === "\n" || (char === "&" && next === "&")) {
steps.push(step);
step = "";
if (char === "&") index++;
continue;
} else if (char === "&" ? next !== ">" && tail[index - 1] !== ">" : "|()<#".includes(char)) {
return undefined;
}
step += char;
}
if (quote !== undefined) return undefined;
steps.push(step);
return steps;
}

// Claude Code defers MCP tools behind ToolSearch, so the agent only finds
// t3_background_wait when the system prompt says when to reach for it.
const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = `
Expand Down Expand Up @@ -7206,17 +7267,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
nativeThreadId: string,
task: OrchestrationV2PendingBackgroundTask,
) {
const startedMonitor = yield* Ref.modify(
const startedWait = yield* Ref.modify(
pendingBackgroundTasksByNativeThread,
(current) => {
const roster = new Map(rosterForNativeThread(current, nativeThreadId));
const startedMonitor =
task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor";
const previous = roster.get(task.taskId);
const startedWait =
task.kind === "monitor"
? previous?.kind !== "monitor"
: task.kind === "command" &&
previous?.command === undefined &&
isClaudeSleepTimer(task.command);
roster.set(task.taskId, task);
return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const;
return [startedWait, new Map(current).set(nativeThreadId, roster)] as const;
},
);
if (startedMonitor) {
if (startedWait) {
yield* addTaskIdsToNativeThreadSet(
awaitedBackgroundTasksByNativeThread,
nativeThreadId,
Expand Down
Loading
Loading