Skip to content

Commit 9e22c87

Browse files
Merge branch 'main' into fix/issue-16355
2 parents 6447cb9 + 689bdb8 commit 9e22c87

36 files changed

Lines changed: 1709 additions & 158 deletions

‎apps/mobile/src/features/threads/thread-work-log.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -937,13 +937,14 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
937937
const warning = failureItem.failure.class === "usage_limit";
938938
const timestamp = new Date(row.createdAt);
939939
const resetAt = failureItem.failure.resetAt;
940+
// The reset time is the viewer's local time; naming the zone keeps it unambiguous.
940941
const resetTime = resetAt
941-
? new Date(resetAt).toLocaleString(undefined, {
942+
? `${new Date(resetAt).toLocaleString(undefined, {
942943
month: "short",
943944
day: "numeric",
944945
hour: "numeric",
945946
minute: "2-digit",
946-
})
947+
})} (${new Intl.DateTimeFormat().resolvedOptions().timeZone})`
947948
: null;
948949
const label = warning
949950
? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}`

‎apps/server/src/mcp/PreviewAutomationBroker.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,43 @@ it.effect.each([
335335
),
336336
);
337337

338+
it.effect("names the click target that matched nothing when the server browser times out", () =>
339+
Effect.scoped(
340+
Effect.gen(function* () {
341+
const broker = yield* makeBroker;
342+
const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
343+
const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
344+
yield* Stream.runForEach(requests, (request) =>
345+
broker.respond({
346+
clientId,
347+
connectionId: request.connectionId,
348+
requestId: request.requestId,
349+
ok: false,
350+
error: {
351+
_tag: "PreviewAutomationTimeoutError",
352+
message: "No element matches the target.",
353+
detail: { reason: 'No element matches ".definitely-no-such-t3-target".' },
354+
},
355+
}),
356+
).pipe(Effect.forkScoped);
357+
yield* Effect.yieldNow;
358+
359+
const error = yield* broker
360+
.invoke<void>({
361+
scope,
362+
operation: "click",
363+
input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 },
364+
})
365+
.pipe(Effect.flip);
366+
367+
expect(error._tag).toBe("PreviewAutomationTimeoutError");
368+
expect(error.message).toBe(
369+
'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".',
370+
);
371+
}),
372+
),
373+
);
374+
338375
it.effect("distinguishes malformed remote failures", () =>
339376
Effect.scoped(
340377
Effect.gen(function* () {

‎apps/server/src/mcp/PreviewAutomationBroker.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,14 @@ const readRemoteTimeoutMs = (detail: unknown): number | undefined => {
205205
: undefined;
206206
};
207207

208+
const readRemoteReason = (detail: unknown): string | undefined =>
209+
typeof detail === "object" &&
210+
detail !== null &&
211+
"reason" in detail &&
212+
typeof detail.reason === "string"
213+
? detail.reason
214+
: undefined;
215+
208216
const MAX_REASON_CHARS = 500;
209217

210218
const classifyResponseError = (
@@ -255,9 +263,13 @@ const classifyResponseError = (
255263
});
256264
case "PreviewAutomationTimeoutError": {
257265
const remoteTimeoutMs = readRemoteTimeoutMs(error.detail);
266+
const remoteReason = readRemoteReason(error.detail);
258267
return new PreviewAutomationTimeoutError({
259268
...context,
260269
...remoteDiagnostics,
270+
...(context.clientId === SERVER_BROWSER_AUTOMATION_CLIENT_ID && remoteReason !== undefined
271+
? { reason: remoteReason.slice(0, MAX_REASON_CHARS) }
272+
: {}),
261273
...(remoteTimeoutMs === undefined
262274
? {}
263275
: { timeoutMs: Math.min(context.timeoutMs, remoteTimeoutMs) }),

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11432,6 +11432,86 @@ describe("ClaudeAdapterV2 background wake turns", () => {
1143211432
),
1143311433
);
1143411434

11435+
it.effect("settles a continuation whose wake turn a user turn absorbed", () =>
11436+
Effect.scoped(
11437+
Effect.gen(function* () {
11438+
const harness = yield* makeWakeHarness;
11439+
const now = yield* DateTime.now;
11440+
11441+
yield* harness.runtime.startTurn(
11442+
makeClaudeTestTurnInput({
11443+
threadId: harness.threadId,
11444+
providerThread: harness.providerThread,
11445+
now,
11446+
attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-1"),
11447+
text: "Run the build in the background.",
11448+
attachments: [],
11449+
}),
11450+
);
11451+
yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
11452+
yield* Queue.offer(harness.sdkMessages, wakeNotification);
11453+
yield* Queue.offer(harness.sdkMessages, turnOneResult);
11454+
yield* harness.awaitTerminal(1);
11455+
yield* harness.offerAndWait(wakeTurnInit);
11456+
yield* harness.offerAndWait(wakeAssistant);
11457+
yield* harness.awaitContinuation(1);
11458+
11459+
// Claude folds this prompt into the wake turn it already opened, so one result ends both.
11460+
yield* harness.runtime.startTurn(
11461+
makeClaudeTestTurnInput({
11462+
threadId: harness.threadId,
11463+
providerThread: harness.providerThread,
11464+
now,
11465+
attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-2"),
11466+
text: "Any update on the pull request?",
11467+
attachments: [],
11468+
providerTurnOrdinal: 2,
11469+
}),
11470+
);
11471+
yield* harness.until(() => harness.offeredMessages.length === 2);
11472+
yield* Queue.offer(
11473+
harness.sdkMessages,
11474+
makeResultFrame({
11475+
uuid: "00000000-0000-4000-8000-000000000140",
11476+
result: "Checks passed and the pull request is up to date.",
11477+
}),
11478+
);
11479+
yield* harness.awaitTerminal(2);
11480+
11481+
yield* harness.runtime.startTurn(
11482+
makeClaudeTestTurnInput({
11483+
threadId: harness.threadId,
11484+
providerThread: harness.providerThread,
11485+
now,
11486+
attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-3"),
11487+
text: "Background task completed.",
11488+
attachments: [],
11489+
providerTurnOrdinal: 3,
11490+
messageCreatedBy: "agent",
11491+
messageCreationSource: "provider",
11492+
}),
11493+
);
11494+
yield* harness.awaitTerminal(3);
11495+
assert.equal(harness.terminalEvents()[2]?.status, "completed");
11496+
assert.isTrue(
11497+
harness.events.some(
11498+
(event) =>
11499+
event.type === "message.updated" && event.message.text === WAKE_ASSISTANT_TEXT,
11500+
),
11501+
);
11502+
}).pipe(
11503+
Effect.provide(
11504+
Layer.mergeAll(
11505+
IdAllocator.layer,
11506+
McpProviderSessions.layer,
11507+
NodeServices.layer,
11508+
NodeCrypto.layer,
11509+
),
11510+
),
11511+
),
11512+
),
11513+
);
11514+
1143511515
it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () =>
1143611516
Effect.scoped(
1143711517
Effect.gen(function* () {

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 92 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ import * as Context from "effect/Context";
123123
import * as SecureRandom from "effect/crypto/SecureRandom";
124124
import * as DateTime from "effect/DateTime";
125125
import * as Deferred from "effect/Deferred";
126+
import * as Duration from "effect/Duration";
126127
import * as Effect from "effect/Effect";
127128
import * as Equal from "effect/Equal";
128129
import * as Exit from "effect/Exit";
@@ -338,6 +339,13 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500;
338339
const BACKGROUND_MOVE_TIMEOUT_MS = 5_000;
339340
// How long a Stop waits for the CLI to exit before the user is offered Force stop.
340341
const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
342+
// Matches the stderr tail the SDK keeps for a CLI it spawns itself.
343+
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
344+
// The process group is killed on exit, so its stderr closes promptly.
345+
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
346+
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
347+
const CLAUDE_ROOT_REFUSAL =
348+
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
341349

342350
const CLAUDE_GROUP_WATCH_SCRIPT = [
343351
"{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } </dev/null >/dev/null 2>&1 &",
@@ -352,6 +360,8 @@ const CLAUDE_GROUP_WATCH_SCRIPT = [
352360
export function spawnClaudeProcessGroup(
353361
options: ClaudeSpawnOptions,
354362
onExit?: () => void,
363+
onStderr: (text: string) => void = () => {},
364+
onStderrClose: () => void = () => {},
355365
): ClaudeSpawnedProcess {
356366
const child = NodeChildProcess.spawn(
357367
"/bin/sh",
@@ -360,10 +370,12 @@ export function spawnClaudeProcessGroup(
360370
cwd: options.cwd,
361371
env: options.env,
362372
signal: options.signal,
363-
stdio: ["pipe", "pipe", "ignore", "pipe"],
373+
stdio: ["pipe", "pipe", "pipe", "pipe"],
364374
detached: true,
365375
},
366376
);
377+
// Always drained, so a chatty CLI never blocks on a full stderr pipe.
378+
child.stderr?.setEncoding("utf8").on("data", onStderr).once("close", onStderrClose);
367379
child.once("exit", () => {
368380
try {
369381
signalProcessGroup(child.pid ?? 0, "SIGKILL");
@@ -558,6 +570,17 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError<ClaudeAge
558570
}
559571
}
560572

573+
export class ClaudeCodeRootRefusalError extends Schema.TaggedError<ClaudeCodeRootRefusalError>()(
574+
"ClaudeCodeRootRefusalError",
575+
{
576+
cause: Schema.Defect(),
577+
},
578+
) {
579+
override get message(): string {
580+
return `Claude Code exited before it started: ${CLAUDE_ROOT_REFUSAL}`;
581+
}
582+
}
583+
561584
class ClaudeMcpRegistrationTimeoutError extends Schema.TaggedError<ClaudeMcpRegistrationTimeoutError>()(
562585
"ClaudeMcpRegistrationTimeoutError",
563586
{},
@@ -1009,10 +1032,25 @@ export const layerQueryRunner: Layer.Layer<
10091032
const unit = launch?.unit;
10101033
const stopScope =
10111034
unit === undefined ? undefined : () => void runFork(agentScope.stop(unit));
1035+
// Only a CLI that fails before its first message explains itself on
1036+
// stderr. The known root refusal becomes a curated failure; any other
1037+
// stderr can hold private text, so it stays out of turn failures.
1038+
let stderrTail = "";
1039+
let stderrClosed: Promise<void> = Promise.resolve();
1040+
let answered = false;
1041+
const appendStderr = (text: string) => {
1042+
if (answered) return;
1043+
stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
1044+
};
10121045
const spawnProcess =
10131046
options.spawnClaudeCodeProcess ??
10141047
((spawnOptions: ClaudeSpawnOptions) => {
1015-
if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope);
1048+
if (platform !== "win32") {
1049+
// Node can report "exit" before it has read the stderr the CLI wrote.
1050+
let stderrDone = () => {};
1051+
stderrClosed = new Promise((resolve) => (stderrDone = resolve));
1052+
return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone);
1053+
}
10161054
const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
10171055
cwd: spawnOptions.cwd,
10181056
env: spawnOptions.env,
@@ -1132,9 +1170,31 @@ export const layerQueryRunner: Layer.Layer<
11321170
);
11331171

11341172
return {
1135-
messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) =>
1136-
queryRunnerError(cause, "fromAsyncIterable"),
1173+
messages: Stream.fromAsyncIterable(
1174+
claudeQueryMessages(queryRuntime),
1175+
(cause) => cause,
11371176
).pipe(
1177+
Stream.catch((cause) =>
1178+
Stream.fromEffect(
1179+
Effect.gen(function* () {
1180+
if (!answered) {
1181+
yield* Effect.promise(() => stderrClosed).pipe(
1182+
Effect.timeoutOption(CLAUDE_STDERR_DRAIN_TIMEOUT),
1183+
);
1184+
}
1185+
const refusedRoot = !answered && stderrTail.includes(CLAUDE_ROOT_REFUSAL);
1186+
return yield* queryRunnerError(
1187+
refusedRoot ? new ClaudeCodeRootRefusalError({ cause }) : cause,
1188+
"fromAsyncIterable",
1189+
);
1190+
}),
1191+
),
1192+
),
1193+
Stream.tap(() =>
1194+
Effect.sync(() => {
1195+
answered = true;
1196+
}),
1197+
),
11381198
Stream.tap((message) =>
11391199
logProtocolEvent({
11401200
direction: "incoming",
@@ -5031,6 +5091,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
50315091
}
50325092
});
50335093
const requestedContinuations = yield* Ref.make(new Set<string>());
5094+
const absorbedWakes = yield* Ref.make(new Set<string>());
50345095
const heldProposedPlansByToolUseId = new Map<string, string>();
50355096
const runtimeContext = yield* Effect.context<never>();
50365097
const runPromise = Effect.runPromiseWith(runtimeContext);
@@ -5466,6 +5527,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
54665527
yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId);
54675528
});
54685529

5530+
const forgetAbsorbedWake = (nativeThreadId: string) =>
5531+
Ref.update(absorbedWakes, (current) => {
5532+
if (!current.has(nativeThreadId)) return current;
5533+
const updated = new Set(current);
5534+
updated.delete(nativeThreadId);
5535+
return updated;
5536+
});
5537+
54695538
const clearWakeStateForNativeThread =
54705539
/* Provider events include streaming deltas; avoid a span for each update. */
54715540
Effect.fnUntraced(function* (nativeThreadId: string) {
@@ -5486,8 +5555,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
54865555
updated.delete(nativeThreadId);
54875556
return updated;
54885557
});
5558+
yield* forgetAbsorbedWake(nativeThreadId);
54895559
});
54905560

5561+
// Claude runs one root turn at a time, so a user turn's result also ends a wake turn it
5562+
// folded in. The continuation replays that wake's buffered frames but gets no result of its own.
5563+
const markAbsorbedWake = Effect.fnUntraced(function* (nativeThreadId: string) {
5564+
const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
5565+
const lastResult = messages.findLastIndex((entry) => entry.type === "result");
5566+
if (!messages.slice(lastResult + 1).some(isClaudeRootTurnFrame)) return;
5567+
yield* Ref.update(absorbedWakes, (current) => new Set(current).add(nativeThreadId));
5568+
});
5569+
54915570
// The SDK emits no initial roster; reset roster and wake eligibility when opening a live query.
54925571
const resetBackgroundTaskStateForNativeThreadProcess = Effect.fnUntraced(function* (
54935572
nativeThreadId: string,
@@ -8070,6 +8149,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
80708149
if (message.type === "result") {
80718150
bufferedResultArrivals.set(message, yield* DateTime.now);
80728151
}
8152+
if (isClaudeRootTurnFrame(message)) {
8153+
yield* forgetAbsorbedWake(wakeInput.nativeThreadId);
8154+
}
80738155
yield* Ref.update(wakeBuffers, (current) => {
80748156
const existing = current.get(wakeInput.nativeThreadId);
80758157
const updated = new Map(current);
@@ -9518,6 +9600,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
95189600
next.delete(context.providerTurnId);
95199601
return next;
95209602
});
9603+
if (!isClaudeProviderContinuationTurn(context.input)) {
9604+
yield* markAbsorbedWake(liveQuery.nativeThreadId);
9605+
}
95219606
const usageLimited =
95229607
context.authenticationFailureMessage === undefined &&
95239608
(context.rejectedRateLimitTypes.size > 0 ||
@@ -10815,6 +10900,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1081510900
updated.delete(nativeThreadId);
1081610901
return updated;
1081710902
});
10903+
const wakeAbsorbed = (yield* Ref.get(absorbedWakes)).has(nativeThreadId);
10904+
yield* forgetAbsorbedWake(nativeThreadId);
1081810905
if (drained.length === 0) {
1081910906
const completedAt = yield* DateTime.now;
1082010907
yield* finalizeActiveTurn({ context, status: "completed", completedAt });
@@ -10883,7 +10970,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
1088310970
yield* handleSdkMessage({ query: querySession.query, message: lastResult });
1088410971
return;
1088510972
}
10886-
if (hasOpaqueTaskNotification && !context.nativeWakeStarted) {
10973+
if (wakeAbsorbed || (hasOpaqueTaskNotification && !context.nativeWakeStarted)) {
1088710974
const completedAt = yield* DateTime.now;
1088810975
yield* finalizeActiveTurn({ context, status: "completed", completedAt });
1088910976
} else if (!context.nativeWakeStarted) {

0 commit comments

Comments
 (0)