Skip to content

FIX-1690 (stop): a block can stop another request in its own session - #2538

Merged
jhoffner merged 4 commits into
mainfrom
fix/FIX-1690-stop
Oct 1, 2026
Merged

jhoffner merged 4 commits into
mainfrom
fix/FIX-1690-stop

Conversation

@jhoffner

@jhoffner jhoffner commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

The problem

A person in App Lab can't send a line to a coding run that is working: nothing can stop a run from inside its own session so the run can continue with what they said. The abort route can stop a request, but only for a client that names it over HTTP. An action that takes a person's message has no way to make room for it.

What this does

The first of three PRs for FIX-1690. It adds one generic hook and nothing else: a block may stop another request running in its own session.

const outcome = await ctx.session.stopRequest(requestId);
// "stopped" | "already-finished" | "not-in-this-session"

It is the abort route's own write, not a copy. The fenced abortRequested write moved out of the route into recordRequestStop, and both callers use it: the route after its owner and tenant check, the hook after checking the request is one the session's own reads would show. A request in another process stops on its next heartbeat, as an abort does. Any id outside the session, including one that doesn't exist, answers not-in-this-session and writes nothing.

What changes: the three composers call one door; for a coding run, the door keeps the line, stops the attempt through a new generic stop hook, and the next attempt continues the same coding session

This PR is the "generic stop hook" box only. The door (door) and the composers (lab) follow.

What's asked of you

Nothing new: this implements the approved spec's S1 and S2. Core and Engine gain no Workforce, task, harness or seat word (ER-7).

Parts worth reviewing closely

For the code reviewer.

  • The session fence: requestInSessionScope in packages/engine/src/context/session-request-scope.ts applies sessionRequestScope (the filter every session read uses) to one record. Session id, tenant, owner, org and flow must all match.
  • The route refactor: handleAbortRequest now maps recordRequestStop's four results to 404 / 409 / 204 / 202. All 98 existing abort tests pass unchanged.
  • My weak spot: the "second process" test loads a fresh copy of the engine (vi.resetModules) so its abort registry has never seen the target's controller. It asserts that precondition, but it's still a simulation, not two OS processes.

Part of FIX-1690 (S1, S2) · spec: specs/issues/FIX-1690/ · spec PR #2525 · epic FIX-1649 · next: door, then lab. Checks here: V1 (unit level); the goal check lands with lab.

How to review this

How to review this. This implements an approved spec — the approach and the numbered
decisions in its DECISIONS.md are already signed off by a human, so please review the
code against that direction, not the direction itself. The canonical set is retained
at specs/issues/<ISSUE-ID>/ on main; Linear links to it and the original merged spec
PR, which keeps review history. Follow-up amendment PRs explain later direction changes.
Current architecture docs remain the authority for shipped behavior (BP-037).

Most valuable here: correctness on the second path (the legacy shape, the null
boundary, the concurrent case, the cancel path), anything deriving an auth or routing
decision from caller-controllable input, and a behaviour the tests assert around
rather than on.

Already settled upstream: the approach and every decision in the spec's DECISIONS.md
(human-approved — if one is wrong, say so as a spec finding and it gets folded back; don't
re-argue it inline), and the conventions in docs/contributing/best-practices.md.

Engineering calls
  • The hook lives on ctx.session as stopRequest, returning a string union. DOCS.md left the name to the implementer. If wrong: a rename before 1.0.
  • A legacy session with no flowId fences on flow kind alone, matching how sessionRequestScope already treats it. If wrong: a legacy session could stop a same-kind request of another instance under its own session id, which today's admission already refuses to create.
  • A block stopping its own request is not refused. It ends itself aborted, which is what the call says. Nothing in the spec covers it.
  • Docs written directly from DOCS.md's reviewed draft: this run had no sub-agent dispatch, so docs-writer / docs-editor were not run on the flows.md paragraph.
Verification

V1 (packages/engine/test/abort.test.ts, ctx.session.stopRequest — …), six cases: same session in process → stopped, target aborted; another process via heartbeat → stopped, target aborted; another session → not-in-this-session, target completes naturally, no abortRequested; another tenant under the same session id → same; unknown id → not-in-this-session; finished → already-finished, record version unchanged.

Red before the change: all six failed with ctx.session.stopRequest is not a function.

Negative control (session fence removed from the hook): the other-session and other-tenant cases fail, expected 'stopped' to be 'not-in-this-session'; the other four stay green.

  • pnpm typecheck: 74/74 tasks pass.
  • pnpm --filter @flow-state-dev/core test: 2255 passed.
  • pnpm --filter @flow-state-dev/engine test: 3327 passed, 1 failed: session-stream-conformance BR-23 on the filesystem store, a 10 s timing test. It fails the same way on main without this change, and passes on a rerun with it.
  • pnpm knip:ci, pnpm lint: clean.
