Skip to content

Count a chat cancel once, and only while a response streams - #274

Open
jerelvelarde wants to merge 1 commit into
a2ui-project:mainfrom
jerelvelarde:jerel/cancel-stream-idle-guard
Open

jerelvelarde wants to merge 1 commit into
a2ui-project:mainfrom
jerelvelarde:jerel/cancel-stream-idle-guard

Conversation

@jerelvelarde

Copy link
Copy Markdown
Contributor

The new tests fail on #269's guard and pass with this one

The problem

#269 sends every cancel through ChatCoordinator.cancelStream(), which decides whether there is
anything to cancel by checking activePromptId. That ID keeps its value after a response finishes
or fails. So New Session after a finished response records a user cancel (trackChatCancel) for a
response that had already ended. Gemini Code Assist pointed this out on #269.

Two more cases share the cause. Pressing Stop twice while a response is still connecting records two
cancels. And a renderer change right after Stop replaces the user's reason, so the chat says "This
response was stopped because the renderer changed" instead of "You stopped this response." The
telemetry only reaches analytics in builds that turn usage tracking on, but the wrong chat note shows
for everyone.

The approach

cancelStream now returns early unless a response is streaming and no cancel is already under way.
"Streaming" is isProgrammaticStreamActive(), which submitPrompt sets and which is cleared once
the response is written to the canvas, fails, or stops after a cancel. "Under way" is a non-null
cancelReason: a cancel was requested, but the response hasn't failed with the cancel error yet. The
first cancel's reason wins.

activePromptId stays in the check because it narrows the type for trackChatCancel. It is not
cleared when the response finishes, which would have been the other fix: submitPrompt's catch
block drops errors from a prompt whose ID no longer matches, and validation errors are thrown after
the stream ends, so clearing the ID there hides them. Two existing tests fail if it is cleared. The
comment above the guard says what each condition is for and why.

What is not covered

  • ChatState's own JSDoc for the streaming signal still calls it a lock against typing deadlocks.
    Only the coordinator's JSDoc changed.
  • Older coordinator tests that poll with setInterval or build promises by hand are unchanged.
  • There is no browser recording. Usage tracking is off in the open-source build, and the reason race
    takes place within one microtask, so the recording runs the new tests against fix(chat): keep the canvas and conversation when switching renderers #269's guard and this
    one.

Verification

Six new tests in chat-coordinator.spec.ts. Each fails on main's guard (37744e6, #269) and passes here:

  • does not track a cancel when a new session starts after a response completes
  • does not track a cancel when a new session starts after a response fails
  • ignores a second Stop while the response is still connecting
  • ignores a second Stop while the first Stop is cancelling the response
  • keeps the Stop note when the renderer changes while Stop is cancelling the response
  • ignores Stop while a renderer change is cancelling the response

They reuse createStreamAwaitingCancel, which gained a holdCancel option so a test can release
the cancel error when it chooses. The full shell suite passes: 1,799 tests,
with coverage. ESLint and Prettier pass on the changed files.

Merge notes

#216 adds half of this guard (|| this.cancelReason !== null) in its first Slack commit. Whichever
of the two lands second keeps this condition.

cancelStream() only checked activePromptId, which keeps its value after
a response completes or fails. So New Session after a finished response
recorded a user cancel in telemetry. It also didn't check for a cancel
already under way: pressing Stop twice recorded two cancels, and a
renderer change right after Stop replaced the user's cancel reason, so
the chat showed the renderer note instead of the Stop note.

Return early unless a response is still streaming and no cancel is
under way. The first cancel's reason wins.

activePromptId stays set after a response finishes: submitPrompt's
catch block drops errors from a prompt that is no longer active, and
validation errors are thrown after the stream finishes, so clearing it
there would hide them.

@gemini-code-assist gemini-code-assist 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 Review

This pull request refactors stream cancellation logic in ChatCoordinator to prevent redundant cancellations and handle cases where no response is streaming, accompanied by comprehensive unit tests. The review feedback highlights a critical issue in the new tests where the non-standard Vitest matcher toHaveBeenCalledExactlyOnceWith is used, which will cause runtime TypeErrors; it is recommended to split this into separate call count and argument assertions. Additionally, the custom createDeferred helper could be simplified using native Promise.withResolvers() if the environment supports it.

Comment on lines +1126 to +1130
expect(trackChatCancel).toHaveBeenCalledExactlyOnceWith({
promptId: 'prompt-1',
turnIndex: 1,
pipelineStatus: PipelineStatus.RECEIVING_STREAM,
});

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.

high

The matcher toHaveBeenCalledExactlyOnceWith is not a standard Vitest or Jest matcher and will cause a runtime TypeError during test execution. In Vitest, you should assert the call count and the arguments separately using toHaveBeenCalledTimes(1) and toHaveBeenCalledWith(...) to match the established testing patterns in this codebase.

      expect(trackChatCancel).toHaveBeenCalledTimes(1);
      expect(trackChatCancel).toHaveBeenCalledWith({
        promptId: 'prompt-1',
        turnIndex: 1,
        pipelineStatus: PipelineStatus.RECEIVING_STREAM,
      });

Comment on lines +1145 to +1149
expect(trackChatCancel).toHaveBeenCalledExactlyOnceWith({
promptId: 'prompt-1',
turnIndex: 1,
pipelineStatus: PipelineStatus.RECEIVING_STREAM,
});

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.

high

The matcher toHaveBeenCalledExactlyOnceWith is not a standard Vitest or Jest matcher and will cause a runtime TypeError during test execution. In Vitest, you should assert the call count and the arguments separately using toHaveBeenCalledTimes(1) and toHaveBeenCalledWith(...) to match the established testing patterns in this codebase.

      expect(trackChatCancel).toHaveBeenCalledTimes(1);
      expect(trackChatCancel).toHaveBeenCalledWith({
        promptId: 'prompt-1',
        turnIndex: 1,
        pipelineStatus: PipelineStatus.RECEIVING_STREAM,
      });

Comment on lines +124 to +132
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((onResolve, onReject) => {
resolve = onResolve;
reject = onReject;
});
return {promise, resolve, reject};
}

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.

medium

If your TypeScript and Node.js environment supports ES2024 (TypeScript 5.4+ and Node.js 22+), you can simplify this code by using the native Promise.withResolvers() instead of implementing a custom createDeferred helper function.

function createDeferred<T>() {
  return Promise.withResolvers<T>();
}

This branch has not been deployed

No deployments
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