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
5 changes: 5 additions & 0 deletions .changeset/oversized-review-daemon-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hunkdiff": patch
---

A review too large for the session daemon now shows "Session daemon rejected this review" in the terminal instead of silently resending it, and a browser review exits with its file count and a `-- <pathspec>` hint instead of printing a link that never loads.
123 changes: 120 additions & 3 deletions packages/hunk/src/app/session/headlessReviewRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,23 @@ import type { AppBootstrap } from "../../core/bootstrap";
import { loadAppBootstrap } from "../../core/changeset/loaders";
import { STML_REFERENCE_WIDTH } from "../../core/stml/layout";
import { createEmptyExtensionLoadResult, type ExtensionLoadResult } from "../../extensions/types";
import type { SessionBrokerClient } from "../../session/broker/brokerClient";
import type {
HunkDaemonConnectionState,
SessionBrokerClient,
} from "../../session/broker/brokerClient";
import { HUNK_DAEMON_REGISTRATION_REJECTED_MESSAGE } from "../../session/client/capabilities";
import type { HunkSessionServerMessage, HunkSessionSnapshot } from "../../session/types";
import { createWatchTestRuntime } from "../../../../../test/helpers/watchTest";
import {
HUNK_SESSION_REGISTRATION_LIMITS,
type SessionRegistrationLimits,
} from "../../session/broker/registrationAdmission";
import { ReviewProducer } from "../review/producer";
import { runHeadlessReview, type HeadlessReviewSession } from "./headlessReviewRunner";
import {
runHeadlessReview,
type HeadlessReviewSession,
type ReviewServedProbe,
} from "./headlessReviewRunner";
import type { ReviewUrlOpener } from "./openReview";
import { createInitialSessionSnapshot, createSessionRegistration } from "./registration";
import type { ReviewSessionRuntime } from "./reviewRuntime";
Expand Down Expand Up @@ -73,9 +85,12 @@ function createTestRuntime(
let bridge: { dispatchCommand(message: HunkSessionServerMessage): Promise<unknown> } | null =
null;
let stopped = 0;
let connectionState: HunkDaemonConnectionState = { status: "connected" };
const hostClient = {
waitForFirstRegistration: waitForRegistration,
getRegistration: () => registration,
getSnapshot: () => snapshots.at(-1)!,
getConnectionState: () => connectionState,
replaceSession(next: typeof registration, snapshot: HunkSessionSnapshot) {
registration = next;
snapshots.push(snapshot);
Expand All @@ -98,6 +113,10 @@ function createTestRuntime(
dispatch: (message: HunkSessionServerMessage) => bridge!.dispatchCommand(message),
hasBridge: () => bridge !== null,
stopCount: () => stopped,
/** Report the link state a daemon's close would leave the broker client in. */
setConnectionState: (next: HunkDaemonConnectionState) => {
connectionState = next;
},
};
}

Expand All @@ -110,9 +129,12 @@ async function startTestHeadlessReview(
stderrIsTTY?: boolean;
waitForRegistration?: () => Promise<void>;
registrationTimeoutMs?: number;
isReviewServed?: ReviewServedProbe;
registrationLimits?: SessionRegistrationLimits;
fake?: ReturnType<typeof createTestRuntime>;
} = {},
) {
const fake = createTestRuntime(bootstrap, options.waitForRegistration);
const fake = options.fake ?? createTestRuntime(bootstrap, options.waitForRegistration);
const signals = new EventEmitter();
const stdout: string[] = [];
const stderr: string[] = [];
Expand All @@ -127,6 +149,8 @@ async function startTestHeadlessReview(
});
const exited = runHeadlessReview(bootstrap, {
registrationTimeoutMs: options.registrationTimeoutMs,
isReviewServed: options.isReviewServed ?? (async () => true),
registrationLimits: options.registrationLimits,
holdProcess: () => {
hold.acquired += 1;
return () => {
Expand Down Expand Up @@ -367,6 +391,7 @@ describe("runHeadlessReview", () => {
holdProcess: () => () => {},
watchOutputClosed: () => () => {},
resolveUpdateNotice: async () => null,
isReviewServed: async () => true,
onStarted: (running) => {
session = running;
},
Expand All @@ -386,6 +411,98 @@ describe("runHeadlessReview", () => {
expect(await exited).toBe(0);
});

// The hello proves only that a daemon talks to the session; the daemon judges the registration
// after it, so the URL waits until the daemon serves the review.
test("asks the daemon for the review until it is served, then prints the URL", async () => {
const { bootstrap } = await createTestHeadlessBootstrap({ open: false });
const fake = createTestRuntime(bootstrap);
const asked: string[] = [];
const review = await startTestHeadlessReview(bootstrap, undefined, {
fake,
// Registered at once, served only on the third ask.
isReviewServed: async (sessionId) => {
asked.push(sessionId);
return asked.length >= 3;
},
});

const sessionId = fake.runtime.hostClient.getRegistration().sessionId;
expect(asked).toEqual([sessionId, sessionId, sessionId]);
expect(review.stdout).toEqual([`${review.session.url}\n`]);
review.signals.emit("SIGINT");
expect(await review.exited).toBe(0);
});

// A daemon that completes the hello and then never answers must not hold the command open: the
// request in flight ends with the wait.
test("ends a hanging review request when the registration bound runs out", async () => {
const { bootstrap } = await createTestHeadlessBootstrap({ open: false });
const signals: AbortSignal[] = [];
const review = await startTestHeadlessReview(bootstrap, undefined, {
registrationTimeoutMs: 20,
isReviewServed: (_sessionId, signal) => {
signals.push(signal);
return new Promise<boolean>((resolve) => {
signal.addEventListener("abort", () => resolve(false), { once: true });
});
},
});

await expect(review.exited).rejects.toThrow("No session daemon accepted it within 1 seconds.");
expect(signals).toHaveLength(1);
expect(signals[0]!.aborted).toBe(true);
expect(review.stdout).toEqual([]);
});

test("exits with the daemon's refusal, and no URL, when it rejects the registration", async () => {
const { bootstrap } = await createTestHeadlessBootstrap({ open: false });
const fake = createTestRuntime(bootstrap);
const review = await startTestHeadlessReview(bootstrap, undefined, {
fake,
// The daemon closes the socket after the hello; the broker client then reports it.
isReviewServed: async () => {
fake.setConnectionState({
status: "disconnected",
notice: HUNK_DAEMON_REGISTRATION_REJECTED_MESSAGE,
direction: "unknown",
});
return false;
},
});

await expect(review.exited).rejects.toThrow(
`could not serve this review through the session daemon on 127.0.0.1:45555. ${HUNK_DAEMON_REGISTRATION_REJECTED_MESSAGE}`,
);
expect(review.stdout).toEqual([]);
expect(review.fake.stopCount()).toBe(1);
expect(review.hold.acquired).toBe(0);
});

test("refuses a review too large for the daemon before waiting, naming its size and a remedy", async () => {
const { bootstrap } = await createTestHeadlessBootstrap({ open: false });
let waited = false;
const review = await startTestHeadlessReview(bootstrap, undefined, {
waitForRegistration: async () => {
waited = true;
},
registrationLimits: { ...HUNK_SESSION_REGISTRATION_LIMITS, maxFiles: 0.5 },
});

const error = await review.exited.then(
() => null,
(failure: unknown) => failure as Error,
);
expect(error?.name).toBe("HunkUserError");
expect(error?.message).toBe(
"could not serve this review through the session daemon on 127.0.0.1:45555. This review has 1 file, more than the session daemon can hold. Narrow it to fewer files with `-- <pathspec>`.",
);
expect(waited).toBe(false);
expect(review.stdout).toEqual([]);
expect(review.fake.stopCount()).toBe(1);
expect(review.fake.hasBridge()).toBe(false);
expect(review.hold.acquired).toBe(0);
});

test("exits with a user error naming the port, and no URL, when registration fails", async () => {
const { bootstrap } = await createTestHeadlessBootstrap({ open: false });
const conflict = new Error(
Expand Down
121 changes: 104 additions & 17 deletions packages/hunk/src/app/session/headlessReviewRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@
* agent's `hunk session reload` and `--watch` changes — go through `ReviewReloadCoordinator`.
*
* Entry point: `hunk <review command> --web` implies `--watch` (startup applies it unless
* `--no-watch`). It waits, bounded, until a daemon accepts the session; when none will (another
* program holds the port, the daemon cannot start, or it is a different Hunk build) it exits with a
* user error and prints no URL. Otherwise it prints exactly the URL line on stdout, then opens that URL in the default browser
* unless `--no-open`. A launch failure is one stderr line without the URL, and the review keeps
* serving. When stderr is a terminal, one line says where the review is — open in the browser,
* or to be opened from the URL — and that Ctrl+C stops it; a failed launch carries that hint in
* its warning instead of a second line.
* `--no-watch`). A review larger than the daemon holds per session exits at once with a user error
* that names its file count and a remedy. Otherwise it waits, bounded, until the daemon serves the
* review to a holder of its link — the hello proves only that a daemon talks to this session, and
* the daemon refuses an oversized or over-capacity registration after it. When none will (another
* program holds the port, the daemon cannot start, it is a different Hunk build, or it refused the
* review) it exits with a user error and prints no URL. Otherwise it prints exactly the URL line on
* stdout, then opens that URL in the default browser unless `--no-open`. A launch failure is one
* stderr line without the URL, and the review keeps serving. When stderr is a terminal, one line
* says where the review is — open in the browser, or to be opened from the URL — and that Ctrl+C
* stops it; a failed launch carries that hint in its warning instead of a second line.
* `hunk session open` reaches the same opener through the bridge (`./openReview.ts`).
*
* Terminal-only concerns get explicit headless answers here: repo-local extensions awaiting a
Expand All @@ -42,7 +45,13 @@ import {
resolveSessionBrokerConfig,
type ResolvedSessionBrokerConfig,
} from "../../session/broker/brokerConfig";
import { reviewProcessUrl } from "../review/capability";
import {
assessSessionRegistration,
describeOversizedSessionRegistration,
type SessionRegistrationLimits,
} from "../../session/broker/registrationAdmission";
import { HUNK_REVIEW_CAPABILITY_HEADER, reviewHttpPath } from "../../session/reviewHttpProtocol";
import { reviewProcessCapability, reviewProcessUrl } from "../review/capability";
import { ReviewSessionHost } from "../review/reviewSessionHost";
import { buildReviewPresentationDefaults, buildReviewSharedState } from "../review/sharedState";
import type { ReviewPresentationDefaults } from "../../session/reviewSharedState";
Expand Down Expand Up @@ -84,23 +93,74 @@ function holdProcessOpen() {

/**
* How long a headless review waits for a daemon to accept it before giving up: one daemon startup
* attempt, as a terminal session's auto-start allows, plus the same again for the signed hello.
* attempt, as a terminal session's auto-start allows, plus the same again for the signed hello
* and the registration that follows it.
*/
export const HEADLESS_REGISTRATION_TIMEOUT_MS = 2 * DAEMON_STARTUP_TIMEOUT_MS;

/** Spacing between asks whether the daemon serves the review yet; registration takes milliseconds. */
const REVIEW_SERVED_POLL_MS = 50;

/**
* Ask the daemon whether it serves one session's review; resolves false on any failure, including
* the wait ending through `signal`.
*/
export type ReviewServedProbe = (sessionId: string, signal: AbortSignal) => Promise<boolean>;

/**
* Ask the daemon for this session's publication with the capability the printed URL carries,
* exactly as the page's first request does: success means the link will load.
*/
function createReviewServedProbe(httpOrigin: string): ReviewServedProbe {
return async (sessionId, signal) => {
try {
const response = await fetch(
`${httpOrigin}${reviewHttpPath({ kind: "publication", sessionId })}`,
{ headers: { [HUNK_REVIEW_CAPABILITY_HEADER]: reviewProcessCapability().token }, signal },
);
Comment on lines +117 to +120

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.

P1 Timeout does not end command

If the daemon stops answering after the signed hello, the registration deadline throws but leaves this fetch running. Cleanup only stops future polls, and the CLI error handler only sets process.exitCode. The open request can therefore keep the command alive past its six-second bound.

Pass an abort signal to the probe and abort it when the wait ends.

Knowledge Base Used: Session management

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/hunk/src/app/session/headlessReviewRunner.ts
Line: 114-117

Comment:
**Timeout does not end command**

If the daemon stops answering after the signed hello, the registration deadline throws but leaves this `fetch` running. Cleanup only stops future polls, and the CLI error handler only sets `process.exitCode`. The open request can therefore keep the command alive past its six-second bound.

Pass an abort signal to the probe and abort it when the wait ends.

**Knowledge Base Used:** [Session management](https://app.greptile.com/-/switch-tenant?tenant=modem&next=%2Fcustom-context%2Fknowledge-base%2Fmodem-dev%2Fhunk%2F-%2Fdocs%2Fsession-management.md)

---

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Valid. Fixed in 4935c05: the probe now takes an AbortSignal that waitForDaemonRegistration aborts in its finally, so the request in flight ends with the wait. New test: "ends a hanging review request when the registration bound runs out" (a probe that never answers until aborted; the run exits at the bound with the signal aborted).


Generated by Claude Code

await response.body?.cancel().catch(() => undefined);
return response.ok;
} catch {
return false;
}
};
}

/**
* Wait until a daemon accepts this session, or fail with a user error naming the daemon port.
* Wait until a daemon accepts this session and serves its review, or fail with a user error
* naming the daemon port.
*
* The broker client reports the first reason registration cannot happen — the port belongs to
* another process, the daemon did not start, or it is a different Hunk build — and this bound
* covers a daemon that never answers. The timer is referenced, so the wait blocks the event loop
* rather than polling it.
* The broker client reports the first reason the hello cannot happen — the port belongs to
* another process, the daemon did not start, or it is a different Hunk build. The daemon judges
* the registration only after the hello, and refuses it by closing the socket, so the wait then
* asks the daemon for the review itself until it answers or the broker client reports the
* refusal. The bound covers a daemon that never answers. The timer is referenced, so the wait
* blocks the event loop rather than polling it.
*/
async function waitForDaemonRegistration(
hostClient: Pick<ReviewSessionRuntime["hostClient"], "waitForFirstRegistration">,
hostClient: Pick<
ReviewSessionRuntime["hostClient"],
"waitForFirstRegistration" | "getConnectionState" | "getRegistration"
>,
isReviewServed: ReviewServedProbe,
config: Pick<ResolvedSessionBrokerConfig, "host" | "port">,
timeoutMs: number,
) {
// Ends the request in flight when the wait does, so a daemon that answers the hello and then
// nothing cannot hold the command open past its bound.
const abandoned = new AbortController();
/** Poll until the review is served, failing as soon as the daemon has refused it. */
const waitForReviewServed = async () => {
await hostClient.waitForFirstRegistration();
const sessionId = hostClient.getRegistration().sessionId;
while (!abandoned.signal.aborted) {
const state = hostClient.getConnectionState();
if (state.status === "disconnected") throw new Error(state.notice);
if (await isReviewServed(sessionId, abandoned.signal)) return;
await new Promise((resolve) => setTimeout(resolve, REVIEW_SERVED_POLL_MS));
}
};

let timer: ReturnType<typeof setTimeout> | undefined;
const timedOut = new Promise<never>((_resolve, reject) => {
timer = setTimeout(
Expand All @@ -112,7 +172,7 @@ async function waitForDaemonRegistration(
);
});
try {
await Promise.race([hostClient.waitForFirstRegistration(), timedOut]);
await Promise.race([waitForReviewServed(), timedOut]);
} catch (error) {
// The broker client's startup timeout promises a background retry; this command exits.
const reason = (error instanceof Error ? error.message : String(error)).replace(
Expand All @@ -128,10 +188,31 @@ async function waitForDaemonRegistration(
`could not serve this review through the session daemon on ${config.host}:${config.port}. ${sanitizeTerminalLine(reason)}${remedy}`,
);
} finally {
abandoned.abort();
clearTimeout(timer);
}
}

/**
* Refuse, before any wait, a review the daemon would refuse for its size, naming its file count
* and the remedy rather than a refusal reason the daemon cannot explain.
*/
function assertDaemonCanHoldReview(
hostClient: Pick<ReviewSessionRuntime["hostClient"], "getRegistration" | "getSnapshot">,
config: Pick<ResolvedSessionBrokerConfig, "host" | "port">,
limits?: SessionRegistrationLimits,
) {
const admission = assessSessionRegistration(
hostClient.getRegistration(),
hostClient.getSnapshot(),
limits,
);
if (admission.ok) return;
throw new HunkUserError(
`could not serve this review through the session daemon on ${config.host}:${config.port}. ${describeOversizedSessionRegistration(admission)}`,
);
}

/** Call `onClosed` once stdout or stderr reports that its reader is gone. */
function watchProcessOutputClosed(onClosed: () => void) {
const onError = (error: unknown) => {
Expand Down Expand Up @@ -178,6 +259,10 @@ export interface HeadlessReviewDeps {
watchOutputClosed?: (onClosed: () => void) => () => void;
/** Bound on waiting for a daemon to accept the session; tests shorten it. */
registrationTimeoutMs?: number;
/** Ask the daemon whether it serves the review yet; tests answer directly. */
isReviewServed?: ReviewServedProbe;
/** The daemon's per-session bounds; tests shrink them. */
registrationLimits?: SessionRegistrationLimits;
}

/** The live pieces of one running headless review, exposed for tests. */
Expand Down Expand Up @@ -380,11 +465,13 @@ export async function runHeadlessReview(
reviewProducer: producer,
}),
);
// The URL is only printed once a daemon has accepted the session and will serve its page.
// The URL is only printed once the daemon serves the review's page to a holder of the link.
const brokerConfig = resolveSessionBrokerConfig(deps.env);
try {
assertDaemonCanHoldReview(hostClient, brokerConfig, deps.registrationLimits);
await waitForDaemonRegistration(
hostClient,
deps.isReviewServed ?? createReviewServedProbe(brokerConfig.httpOrigin),
brokerConfig,
deps.registrationTimeoutMs ?? HEADLESS_REGISTRATION_TIMEOUT_MS,
);
Expand Down
Loading
Loading