Files
  • packages/core/src/types/scope.ts: StopRequestOutcome, SessionScopeHandle.stopRequest.
  • packages/engine/src/execution/record-request-stop.ts: the shared fenced write.
  • packages/engine/src/routes/abort-routes.ts: calls it.
  • packages/engine/src/context/session-request-scope.ts: requestInSessionScope.
  • packages/engine/src/context/createExecutionContext.ts: the hook.
  • apps/docs/docs/fundamentals/flows.md, docs/architecture/execution-and-errors.md: docs.
  • .changeset/session-stop-request.md: core, engine minor.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq


Generated by Claude Code


Note

Medium Risk
Touches request cancellation and session-scoped authorization on the execution path; behavior is shared with /abort via a refactor, with broad test coverage but real multi-process risk.

Overview
Adds ctx.session.stopRequest(requestId) on SessionScopeHandle, so a block can cancel another in-session request the same way HTTP /abort does—enabling flows (e.g. message intake) to stop an in-flight run before continuing.

The fenced abortRequested write is centralized in recordRequestStop; the abort route and the session hook both call it after their own admission checks (owner/tenant vs requestInSessionScope). Outcomes are stopped, already-finished, or not-in-this-session (unknown or foreign ids are indistinguishable). Cross-process stops still land on the target’s next heartbeat.

Core exports StopRequestOutcome; docs and a changeset note the minor bump. Engine tests cover local/remote stop, session/tenant fencing, and parity between the predicate and store listings; App Lab’s composer test waits for the status poll before asserting the draft clears.

Reviewed by Cursor Bugbot for commit 50f2510. Configure here.

…n (FIX-1690)

ctx.session.stopRequest(id) records the abort route's own fenced write
(recordRequestStop, now shared by both callers) on a request the session's
own reads would show, and answers stopped / already-finished /
not-in-this-session. Requests and sessions only: no Workforce word.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@vercel

vercel Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

3 Skipped Deployments
Project Deployment Actions Updated
flow-state-dev-docs Ignored Ignored Oct 1, 2026 2:02am UTC
flow-state-dev-kitchen-sink Ignored Ignored Oct 1, 2026 2:02am UTC
flow-state-dev-ui Ignored Ignored Preview Oct 1, 2026 2:02am UTC

Request Review

@linear-code

linear-code Bot commented Oct 1, 2026

Copy link
Copy Markdown

FIX-1690

@cursor

cursor Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_37553fcb-7ec2-4cf2-8077-539fb50bdd42)

jhoffner commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Second look + architecture pass

Overall: the shape is right. Extracting recordRequestStop so the route and the hook share one fenced write is the correct refactor-while-adding-the-feature. The incarnation fence covers the check-then-write window, and the route refactor is behavior-preserving. I found no blockers. Findings below are ranked, and for the implementing agent to take or decline.

1. requestInSessionScope is a second copy of the session-filter semantics (worth addressing)

The doc says "one filter", but sessionRequestScope produces a filter object that the stores evaluate (in-memory, SQLite and Postgres each do it their own way). requestInSessionScope now re-implements that predicate in TS for a single record. The two can drift: for example, someone adds a key to sessionRequestScope, the stores honor it, and the hook silently doesn't. That drift would be a fence hole on an auth path.

Cheapest fix, no new abstraction: add one parity test. For a matrix of records (same session with a different tenant, owner, org or flow kind, a flowId mismatch, and a legacy session with no flowId), assert that requestInSessionScope(rec, scope) agrees with stores.request.list({...scope}) containing rec. Then the "same filter" claim is enforced rather than asserted in prose. The current negative control only covers session id and tenant. Owner, org, flow kind and the flowId branches have no red case, so removing any of them from the predicate leaves the suite green (BP-003).

2. The auth check materializes the whole request (low)

stores.request.get(targetId) loads the record with its items. RequestStore documents that get() is not acceptable for hot paths (see countItems and the abort-poll read). The route already does this, so there is precedent. But a coding run's request can carry many items, and the intended caller is an action fired per user message. If the narrow-read direction is wanted, the fix is a header-only read (no items) on RequestStore. I'd leave that out of this PR and note it as a follow-up, since it touches every adapter.

3. Self-stop is accepted silently (decision, not a bug)

The "Engineering calls" note says a block stopping its own request ends itself aborted. A caller reaching that by accident (passing its own ctx.requestId) gets a "stopped" outcome and a dead run. A test pinning the intended behavior would stop it changing by accident. If it's unintended, returning "not-in-this-session" for the caller's own id is a one-line guard. I don't have a strong view; I'd pin it in a test either way.

