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
71 changes: 71 additions & 0 deletions apps/desktop/src/backend/DesktopBackendManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,77 @@ describe("DesktopBackendManager", () => {
}),
);

// The first probe's body stalls after the headers, or never ends past the 64 KiB read cap.
it.effect.each([
{ body: "stalled" as const, proven: true, readyAfterProbes: 2 },
{ body: "stalled" as const, proven: false, readyAfterProbes: 2 },
{ body: "endless" as const, proven: true, readyAfterProbes: 1 },
])(
"a $body probe body settles within its timeout (launch proof: $proven)",
({ body, proven, readyAfterProbes }) =>
Effect.gen(function* () {
const probes = yield* Ref.make(0);
const probed = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const proof = "proof-for-abc";
const firstBody = () =>
new ReadableStream<Uint8Array>({
start: (controller) => {
if (body === "endless") {
controller.enqueue(new TextEncoder().encode(proof.padEnd(70_000, "x")));
}
},
});
const instance = yield* makeTestInstance({
config: {
...pollingConfig,
...(proven
? {
readinessProbe: Effect.succeed({
path: "/launch-proof?challenge=abc",
accept: (text: string) =>
Effect.succeed(
text === proof || (text.startsWith(proof) && text.length === 64 * 1024),
),
}),
}
: {}),
},
onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
spawnerLayer: Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.acquireRelease(
Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })),
() => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
),
),
),
httpClientLayer: layerHttpClient((request) =>
Ref.getAndUpdate(probes, (count) => count + 1).pipe(
Effect.tap(() => Deferred.succeed(probed, undefined)),
Effect.map((count) =>
HttpClientResponse.fromWeb(
request,
new Response(count === 0 ? firstBody() : proof, { status: 200 }),
),
),
),
),
});
yield* instance.start;
yield* Deferred.await(probed);
// Past the probe timeout, then past the retry interval it starts.
yield* TestClock.adjust(Duration.seconds(1));
yield* TestClock.adjust(Duration.seconds(1));

yield* Deferred.await(ready);
assert.equal(yield* Ref.get(probes), readyAfterProbes);
yield* instance.stop();
}),
);

it.effect("notices a WSL backend soon after it listens despite slow refused connects", () =>
Effect.gen(function* () {
const ready = yield* Deferred.make<void>();
Expand Down
12 changes: 10 additions & 2 deletions apps/mobile/src/lib/threadActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ export interface ThreadFeedLatestRun {
readonly providerStartingLabel?: string;
readonly providerStartingLabelMsg?: string;
readonly providerStarting?: { readonly driver: string };
readonly awaitedEarlierSubagents?: number;
}

/** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */
Expand Down Expand Up @@ -1514,7 +1515,8 @@ function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLate
left.turnEnded === right.turnEnded &&
left.providerStartingLabel === right.providerStartingLabel &&
left.providerStartingLabelMsg === right.providerStartingLabelMsg &&
left.providerStarting?.driver === right.providerStarting?.driver)
left.providerStarting?.driver === right.providerStarting?.driver &&
left.awaitedEarlierSubagents === right.awaitedEarlierSubagents)
);
}

