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
52 changes: 48 additions & 4 deletions src/handlers/background-tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,25 @@ export class BackgroundTaskListener implements EventListener {
}
}

/** True while a rewind command's replacement-turn claim is still open. */
hasActiveRewindClaim(): boolean {
return this.rewindClaimAt !== null;
}

/** Clear rewind-claim and notification-turn forwarding state after an
* explicit user cancel on a session with no pendingTurns entry. */
clearRewindAndNotifyState(): void {
this.rewindClaimAt = null;
this.rewindClaimToken = null;
if (this.rewindClaimTimer) {
clearTimeout(this.rewindClaimTimer);
this.rewindClaimTimer = null;
}
this.activeNotifyTurnId = null;
this.windowTurnId = null;
this.firstMessageId = null;
}

/**
* True while at least one subagent background task is still running: the
* held-prompt turn loop keeps `session/prompt` open for exactly this work
Expand Down Expand Up @@ -627,7 +646,16 @@ export class BackgroundTaskListener implements EventListener {
// Foreign-turn running state (upstream taskActivityTracker parity):
// a turn.started from ANY source — background_task wake, subagent_message,
// control-only — marks the session running for every consumer that has
// no turn loop of its own to derive it from.
// no turn loop of its own to derive it from. Skip detached compaction's
// internal turn: compaction already owns busy state via
// `autoCompactInFlight`, and recording it in `foreignActiveTurns` would
// bypass the cancel guard and let ESC kill compaction.
if (
inputSource !== "background_task" &&
this.server.autoCompactInFlight?.has(this.zcodeSid)
) {
return;
}
this.trackForeignTurn(turnId, true);
return;
}
Expand Down Expand Up @@ -1031,11 +1059,27 @@ export class BackgroundTaskListener implements EventListener {
): void {
if (task.terminalPushed || p.taskKind === "workflow") return;
task.terminalPushed = true;
const acpSid = this.server.acpSidByZcodeSid?.get(this.zcodeSid);
const label = pushSourceLabel(this.server, acpSid);
const desc = task.description.trim();
const rawDetail = p.status && p.status !== "running" ? p.status : acpStatus;
if (isSubagentTask(task)) {
const title =
acpStatus === "completed"
? "subagent completed"
: rawDetail !== "failed"
? `subagent ${rawDetail}`
: "subagent failed";
const body = desc ? `${desc} · ${rawDetail}` : rawDetail;
pushSettled(this.server, { kind: "task", label, title, body });
return;
}
const statusLine = exitCode !== undefined ? `exit ${exitCode} · ${acpStatus}` : rawDetail;
pushSettled(this.server, {
kind: "task",
label: pushSourceLabel(this.server),
title: "background task done",
body: exitCode !== undefined ? `exit ${exitCode} · ${acpStatus}` : acpStatus,
label,
title: acpStatus === "completed" ? "background task done" : "background task failed",
body: desc ? `${desc} · ${statusLine}` : statusLine,
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/handlers/rewind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ async function runRewind(
zcodeSid: string,
buildRequest: (snapshot: RowsRangeSnapshot) => RewindRequest,
): Promise<Record<string, unknown>> {
const listener = await server.ensureBackgroundListener(zcodeSid);
const listener = await server.ensureBackgroundListener(zcodeSid, { subscribe: true });
let accepted = false;
let claimToken: number | null = null;
await emitSessionTurnState(server, acpSid, true);
Expand Down
49 changes: 45 additions & 4 deletions src/handlers/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1939,7 +1939,7 @@ export async function resumeSession(
// above); without this, a loaded session has no readable root.
server.sessionCwds.set(acpSid, cwd);
log(`session/resume -> ${zcodeSid}`);
await server.ensureBackgroundListener(zcodeSid);
await server.ensureBackgroundListener(zcodeSid, { subscribe: true });
await adoptStoredTitle(server, acpSid, zcodeSid);
// Martty's /resume rides session/resume (no history by ACP design) and only
// folds updates addressed to a session id it has already adopted — i.e.
Expand Down Expand Up @@ -2122,7 +2122,7 @@ export async function resumeIntoSession(
const finalCwd = backendWs && !server.serveMode ? backendWs : cwd;
server.sessionCwds.set(acpSid, finalCwd);
recordMaterializedSession(acpSid, zcodeTarget, finalCwd);
await server.ensureBackgroundListener(zcodeTarget);
await server.ensureBackgroundListener(zcodeTarget, { subscribe: true });
await adoptStoredTitle(server, acpSid, zcodeTarget);
} catch (e) {
warn(`/resume: adopting ${zcodeTarget} failed (${e instanceof Error ? e.message : String(e)})`);
Expand Down Expand Up @@ -2370,7 +2370,7 @@ export async function loadSession(
// Same as resumeSession: backend-authoritative session root for file access.
server.sessionCwds.set(acpSid, cwd);
log(`session/load → ${zcodeSid}`);
await server.ensureBackgroundListener(zcodeSid);
await server.ensureBackgroundListener(zcodeSid, { subscribe: true });
await adoptStoredTitle(server, acpSid, zcodeSid);

// Goal-loop restart recovery (ADR-0022 §6): surface a recovery hint at most
Expand Down Expand Up @@ -2717,6 +2717,7 @@ export async function runOneTurn(
differ.markSeen(await fetchMessagesSinceAnchor(server, zcodeSid, differ.historyAnchor));
snapshot = await listener.subscribe(() => server.nextId());
}
server.markSessionSubscribed?.(backend, zcodeSid);
// A successful subscribe proves the resident runtime is live — refresh
// the verification so concurrent/later entry points skip a reload.
residentBackend = backend;
Expand Down Expand Up @@ -2868,7 +2869,11 @@ export async function runOneTurn(
return {
stopReason: "end_turn",
_meta: {
zcode: { delivery: outcome.kind, commandId: outcome.commandId },
zcode: {
delivery: outcome.kind,
commandId: outcome.commandId,
...(outcome.kind === "queued" ? { queueItemId: outcome.queueItemId } : {}),
},
},
};
}
Expand Down Expand Up @@ -3828,10 +3833,46 @@ export function cancelSessionTurns(
} catch (e) {
log(`goal-loop pause request failed: ${e instanceof Error ? e.message : String(e)}`);
}
// A backend-owned turn (rewind replacement, background notification, a
// failed orphan adopt, or a turn whose start was never observed) has no
// pendingTurns entry, yet is still running upstream. Still send the stop
// pair unless detached auto-compact owns the session's prompt lock (ESC
// during detached compaction must not kill compaction).
const foreignOrNotify =
server.foreignActiveTurns?.has(zcodeSid) === true ||
server.notifyTurnActiveSince?.has(zcodeSid) === true ||
server.backgroundListeners?.get(zcodeSid)?.hasActiveRewindClaim() === true;
const compactRunning = server.autoCompactInFlight?.has(zcodeSid) === true;
if (!compactRunning) {
void stopBackendTurn(server, zcodeSid, { zcodeSid, cancelled: true, sendAccepted: true });
server.lastCancelledAt?.set(zcodeSid, Date.now());
}
if (foreignOrNotify) {
server.foreignActiveTurns?.delete(zcodeSid);
server.notifyTurnActiveSince?.delete(zcodeSid);
server.backgroundListeners?.get(zcodeSid)?.clearRewindAndNotifyState();
const acpSid = server.acpSidByZcodeSid?.get(zcodeSid);
if (acpSid && !compactRunning) {
void emitSessionTurnState(server, acpSid, false).catch(() => undefined);
}
}
}
return matched;
}

/**
* Awaitable stop pair for an unowned backend turn (remote force-close): ensures
* `session/stop` + `v4/command stop` are written to the backend pipe BEFORE
* `session/close` evicts the resident runtime.
*/
export async function stopUnownedBackendTurn(
server: ZcodeAcpServer,
zcodeSid: string,
): Promise<void> {
await stopBackendTurn(server, zcodeSid, { zcodeSid, cancelled: true, sendAccepted: true });
server.lastCancelledAt?.set(zcodeSid, Date.now());
}