4. Nits

  • packages/core/src/types/index.ts: StopRequestOutcome sits between SessionMetadataInput and SessionScopeHandle, so the list is out of alphabetical order.
  • abort.test.ts: StopOutcome is rebuilt via Awaited<ReturnType<...["stopRequest"]>> when StopRequestOutcome is exported from core now. Import it instead.
  • The cross-process test is a module-reset simulation, as the PR says. That's adequate for this level. The lab goal check should be the one that exercises the real two-process path.

Alternatives considered

  • Exposing the stop via a request-handle (ctx.requests.get(id).stop()) instead of ctx.session: no better, since the session fence is the point and ctx.session carries it naturally.
  • Folding requestInSessionScope into the store layer (requests.getInSession(id, scope)): would eliminate finding 1 structurally, but it adds a store-contract method across three adapters for one caller. Not worth it now; revisit if a second caller appears.

Generated by Claude Code

@cursor cursor 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.

/simplify review (FIX-1690)

Verdict: The production shape is about as small as it can be for the spec’s “one write path” plus session-scoped admission. I’m approving; what follows is optional polish and one follow-up to keep in mind—not blockers.

Did the approach go too far?

No, for runtime code. The meaningful production delta is roughly:

  • recordRequestStop — moves the fenced setFieldsIfStatus + abortRequest path out of abort-routes.ts so the HTTP abort handler and ctx.session.stopRequest cannot drift (incarnation fence was the easy thing to duplicate).
  • requestInSessionScope — applies the existing sessionRequestScope list filter to a single get(id); blocks have no ResolvedPrincipal, so reusing callerReachesRequest would be the wrong trust boundary.
  • StopRequestOutcome (public) vs RequestStopResult (engine-internal) — keeps HTTP 204/202/404/409 separate from the three block-facing outcomes without leaking route semantics into core.

What grew the diff: retained spec + figures, atlas regen, and ~230 lines of integration tests in an already-large abort.test.ts. That’s documentation/process surface, not architectural sprawl.

Simpler alternatives considered

Alternative Why I’d skip it
Blocks call the abort HTTP route internally No principal on the block path; admission is “request this session would list,” not “caller owns request id.”
Inline the abort write only in stopRequest Reintroduces the duplication this PR removes from the route.
Collapse RequestStopResult into StopRequestOutcome Loses fired vs recorded mapping for 204 vs 202, or leaks HTTP into blocks.
Third-party package for cancellation AbortController + store fencing is already the stack; nothing off-the-shelf replaces session-scoped sibling cancel.
Deeper dedup: one matchesSessionRequestScope shared with all request.list implementations Real consistency win, but a cross-adapter store refactor—bigger than this issue; fine as a follow-up if list vs predicate ever drift.

Optional cleanups (non-blocking)

  1. Tests: makeStoppableFlow mirrors makeBlockingFlow (~L990) with the same abort-aware wait handler plus a stop action. Extending makeBlockingFlow (optional stop action / shared delay helper) would drop ~40 lines and keep one flow factory.
  2. Comments: record-request-stop.ts repeats the file header in the inline block (~L43–67); trimming to one invariant line would match BP-007 without behavior change.
  3. Types in tests: Prefer importing StopRequestOutcome from @flow-state-dev/core over the Awaited<ReturnType<...>> alias.
  4. Follow-up (if block-driven cancels get hot): stopRequest does request.get then scope check; on Postgres, get can pull items for a long sibling run. Same pattern as abort today, but this PR adds a new call site—worth a metadata-only read later, not required here.

What not to simplify

  • Merging session scope checks with callerReachesRequest / routing through handleAbortRequest.
  • Folding gone into a distinct public outcome (would weaken the uniform "not-in-this-session" story for out-of-scope ids).

Nice extraction on the abort route; tests cover local stop, cross-process heartbeat, session/tenant refusal, unknown id, and terminal request.

Open in Web View Automation 

Sent by Cursor Automation: Review For Best Approach

Comment thread packages/engine/test/abort.test.ts Resolved

@cursor cursor 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.

Code Snob. A smaller test shape exists. Production stays.

makeStoppableFlow copies makeBlockingFlow's wait-for-abort promise (already-aborted signal, then a timer raced against abort). That body should live once. The banner above the new describe restates the test name, and StopOutcome rebuilds StopRequestOutcome via Awaited<ReturnType<...>>.

Fold that subtraction from #2542 (completedNaturallyUnlessAborted). Same six stopRequest cases, and the cross-process suite that uses makeBlockingFlow, still pass. abort.test.ts is 28 insertions / 54 deletions against this head. Calling defineFlow twice to reuse actions.run registers the kind twice, so that lost. A stop flag on makeBlockingFlow is a one-caller option.

recordRequestStop, requestInSessionScope, and stopRequest are already the contract: one fenced write, six session keys on a single get, three returns. Do not shrink those.

Agent on this PR: fold the subtraction, then close the POC unmerged after this lands. The POC does not merge.

View PR

Open in Web View Automation 

Sent by Cursor Automation: Code Snob