Expand Down Expand Up @@ -2022,7 +2024,13 @@ export function deriveThreadFeedPresentation(
const waitingOn =
activeRunId === null
? 0
: countSubagentsBlockingRun(feed, activeRunId, feedEntryTurnItems, !zen);
: countSubagentsBlockingRun(
feed,
activeRunId,
feedEntryTurnItems,
!zen,
latestRun?.awaitedEarlierSubagents,
);
result.push(
thinkingRow(
activeWorkStartedAt,
Expand Down
18 changes: 18 additions & 0 deletions apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1532,6 +1532,7 @@ describe("source control tools", () => {
thread: branchThread,
pullRequests: {
diff: (input) => Effect.succeed(pages[input.cursor ?? "first"]!),
summary: () => Effect.succeed({ state: "open", headSha: "fed9876" } as never),
submitReview: (input) => Effect.sync(() => void reviews.push(input)),
},
});
Expand Down Expand Up @@ -1567,6 +1568,23 @@ describe("source control tools", () => {
})
.pipe(Effect.flip);
expect(error.message).toContain("a.ts line 40 (new side) is not in this PR's diff");
// Pinned to a head that moved, the line is gone because of the new commits.
const moved = yield* harness
.call("pull_request_review", {
verdict: "comment",
expectedHeadSha: "abc1234",
comments: [{ path: "a.ts", line: 40, body: "Here?" }],
})
.pipe(Effect.flip);
expect(moved.message).toContain("The head is now fed9876, not abc1234");
const current = yield* harness
.call("pull_request_review", {
verdict: "comment",
expectedHeadSha: "fed9876",
comments: [{ path: "a.ts", line: 40, body: "Here?" }],
})
.pipe(Effect.flip);
expect(current.message).toContain("a.ts line 40 (new side) is not in this PR's diff");
expect(reviews).toHaveLength(1);
}),
);
Expand Down
18 changes: 15 additions & 3 deletions apps/server/src/mcp/toolkits/pullRequests/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
TrimmedNonEmptyString,
pullRequestConversationThreads,
} from "@onicode/contracts";
import { isHeadSha } from "@onicode/shared/git";
import * as Cause from "effect/Cause";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
Expand Down Expand Up @@ -450,8 +451,7 @@ const make = Effect.gen(function* () {
const headSha =
layer.number !== ref.number
? layer.headSha
: layer.headSha !== undefined &&
PullRequestService.isHeadSha(layer.headSha, input.expectedHeadSha)
: layer.headSha !== undefined && isHeadSha(layer.headSha, input.expectedHeadSha)
? layer.headSha
: input.expectedHeadSha;
if (headSha === undefined)
Expand Down Expand Up @@ -487,6 +487,7 @@ const make = Effect.gen(function* () {
const reviewComments = Effect.fn("PullRequestsToolkit.reviewComments")(function* (
ref: PullRequestRef,
comments: ReadonlyArray<ReviewLineComment>,
expectedHeadSha: string | undefined,
) {
const placed = new Map<ReviewLineComment, PullRequestReviewCommentDraft>();
const unplaced = () => comments.filter((comment) => !placed.has(comment));
Expand Down Expand Up @@ -515,6 +516,17 @@ const make = Effect.gen(function* () {
}
const missing = unplaced()[0];
if (missing !== undefined) {
// A line can be missing because the head moved, which the agent fixes by reading it again.
if (expectedHeadSha !== undefined) {
const { headSha } = yield* pullRequests
.summary(ref, { bypassCache: true })
.pipe(Effect.mapError(forgeFailure));
if (headSha !== undefined && !isHeadSha(headSha, expectedHeadSha)) {
return yield* new PullRequestForgeError({
detail: `The head is now ${headSha}, not ${expectedHeadSha}. Review the new commits first.`,
});
}
}
return yield* new PullRequestForgeError({
detail: `${missing.path} line ${missing.startLine ?? missing.line} (${missing.side ?? "new"} side) is not in this PR's diff. Comment on a changed line or one shown around it.`,
});
Expand Down Expand Up @@ -1210,7 +1222,7 @@ const make = Effect.gen(function* () {
});
}
const { target, ref } = yield* locate(input);
const comments = yield* reviewComments(ref, input.comments ?? []);
const comments = yield* reviewComments(ref, input.comments ?? [], input.expectedHeadSha);
yield* pullRequests
.submitReview({
...ref,
Expand Down
180 changes: 180 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import {
import { MAX_AGENT_TERMINAL_OUTPUT_CHARS } from "@onicode/provider-acp/server/runtimeModel";
import {
extractXAiAcpSubagentUpdate,
extractXAiAwaitedSubagentIds,
makeGrokAdapterV2,
makeXAiPromptCompletionRuntime,
normalizeXAiAcpToolCallState,
Expand Down Expand Up @@ -11059,6 +11060,185 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);

it.effect.each([
{ ends: "the poll returns", end: "returns", untilMarker: [true, false, true, "marker"] },
{
ends: "the prompt ends inside the poll",
end: "inside",
untilMarker: [true, false, "marker"],
},
{
ends: "the poll drops its timeout",
end: "untimed",
untilMarker: [true, false, true, "marker"],
},
] as const)(
"marks a Grok child awaited only while a blocking poll names it, until $ends",
({ end, untilMarker }) =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const selfInvocation = yield* resolveSelfInvocation();
const mockAgentPath = yield* bundledMockAgentPath;
const instanceId = ProviderInstanceId.make("acp-grok-poll");
const threadId = ThreadId.make("thread-acp-grok-poll");
const childSessionId = "019f44a6-4820-7402-925d-bc862ee71200";
type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
const poll = (toolCallId: string, rawInput: Record<string, unknown>) =>
sessionUpdateHandler!({
sessionId: "mock-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_ids: [childSessionId], ...rawInput },
},
});
const pollReturned = (toolCallId: string) =>
sessionUpdateHandler!({
sessionId: "mock-session-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId,
status: "completed",
rawOutput: { type: "Text", text: "Status: running" },
},
});
const adapter = yield* makeAcpAdapterV2({
instanceId,
selfInvocation,
continuationRequests: { offer: () => Effect.void },
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
extractSubagentUpdate: extractXAiAcpSubagentUpdate,
extractSubagentWait: extractXAiAwaitedSubagentIds,
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath,
wrapRuntime: (runtime) => ({
...runtime,
handleSessionUpdate: (handler) =>
Effect.sync(() => {
sessionUpdateHandler = handler;
}).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
prompt: () =>
Effect.gen(function* () {
yield* sessionUpdateHandler!({
sessionId: "mock-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-spawn",
title: "spawn_subagent",
kind: "other",
status: "completed",
rawInput: { description: "Researcher", prompt: "Research" },
rawOutput: {
type: "Text",
text: `Subagent started in background.\nsubagent_id: ${childSessionId}`,
},
},
});
// Without a timeout the poll only reads the child's status.
yield* poll("tool-call-peek", {});
yield* pollReturned("tool-call-peek");
yield* poll("tool-call-wait", { timeout_ms: 15_000 });
if (end === "untimed") {
yield* sessionUpdateHandler!({
sessionId: "mock-session-1",
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-wait",
status: "in_progress",
rawInput: { task_ids: [childSessionId], timeout_ms: 0 },
},
});
}
if (end === "returns") yield* pollReturned("tool-call-wait");
yield* sessionUpdateHandler!({
sessionId: "mock-session-1",
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-marker",
title: "Read",
kind: "read",
status: "completed",
rawInput: { path: "README.md" },
},
});
return { stopReason: "end_turn" as const };
}),
}),
}),
},
});
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-grok-poll"),
modelSelection,
runtimePolicy,
});
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
yield* runtime.events.pipe(
Stream.runForEach((event) => Queue.offer(events, event)),
Effect.forkScoped,
);
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const turnInput = makeTurnInput({
threadId,
providerThread,
instanceId,
runtimePolicy,
now: yield* DateTime.now,
});
yield* runtime.startTurn(turnInput);
const seen: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
while (seen.at(-1)?.type !== "turn.terminal") seen.push(yield* Queue.take(events));
// Each change, in order; a status update may re-emit the same value.
const changes = <A>(values: ReadonlyArray<A>) =>
values.filter((value, index) => index === 0 || values[index - 1] !== value);
assert.deepEqual(
changes(
seen.flatMap((event) =>
event.type === "turn_item.updated" && event.turnItem.type === "subagent"
? [event.turnItem.background]
: [],
),
),
[true, false, true],
);
assert.deepEqual(
changes(
seen.flatMap((event) =>
event.type === "subagent.updated" ? [event.subagent.awaitedByRunId] : [],
),
),
[undefined, turnInput.runId, undefined],
);
// The marker tool comes after the poll section, before the turn ends.
const trace = changes(
seen.flatMap((event): Array<boolean | "marker"> => {
if (event.type !== "turn_item.updated") return [];
if (event.turnItem.type === "subagent") return [event.turnItem.background ?? false];
return event.turnItem.nativeItemRef?.nativeId === "tool-call-marker" ? ["marker"] : [];
}),
);
assert.deepEqual(trace.slice(0, trace.indexOf("marker") + 1), [...untilMarker]);
}).pipe(Effect.provide(layerTest), Effect.scoped),
);

it.effect(
"user attach flushes a deferred terminal but leaves wake traffic for its continuation",
() =>
Expand Down
Loading