/**
* Raised by `runEventTurn` when the backend emits `turn.failed`. Carries the
* structured error object (with its nested `cause`) so `prompt`'s retry loop
Expand Down
13 changes: 13 additions & 0 deletions src/push/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,19 @@ export function pushTerminalNotification(data: PushEventData & { kind: "terminal
dispatchPush(cfg, s, data);
}

/**
* Push an interactive/authorization notice that needs human attention even when
* a remote client is connected (e.g. V2 MCP OAuth fallback opening the browser
* on the host machine while the user is on mobile). Gated by `push.notify.ask`.
*/
export function pushAskNotice(data: PushEventData & { kind: "permission" | "question" }): void {
const cfg = pushConfig();
if (!cfg || !cfg.notify.ask) return;
const s = pushSender();
if (!s) return;
dispatchPush(cfg, s, data);
}

/**
* Derive the permission/question payload from the wire method+params (§4/§5.1)
* — shared by the zero-clients push and the unanswered-ask watchdog. `label`
Expand Down
26 changes: 24 additions & 2 deletions src/remote/session-close-endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import process from "node:process";

import { cancelSessionTurns } from "../handlers/session.js";
import { cancelSessionTurns, stopUnownedBackendTurn } from "../handlers/session.js";
import { clearV4ConversationState } from "../v2/queue.js";
import { recordClosedSessionIds } from "../closed-sessions.js";
import type { ZcodeAcpServer } from "../server.js";
import { log } from "../utils.js";
Expand Down Expand Up @@ -225,6 +226,9 @@ export async function retireSession(
const running =
zcodeSid !== undefined &&
[...server.pendingTurns.values()].some((t) => t.zcodeSid === zcodeSid);
const foreignRunning =
zcodeSid !== undefined &&
(server.foreignActiveTurns.has(zcodeSid) || server.notifyTurnActiveSince.has(zcodeSid));
if (running && !opts.force) return { error: "running" };
if (running && zcodeSid !== undefined) {
// Force close (ADR-0006 amendment): ESC semantics without a client
Expand All @@ -239,6 +243,19 @@ export async function retireSession(
if (![...server.pendingTurns.values()].some((t) => t.zcodeSid === zcodeSid)) break;
await sleep(50);
}
} else if (opts.force && foreignRunning && zcodeSid !== undefined) {
// Unowned backend turn (rewind/notification/orphan): await the stop pair so
// session/stop + v4 stop land on stdin BEFORE session/close evicts the
// runtime, then give the terminal event a brief settle window.
await stopUnownedBackendTurn(server, zcodeSid);
log(`remote: force close stopping foreign turn(s) for ${zcodeSid}`);
const deadline = Date.now() + Math.min(forceSettleMs, 500);
while (Date.now() < deadline) {
if (!server.foreignActiveTurns.has(zcodeSid) && !server.notifyTurnActiveSince.has(zcodeSid)) {
break;
}
await sleep(50);
}
}
// Retire from discovery AND stamp the retirement: a turn that outlives the
// force-settle bound settles after this point, and its terminal activity
Expand Down Expand Up @@ -267,7 +284,12 @@ export async function retireSession(
// The runtime eviction below kills any in-flight FOREIGN turn (background
// wake / subagent_message) with no terminal event arriving — drop the
// tracking entry or the retired conversation would keep reporting running.
if (zcodeSid) server.foreignActiveTurns.delete(zcodeSid);
if (zcodeSid) {
server.foreignActiveTurns.delete(zcodeSid);
server.notifyTurnActiveSince.delete(zcodeSid);
server.invalidateSessionSubscription?.(zcodeSid);
clearV4ConversationState(zcodeSid);
}
if (zcodeSid && server.backend && !server.backend.isDead) {
try {
server.backend.send("session/close", { sessionId: zcodeSid });
Expand Down
Loading
Loading