A parity test holds requestInSessionScope to the stores' own listing for a
record that differs on each key (session, tenant, owner, org, flow kind,
flow instance), on two stores and for bound and legacy sessions. A block
naming its own request is pinned as stopping itself. Test helper reuse and
review nits.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq

jhoffner commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

Re: the second look + architecture pass. Changes are in 23b4e83.

  1. Parity: taken. New test: packages/engine/test/session-request-scope-parity.test.ts.
    • It builds one record per key, each differing from a matching record on that key alone: session, tenant (another one, and none), owner, org, flow kind, flow instance (another one, and none).
    • It asserts requestInSessionScope answers exactly what stores.request.list({...sessionRequestScope(...)}) answers.
    • It runs on the in-memory and filesystem stores, for a bound session and a legacy one. It also asserts the match is not vacuous: the matching record is listed, and something is excluded.
    • Negative controls: I replaced each conjunct of the predicate with true, one at a time. Tenant, owner, org and flow kind each fail 4/4. flowId fails 2/4, the two bound-session cases; for a legacy session there is no flowId to check, which is correct.
    • SQLite and Postgres aren't in this matrix because the engine doesn't depend on them. Their listing filters are covered by their own conformance suites.
  2. Header-only read: left as a follow-up, as you suggest. It touches every RequestStore adapter, and the route already reads this way.
  3. Self-stop: pinned. The new test "stops the calling request itself when it names its own id" checks that the request ends aborted with abortRequested. Control: a guard refusing the caller's own id makes it fail.
  4. Nits: both taken. The export order is fixed, and the test imports StopRequestOutcome from core.

The cross-process path is still the module-reset simulation here. The door PR's real-model goal stops a real Claude Code attempt through this hook, but it does so within one host process, so it does not add a two-process proof either.


Generated by Claude Code

claude added 2 commits October 1, 2026 01:45
… stream (FIX-1690)

The kept line can reach the transcript over the session's live stream
before the post's next status poll answers, and only that answer clears
the draft. Under CI load the stream won and the same-tick assertion read
the draft still set. Reproduced on main by delaying the status answer
400 ms: red 3/3; green 3/3 with the wait. Control: a composer that never
clears its draft still fails.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq
@cursor

cursor Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_c13a1c9e-1a3d-4a8e-9434-cd3d31d29b6b)

jhoffner commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI on 23b4e83 was red; 50f2510 fixes it.

What failed: labs/app-lab/test/shell.test.tsx › the composer (V6) › draws a post only once the channel holds it (expected 'kept line' to be ''). This PR doesn't touch App Lab. CI tests the merge with main, and this test came in from main.

Cause (a race in the test, on main): the kept line can reach the transcript over the session's live stream before the post's next /status poll answers. Only that answer clears the draft. Under CI load the stream won, and the same-tick expect(input.value).toBe("") saw the draft still set.

Proof it's main's, and that the fix holds:

Run Result
Unmodified main (56d27555b), /status answers 400 ms late after release red 3/3, CI's exact assertion
This branch (main merged), same 400 ms delay, with the fix green 3/3
Control: the composer never clears its draft still fails at expected 'kept line' to be ''
Full App Lab suite 96 passed, 1 skipped

The fix waits for the draft to clear (waitFor) instead of asserting it in the same tick. The assertion is unchanged.

Standing down on one more: the engine's session-stream-conformance › filesystem › BR-23 (keeps an unfinished run older than a page of runs listed) didn't fail on this CI run, but it can.

  • It fails on unmodified main: 1 of 2 full engine runs, with no matching event within 10000 ms; got []. The passing run took 8.7 s against a 10 s wait.
  • Cause: on the filesystem store, the stream's opening read of 106 child runs takes ~6.2 s even in isolation. Seeding takes 0.2 s; the in-memory store takes 0.2 s in total.
  • That is a filesystem-store read cost on main, not something this PR touches. I'm not loosening the wait here, because a longer timeout would hide the cost rather than fix it. It's tracked as FIX-1702. If it reddens a run on this PR, a re-run is the answer.

Generated by Claude Code

@jhoffner
jhoffner merged commit e189e1d into main Oct 1, 2026
14 checks passed
jhoffner pushed a commit that referenced this pull request Oct 1, 2026
Post-merge amendment of the retained closure spec (original review #2426):
- names, paths and commands follow the Shift Manager rename (#2588)
- leg c sweeps the promised set: message, reasoning, tool, code block and
  ask cards, plus the devtool page (#2532)
- a4 targets eng.coder's running task session (FIX-1690: #2538/#2544/#2565)
- Part 4's Inbox reply is graded on FIX-1690's test seat (#2525)
- a2 runs without --devtool; Shift Manager serves its own (#2531)

Recorded in DECISIONS -> How it got here, and a new EVOLUTION.md.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq
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.

2 participants