Skip to content

fix(harness): cancel Terminal preparation after End [SAP-3292] - #995

Closed
ynadge wants to merge 1 commit into
assistant-runtime-retirementfrom
terminal-end-admission
Closed

ynadge wants to merge 1 commit into
assistant-runtime-retirementfrom
terminal-end-admission

Conversation

@ynadge

@ynadge ynadge commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Primary change type

  • Bug fix

Problem and motivation

A Terminal launch paused in asynchronous preparation could spawn after the user ended its Studio session. The kill fallback also marked a session exited even when process termination could not be confirmed.

Summary and scope

Capture close generations across create/resume/restart preparation and verify them at final PTY publication. Keep preparation serialized for each Studio ID. Expose confirmed, absent, and unconfirmed cleanup results with the exact runtime epoch, retaining unresolved handles and late positive evidence. Preserve the existing boolean close/kill APIs for their callers.

Related work

Related issue: https://linear.app/sapiom/issue/SAP-3292

Native stack target: main. Depends on the preceding branch, preserving Epic 2 dependency ancestry through #987. Depends on #994. This is the Terminal companion to the Assistant retirement primitives; lifecycle controls follow.

Validation

pnpm --filter @sapiom/harness exec vitest run src/core/session-manager-close.test.ts src/core/session-manager.test.ts — 214 passed
pnpm --filter @sapiom/harness typecheck — passed (server and web)
pnpm --filter @sapiom/harness build:server; targeted ESLint and formatting — passed

pr:size is absent in sapiom-js; incremental git diff --numstat measures 682 changed lines, including tests.

Tests and documentation

Twenty behavior tests cover preparation races, repeated close, independent sessions, shutdown, and exact late exit evidence. Seven paused-create cases reproduced the original bug; two late-evidence tests also failed before that correction.

Compatibility and release impact

  • Breaking or externally visible changes: Terminal launches cannot publish after End. Unconfirmed cleanup blocks replacement until matching positive evidence arrives.
  • Changeset: added for @sapiom/harness.
  • Fix-forward: correct startup/cleanup in a follow-up while retaining process guards and proof; never delete guards to bypass uncertain cleanup.

Security

  • No secrets, credentials, private data, or unsanitized logs included.
  • No suspected vulnerability disclosed publicly.

AI assistance

  • AI assistance used: Codex implemented the modules/tests; a separate agent reviewed their integration contracts and the root agent reran validation and reviewed the incremental diff.

Checklist

  • CONTRIBUTING.md read; maintainer-authorized issue work.
  • One focused increment, tests, relevant checks, documentation, and release impact addressed above.
  • I can explain and maintain the submitted changes.

Devin Review

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 158d8f6d-baed-41e1-b7cd-fd926a006015

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 6 potential issues.

Devin Review

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.

🔴 Retiring processes escape shutdown

After kill retires an unconfirmed handle, killAll excludes it because it snapshots only ptys. Shutdown can exit with the retained child still running.

(Refers to this code)

Learn more

An unconfirmed kill removes the handle from ptys and stores it in retiringPtys. The server later calls killAll during shutdown to terminate child processes. This implementation snapshots only ptys, so it neither retries termination nor waits for positive evidence from retained handles. The server can therefore finish shutdown while one of its terminal children remains alive.

Example: Terminal A survives the initial SIGTERM and SIGKILL attempts, then enters retiringPtys. Quitting Studio calls killAll, which sees no entry for A and resolves immediately while A continues running.

Recommended fix: Include exact handles from both ptys and retiringPtys in shutdown cleanup. Retry signaling retained handles without moving them back into the live registry, and keep shutdown bounded by the server's existing outer timeout.

Devin Review

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

