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
177 changes: 152 additions & 25 deletions apps/desktop/src/main/services/chat/agentChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2067,6 +2067,8 @@ type CodexResumeFailureError = Error & {
resumeFailureClassification: ResumeFailureClassification;
/** The app-server's structured error `data`, carried past the rewrite of its message. */
data?: unknown;
/** The resume request itself hit its deadline: the process never answered. */
codexRequestTimeout?: true;
};

function isCodexResumeFailureError(error: unknown): error is CodexResumeFailureError {
Expand Down Expand Up @@ -2917,6 +2919,16 @@ function isCodexRequestTimeoutError(error: unknown): boolean {
return /^Codex request '.+' timed out after \d+ms\.$/.test(message);
}

/**
* A Codex app-server request hit its deadline, also when the raw timeout was
* wrapped in the resume failure ADE reports (`thread/resume`). The process
* stayed "ready" without answering, so nothing on it can be trusted.
*/
function isCodexAppServerUnresponsiveError(error: unknown): boolean {
return isCodexRequestTimeoutError(error)
|| (isCodexResumeFailureError(error) && error.codexRequestTimeout === true);
}

function rejectPendingCodexRequests(
pending: Map<string, PendingRpc>,
message: string,
Expand Down Expand Up @@ -6285,6 +6297,8 @@ type PreparedSendMessage = {
laneDirectiveKey?: string | null;
/** The epoch directives this turn's prompt carries, marked delivered after the run. */
epochDirectiveKeys?: EpochDirectiveKeys;
/** The epoch directives this prompt revokes; their delivery keys are forgotten after the run. */
revokedEpochDirectives?: EpochDirective[];
providerSlashCommand?: boolean;
forceClaudeUserMessage?: boolean;
onDispatched?: () => void;
Expand Down Expand Up @@ -10087,6 +10101,26 @@ function composeLaunchDirectives(baseText: string, directives: Array<string | nu
return `${filtered.join("\n\n")}\n\nUser request:\n${baseText}`;
}

/**
* The turn text that retracts an epoch directive whose capability is gone.
* These directives ride the conversation (for Codex, as user-turn items), so
* omitting the block later does not remove what the agent was already told;
* it keeps following the old instruction. One short correction says it is
* void, once, on the first turn after the change.
*/
function buildEpochDirectiveRevocation(kind: EpochDirective): string {
switch (kind) {
case "computerUse":
return "ADE computer use is not available in this session now. Earlier computer-use instructions no longer apply.";
case "laneScreen":
return "This lane has no private screen now. Earlier lane-screen instructions no longer apply.";
case "laneDevices":
return "ADE: the lane device last announced is no longer bound. Earlier <ade-lane-tools> instructions no longer apply: this lane has no Apple device or Android emulator. Create one with `ade apple start` or `ade android device-create` if this chat needs it.";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Invalid Android device replacement command

After detachment, buildEpochDirectiveRevocation gives the agent a creation command that the Android CLI rejects without --profile or --catalog.

Suggested change
return "ADE: the lane device last announced is no longer bound. Earlier <ade-lane-tools> instructions no longer apply: this lane has no Apple device or Android emulator. Create one with `ade apple start` or `ade android device-create` if this chat needs it.";
return "ADE: the lane device last announced is no longer bound. Earlier <ade-lane-tools> instructions no longer apply: this lane has no Apple device or Android emulator. Create one with `ade apple start` or `ade android device-create --profile <id>` if this chat needs it. List Android profiles with `ade android devices --profiles`.";

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

case "laneGuidance":
return "ADE's guidance for this session changed. Earlier guidance no longer applies.";
}
}

/**
* Materialize a session's attached Linear issues into a per-session context
* file the spawned agent (ADE chat or CLI) can read without Linear creds, and
Expand Down Expand Up @@ -30538,6 +30572,15 @@ export function createAgentChatService(args: {
* defers forever.
*/
deadCodexRuntime?: "turn_imminent" | "settle";
/**
* Codex: a request on this app-server hit its deadline without an answer
* (turn/start, thread/start or thread/resume), so the process is
* presumed stuck. A private one, or the last chat on a shared one, is
* stopped; a shared one other chats are still using is retired from the
* pool instead. The chat's thread pointer is kept, so its delivered
* epoch directives are kept too: the resumed thread still holds them.
*/
codexAppServerUnresponsive?: boolean;
},
): void => {
runtimeTeardownEpochs.set(managed, runtimeTeardownEpoch(managed) + 1);
Expand Down Expand Up @@ -30595,8 +30638,13 @@ export function createAgentChatService(args: {
// next send resumes that thread (a failed resume throws rather than opening
// a new one). The resumed thread already holds the lane and computer-use
// directives; forgetting them re-sent ~10k chars on every idle restart.
// A process retired for silence is the same case: the pointer survives, so
// the old thread still holds its directives and must keep their keys, or a
// capability that disappeared is never revoked (`revokedEpochDirectives`).
const preserveDeliveredDirectives = preserveProviderResumeState
|| (managed.runtime.kind === "codex" && reasonAllowsPreservation && Boolean(managed.session.threadId));
|| (managed.runtime.kind === "codex"
&& (reasonAllowsPreservation || options?.codexAppServerUnresponsive === true)
&& Boolean(managed.session.threadId));
if (managed.runtime.kind === "codex") {
const runtime = managed.runtime;
failOpenCodexCompactions(managed, runtime, "teardown");
Expand All @@ -30607,7 +30655,7 @@ export function createAgentChatService(args: {
&& !managed.deleted;
runtime.suppressExitError = true;
clearCodexNoFirstEventWatchdog(managed);
if (!releaseCodexRuntimeHost(managed, runtime)) {
if (!releaseCodexRuntimeHost(managed, runtime, { unresponsive: options?.codexAppServerUnresponsive === true })) {
try { runtime.reader.close(); } catch { /* ignore */ }
runtime.killTimer = terminateChildProcessTree(
runtime.process,
Expand Down Expand Up @@ -47493,17 +47541,34 @@ export function createAgentChatService(args: {
* the chat's running turn is interrupted and its threads unsubscribed, so
* nothing of it keeps running unseen; a process that cannot answer that is
* presumed stuck and stopped, and every chat on it recovers as from a crash.
*/
const releaseCodexRuntimeHost = (managed: ManagedChatSession | null, runtime: CodexRuntime): boolean => {
* `unresponsive` says a request already hit its deadline with no answer:
* the process is presumed stuck, so on a private one (or the last chat on a
* shared one) it is stopped at once, without waiting out the release
* requests on a server known to be silent. A shared process other chats are
* still using is not stopped: one chat's deadline can be a slow machine, and
* killing it would fail their live turns. It is retired from the pool
* instead, so no new chat joins it, and stops with its last chat.
*/
const releaseCodexRuntimeHost = (
managed: ManagedChatSession | null,
runtime: CodexRuntime,
options?: { unresponsive?: boolean },
): boolean => {
const seat = codexHostByRuntime.get(runtime);
if (!seat) return false;
codexHostByRuntime.delete(runtime);
const { host, client } = seat;
const ownThreadId = managed?.session.threadId ?? null;
const turnId = runtime.activeTurnId ?? runtime.startedTurnId ?? null;
const threadIds = [ownThreadId, ...runtime.codexSubagentThreads.keys()].filter((id): id is string => Boolean(id));
const remaining = host.detach(client, threadIds);
if (options?.unresponsive) {
// `detach` already stopped a private process and the last chat's one.
if (remaining > 0) host.poison();
return true;
Comment on lines +47565 to +47568

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Old server blocks reconnection

When two chats share an app-server and one times out, this branch detaches that chat without unloading its thread. host.poison() only removes the server from the pool. The other chat keeps the old process alive, so it can retain the thread's writer lock. Retrying starts a fresh server, but resuming the original thread can fail because it still has an active writer.

Keep a bounded thread-release step before allowing that chat to resume elsewhere, and stop the old server if release fails.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/services/chat/agentChatService.ts
Line: 47565-47568

Comment:
**Old server blocks reconnection**

When two chats share an app-server and one times out, this branch detaches that chat without unloading its thread. `host.poison()` only removes the server from the pool. The other chat keeps the old process alive, so it can retain the thread's writer lock. Retrying starts a fresh server, but resuming the original thread can fail because it still has an active writer.

Keep a bounded thread-release step before allowing that chat to resume elsewhere, and stop the old server if release fails.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

}
// A process that already exited holds nothing to release.
if (host.detach(client, threadIds) === 0 || !threadIds.length || host.isGone()) return true;
if (remaining === 0 || !threadIds.length || host.isGone()) return true;
const release = (async () => {
if (ownThreadId && turnId) {
await host.request("turn/interrupt", { threadId: ownThreadId, turnId }, CODEX_SHARED_RELEASE_TIMEOUT_MS)
Expand Down Expand Up @@ -59725,10 +59790,10 @@ export function createAgentChatService(args: {
// on whether the capability set had changed since the agent was last told.
// It is now epoch-scoped like the lane directive, and re-sent whenever the
// available backends change, so a changed capability set is re-announced
// rather than repeated. A transition to NO available backend emits no
// directive at all (there is nothing to say), so a capability that is lost
// entirely is not revoked mid-session — the agent simply stops being told
// it is available on the next turn that re-announces.
// rather than repeated. A transition to NO available backend has no new
// directive to send; one short revocation says the old block is void (the
// turn text is conversation history, so omitting it later is not a
// retraction).
const computerUseDirective = personalSession ? null : currentComputerUseDirective();
const computerUseDirectiveKey = computerUseDirective
? `${laneDirectiveKey ?? "no-lane"}::${computerUseDirectiveFingerprint(computerUseDirective)}`
Expand All @@ -59745,23 +59810,36 @@ export function createAgentChatService(args: {
&& effectiveCursorRuntime(managed, runtime) === "cloud";
// The lane's Android emulator goes in the same block (one hint names both
// devices); an Apple-only lane keeps its text and key exactly.
// A lookup that throws returns null like "no device", but it says nothing
// about the device: a failed read must not revoke a hint that is still true.
// The two reads are tracked apart: a failed Apple read cannot explain an
// Android-only hint (nor the reverse), so the other platform's authoritative
// null still revokes it.
let laneAppleLookupFailed = false;
let laneAndroidLookupFailed = false;
const laneDevices = personalSession || cursorCloudTurn
? null
: resolveLaneDeviceDirective({
laneId: executionContext.laneId,
appleLookup: laneAppleDeviceLookup,
androidLookup: laneAndroidDeviceLookup,
shell: laneDirectiveShell,
onAppleLookupError: (error) => logger.warn("agent_chat.lane_apple_device_lookup_failed", {
sessionId,
laneId: executionContext.laneId,
error: error instanceof Error ? error.message : String(error),
}),
onAndroidLookupError: (error) => logger.warn("agent_chat.lane_android_device_lookup_failed", {
sessionId,
laneId: executionContext.laneId,
error: error instanceof Error ? error.message : String(error),
}),
onAppleLookupError: (error) => {
laneAppleLookupFailed = true;
logger.warn("agent_chat.lane_apple_device_lookup_failed", {
sessionId,
laneId: executionContext.laneId,
error: error instanceof Error ? error.message : String(error),
});
},
onAndroidLookupError: (error) => {
laneAndroidLookupFailed = true;
logger.warn("agent_chat.lane_android_device_lookup_failed", {
sessionId,
laneId: executionContext.laneId,
error: error instanceof Error ? error.message : String(error),
});
},
});
const shouldInjectLaneDevicesDirective = laneDevices != null
&& managed.deliveredDirectiveKeys.laneDevices !== laneDevices.key;
Expand All @@ -59775,6 +59853,41 @@ export function createAgentChatService(args: {
: null;
const shouldInjectLaneScreenDirective = laneScreenDirectiveKey != null
&& managed.deliveredDirectiveKeys.laneScreen !== laneScreenDirectiveKey;
// A Devin Cloud turn runs on a Devin VM: every directive below describes
// this machine (its worktree path, the `ade` CLI, computer use) and none of
// it exists there. Its only framing is the branch pin `runAcpTurn` adds.
const devinCloudPrompt = isDevinCloudAcpSession(managed.session);
// An epoch directive the provider thread already holds whose capability is
// gone now. The old block is conversation history, so leaving it out of
// this turn does not retract it; the revocation text says it is void.
const revokedEpochDirectives: EpochDirective[] = [];
if (!personalSession && !cursorCloudTurn && !providerSlashCommand && !devinCloudPrompt) {
if (computerUseDirectiveKey == null && managed.deliveredDirectiveKeys.computerUse != null) {
revokedEpochDirectives.push("computerUse");
}
if (laneDevices == null) {
// The delivered hint names the Apple device, the emulator or both, and
// its key says which. Only a failed read for a platform the hint names
// can hide a still-bound device in it; a failure for the other one
// leaves the delivered content fully explained by the reads that did
// answer, so the hint is revoked.
const deliveredLaneDeviceKey = managed.deliveredDirectiveKeys.laneDevices ?? null;
const deliveredHadApple = deliveredLaneDeviceKey != null
&& !deliveredLaneDeviceKey.startsWith("android:");
const deliveredHadAndroid = deliveredLaneDeviceKey != null
&& (deliveredLaneDeviceKey.startsWith("android:") || deliveredLaneDeviceKey.includes("|android:"));
if (
deliveredLaneDeviceKey != null
&& !(deliveredHadApple && laneAppleLookupFailed)
&& !(deliveredHadAndroid && laneAndroidLookupFailed)
) {
revokedEpochDirectives.push("laneDevices");
}
}
if (laneScreenDirectiveKey == null && managed.deliveredDirectiveKeys.laneScreen != null) {
revokedEpochDirectives.push("laneScreen");
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude never re-announces a capability after revocation

Medium Severity

In a Claude chat, the computer-use or lane-screen block can be carried by the system prompt instead of the turn text. If that capability disappears, a revocation goes into the turn text and the delivered key is deleted. If it later comes back with the same text, claudeSystemPromptCarries still returns true, so nothing is re-sent, yet the key is marked delivered. The model is left believing the last word: the capability is gone.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3ef4c1a. Configure here.

const expandedSlashCommandPrompt = providerSlashCommand && !personalSession
? expandAdeSlashCommand(managed, trimmed)
: null;
Expand All @@ -59788,10 +59901,6 @@ export function createAgentChatService(args: {
const slashCommandPromptWithMentions = expandedSlashCommandPrompt != null
? carryChatMentionBlocks(trimmed, expandedSlashCommandPrompt)
: null;
// A Devin Cloud turn runs on a Devin VM: every directive below describes
// this machine (its worktree path, the `ade` CLI, computer use) and none of
// it exists there. Its only framing is the branch pin `runAcpTurn` adds.
const devinCloudPrompt = isDevinCloudAcpSession(managed.session);
const promptText = devinCloudPrompt
? trimmed
: providerSlashCommand && !personalSession
Expand Down Expand Up @@ -59827,6 +59936,7 @@ export function createAgentChatService(args: {
? laneScreenDirective
: null,
shouldInjectLaneDevicesDirective ? laneDevices.directive : null,
...revokedEpochDirectives.map(buildEpochDirectiveRevocation),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Queued turns miss capability corrections

When Claude is busy, the queue stores preparedSteer.submittedText, dropping the composed prompt and its new corrections. deliverNextQueuedSteerInner then builds a fresh prompt without checking for lost capabilities. If a device is detached after its hint was delivered, the next queued turn gets no correction and can keep following the old device instructions. Share the correction logic with queued delivery and clear the keys only after that message is sent.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/services/chat/agentChatService.ts
Line: 59892

Comment:
**Queued turns miss capability corrections**

When Claude is busy, the queue stores `preparedSteer.submittedText`, dropping the composed prompt and its new corrections. `deliverNextQueuedSteerInner` then builds a fresh prompt without checking for lost capabilities. If a device is detached after its hint was delivered, the next queued turn gets no correction and can keep following the old device instructions. Share the correction logic with queued delivery and clear the keys only after that message is sent.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

contextAttachmentPrompt || null,
]);
const codexGoalTitleSeed = managed.session.provider === "codex" && isCodexGoalSlashInput(trimmed)
Expand Down Expand Up @@ -59886,6 +59996,7 @@ export function createAgentChatService(args: {
...(shouldInjectLaneDevicesDirective ? { laneDevices: laneDevices.key } : {}),
...(shouldInjectLaneScreenDirective ? { laneScreen: laneScreenDirectiveKey } : {}),
},
revokedEpochDirectives,
providerSlashCommand: personalSession ? false : providerSlashCommand === true,
forceClaudeUserMessage: managed.session.provider === "claude" && (providerSlashCommand == null || personalSession) && slashCommand != null,
...(runtime ? { runtime } : {}),
Expand Down Expand Up @@ -59937,8 +60048,8 @@ export function createAgentChatService(args: {
managed.runtime.agentMessagePhaseByItemId.clear();
managed.runtime.recentNotificationKeys.clear();
managed.runtime.reconciledItemSignaturesByTurn.clear();
if (isCodexRequestTimeoutError(error)) {
teardownRuntime(managed, "handle_close");
if (isCodexAppServerUnresponsiveError(error)) {
teardownRuntime(managed, "handle_close", { codexAppServerUnresponsive: true });
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
Comment on lines +60051 to 60053

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Codex recovery reuses the wedged server

When a recovery request times out, recoverContinuity bypasses emitManagedSendFailure. The next recovery attempt reuses the same unresponsive server and times out again.

Learn more

The chat's runtime holds a seat on its Codex process. Normal sends retire the process through the managed send failure handler, but the recovery card's Try again action calls recoverContinuity directly. Its original-thread retry classifies the error and restores the card without retiring the process. Its history reconstruction similarly catches a thread/start timeout before it reaches ordinary send handling. ensureCodexSessionRuntime hands those flows the existing runtime while the process is still alive.

Example: After a chat requires recovery, the user clicks Try again. The Codex process stays alive but never answers thread/resume. A second click sends another resume to that process and hits the same deadline.

Recommended fix: Retire the host that owns a timed-out lifecycle request at the request boundary, or explicitly handle those timeouts in both recovery branches. Preserve recovery rollback and the original thread pointer; do not emit an ordinary turn failure for a recovery operation that never dispatched a turn.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}
if (managed.runtime?.kind === "opencode" && !isBusyError) {
Expand Down Expand Up @@ -60230,6 +60341,10 @@ export function createAgentChatService(args: {
code: "provider_thread_resume_failed" as const,
resumeFailureClassification: classification,
data: asRecord(error)?.data,
// The message rewrite above hides the raw timeout shape from
// `isCodexRequestTimeoutError`; keep the fact, so the caller can retire
// an app-server that never answered instead of reusing it.
...(isCodexRequestTimeoutError(error) ? { codexRequestTimeout: true as const } : {}),
},
);
};
Expand Down Expand Up @@ -66118,6 +66233,7 @@ export function createAgentChatService(args: {
reasoningEffort,
laneDirectiveKey,
epochDirectiveKeys,
revokedEpochDirectives,
providerSlashCommand,
forceClaudeUserMessage,
steerId,
Expand Down Expand Up @@ -66191,6 +66307,10 @@ export function createAgentChatService(args: {
&& managed.directiveDispatchGeneration !== (managed.directiveEpochGeneration ?? 0)
) return;
Object.assign(managed.deliveredDirectiveKeys, epochDirectiveKeys);
// A revocation this turn delivered is done: forgetting the old key now
// keeps it from being repeated (and only now, after the run, so a failed
// send leaves the key and retries the revocation next turn).
for (const kind of revokedEpochDirectives ?? []) delete managed.deliveredDirectiveKeys[kind];
Comment on lines +66310 to +66313

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Undelivered revocations are forgotten

markEpochDirectivesDelivered forgets revocations after a skipped Cursor /compact or an OpenCode prompt rejection. Cursor compaction omits the prompt, and OpenCode returns normally after reporting the rejection. The next message does not retry the revocation.

Learn more

The dispatch wrapper treats a normal return as proof of prompt delivery. The Cursor dispatch branch runs that callback for /compact, even though the Cursor worker calls summarize() instead of sending the composed prompt and can skip compaction without running anything. The OpenCode dispatch branch also runs the callback when runTurn handles an admission failure and returns. Neither outcome delivers the revocation, but both can remove the old delivery key.

Example: A local Cursor chat previously received an emulator hint. The user detaches the emulator and runs /compact after a cut-off run. Cursor skips the compaction; the next ordinary message lacks the revocation even though Cursor never received it.

Recommended fix: Commit revocations only when the provider confirms admission of the composed user prompt. Exclude summarize-only runs and preserve the old keys on pre-admission failure.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

};

const sessionPresetTiers = sessionPresetReasoningTiers(managed);
Expand Down Expand Up @@ -71589,6 +71709,13 @@ export function createAgentChatService(args: {
} catch (error) {
const classifiedError = codexResumeFailureError(managed, originalThreadId, error);
const classification = classifiedError.resumeFailureClassification;
// The retry met an app-server that never answered, exactly as a send
// does (`emitManagedSendFailure`). Retire it here too: otherwise the
// pool hands the same silent process back, and every "Try again"
// waits out the same deadline without the process ever changing.
if (isCodexAppServerUnresponsiveError(classifiedError) && managed.runtime?.kind === "codex") {
teardownRuntime(managed, "handle_close", { codexAppServerUnresponsive: true });
}
if (!managed.session.continuityRecovery) {
managed.session.continuityRecovery = {
state: "required",
Expand Down
Loading
Loading