Comment on lines +1749 to +1751
async closeWithResult(id: string): Promise<TerminalCleanupResult> {
const handle = this.ptys.get(id) ?? this.retiringPtys.get(id);
await this.close(id);

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.

🔴 End reports success for live terminals

When End targets a surviving process, closeWithResult can report unconfirmed, but the DELETE route never calls it. The route calls close and always returns { ok: true }, hiding the live process from clients.

Learn more

closeWithResult is the only API that distinguishes confirmed termination from bounded registry retirement. The existing DELETE endpoint is the Studio End action, but it still calls the legacy boolean close API. That API resolves after 2.5 seconds even when the retained process remains alive. The endpoint then returns an unconditional success response, so the browser cannot present or track the unconfirmed cleanup state.

Example: A terminal ignores SIGTERM and remains visible to the liveness probe after SIGKILL. closeWithResult would return { state: "unconfirmed", runtimeEpoch: "epoch-1" }, but DELETE currently returns { ok: true }.

Recommended fix: Wire the End endpoint to closeWithResult and return the TerminalCleanupResult contract. Update its client and route tests to handle confirmed, absent, and unconfirmed explicitly.

Devin Review

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

Comment on lines +3868 to +3876
return this.prepareSession(id, (generation) =>
this.restartFreshPrepared(
id,
expected,
nextInput,
trusted,
hasRecordedTurns,
generation,
),

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.

🟡 Closed delegated binding is recreated

When End lands during restartFreshBound preflight, the restart recreates the binding marker deleted by close. restartFreshPrepared writes it after awaited probes without another generation check, leaving stale recovery state.

Learn more

prepareSession captures the close generation only when the restart begins. restartFreshPrepared then awaits adapter.canResume and hasRecordedTurns before advancing and persisting the private binding marker. End can run during either await, delete that marker, and increment the generation. The restart resumes without checking the generation, writes the next marker back, and only detects cancellation later inside spawn. Its failure cleanup does not remove that rewritten marker.

Example: A delegated session starts fresh-restart preflight with marker incarnation 1. End completes while hasRecordedTurns is pending and deletes the marker. The preflight returns false, so the restart persists incarnation 2 before spawn rejects; the closed session now has a private marker again.

Recommended fix: Call assertAdmission(id, closeGeneration) immediately after the awaited preflight probes and before mutating subsessionBindings. Recheck after binding persistence if later side effects rely on the marker remaining current, and add a race test paused in each probe.

Devin Review

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

Comment on lines +687 to +700
export class SessionPreparationCancelledError extends Error {
readonly code = "SESSION_PREPARATION_CANCELLED";
constructor() {
super("session was closed while terminal startup was being prepared");
this.name = "SessionPreparationCancelledError";
}
}

export class SessionCleanupUnconfirmedError extends Error {
readonly code = "SESSION_CLEANUP_UNCONFIRMED";
constructor() {
super("the previous terminal process has not been confirmed stopped");
this.name = "SessionCleanupUnconfirmedError";
}

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.

🟡 Lifecycle conflicts return server errors

When End races Resume, or cleanup remains unconfirmed, the new lifecycle errors fall through as HTTP 500. The resume mapper omits both conflict types.

Learn more

resume can now reject with SessionPreparationCancelledError when End advances its generation during preparation. It can also reject with SessionCleanupUnconfirmedError while a retained process lacks positive exit evidence. Both are expected lifecycle conflicts with stable codes, but sendResumeError recognizes neither class. Express therefore sends the generic 500 response instead of the bounded 409 contract used for other resume conflicts.

Example: A user clicks Resume while the previous process is retained as unconfirmed. assertAdmission throws SESSION_CLEANUP_UNCONFIRMED; the API responds 500 although retrying after process exit is valid.

Recommended fix: Import both lifecycle error classes into the REST router, map them to HTTP 409 in sendResumeError, and add route tests for an End race and retained cleanup.

Devin Review

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

Comment on lines +1785 to +1787
/** Bounded legacy registry cleanup, also used by internal Terminal restarts.
* True means a live/stale row was retired, not proof its OS process stopped.
* Use closeWithResult() for End's truthful cleanup outcome. */

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.

🔍 Legacy kill contract changed broadly

kill now proves registry retirement, not process exit. Audit its existing callers for places that still require termination evidence.

Devin Review

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

Comment on lines +682 to +700
export type TerminalCleanupResult = Readonly<{
state: "confirmed" | "absent" | "unconfirmed";
runtimeEpoch: string | null;
}>;

export class SessionPreparationCancelledError extends Error {
readonly code = "SESSION_PREPARATION_CANCELLED";
constructor() {
super("session was closed while terminal startup was being prepared");
this.name = "SessionPreparationCancelledError";
}
}

export class SessionCleanupUnconfirmedError extends Error {
readonly code = "SESSION_CLEANUP_UNCONFIRMED";
constructor() {
super("the previous terminal process has not been confirmed stopped");
this.name = "SessionCleanupUnconfirmedError";
}

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.

🔍 Public lifecycle types lack documentation

The exported result and errors introduce visible lifecycle contracts without JSDoc. Repository rules require documentation for public APIs and behavior.

Devin Review

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant