Skip to content
TypeScript

Add stop thread keybinding command (#4308)

Jake Leventhal09e8de9c655a
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 537828e0e06..51ced02334d 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -32,6 +32,7 @@ import {
branchMismatchKey,
buildExpiredTerminalContextToastCopy,
buildLoadingThreadFromShell,
+ buildRunningThreadTurnInterruptInput,
buildThreadTurnInterruptInput,
createLocalDispatchSnapshot,
deriveComposerSendState,
@@ -906,6 +907,20 @@ describe("buildThreadTurnInterruptInput", () => {
threadId,
});
});
+
+ it("omits a turn id when a running session has not projected its active turn yet", () => {
+ expect(
+ buildThreadTurnInterruptInput(
+ makeThread({
+ session: {
+ ...readySession,
+ status: "running",
+ activeTurnId: null,
+ },
+ }),
+ ),
+ ).toEqual({ threadId });
+ });
});
describe("resolveComposerProviderSelection", () => {
@@ -1266,6 +1281,41 @@ describe("resolveComposerInteractionMode", () => {
});
});
+describe("buildRunningThreadTurnInterruptInput", () => {
+ it("targets only the active turn of a running thread", () => {
+ const activeTurnId = TurnId.make("turn-running");
+ const runningThread = makeThread({
+ session: {
+ ...readySession,
+ status: "running",
+ activeTurnId,
+ },
+ });
+
+ expect(buildRunningThreadTurnInterruptInput(runningThread, "running")).toEqual({
+ threadId,
+ turnId: activeTurnId,
+ });
+ expect(buildRunningThreadTurnInterruptInput(runningThread, "ready")).toBeNull();
+ expect(
+ buildRunningThreadTurnInterruptInput(makeThread({ session: readySession }), "ready"),
+ ).toBeNull();
+ expect(buildRunningThreadTurnInterruptInput(null, "disconnected")).toBeNull();
+ });
+
+ it("targets a running thread before its active turn has been projected", () => {
+ const runningThread = makeThread({
+ session: {
+ ...readySession,
+ status: "running",
+ activeTurnId: null,
+ },
+ });
+
+ expect(buildRunningThreadTurnInterruptInput(runningThread, "running")).toEqual({ threadId });
+ });
+});
+
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
const state = deriveComposerSendState({
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 03770bf20fc..b918a466ba1 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -507,6 +507,16 @@ export function getAntigravitySendBlockReason(
return null;
}
+export function buildRunningThreadTurnInterruptInput(
+ thread: Pick<Thread, "id" | "session"> | null | undefined,
+ phase: SessionPhase,
+): { threadId: ThreadId; turnId?: TurnId } | null {
+ if (phase !== "running" || thread?.session?.status !== "running") {
+ return null;
+ }
+ return buildThreadTurnInterruptInput(thread);
+}
+
export function reconcileMountedTerminalThreadIds(input: {
currentThreadIds: ReadonlyArray<string>;
openThreadIds: ReadonlyArray<string>;
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 6d1906ff975..7d5e9c9b153 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -239,6 +239,7 @@ import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl"
import { useThreadActions } from "../hooks/useThreadActions";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { confirmTerminalClose, isTerminalCloseConfirmPending } from "../lib/terminalCloseConfirm";
+import { isPreviewFocused } from "../lib/previewFocus";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
import {
preventRepeatedTerminalCloseShortcut,
@@ -361,6 +362,7 @@ import {
buildExpiredTerminalContextToastCopy,
buildLocalDraftThread,
buildLoadingThreadFromShell,
+ buildRunningThreadTurnInterruptInput,
buildThreadTurnInterruptInput,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
@@ -3410,6 +3412,27 @@ export default function ChatView(props: ChatViewProps) {
[activeServerThread, draftId, routeThreadKey, routeThreadRef],
);
+ const interruptContextRef = useRef({ activeThread, phase, setThreadError });
+ interruptContextRef.current = { activeThread, phase, setThreadError };
+ const onInterrupt = useCallback(async () => {
+ const { activeThread, phase, setThreadError } = interruptContextRef.current;
+ const input = buildRunningThreadTurnInterruptInput(activeThread, phase);
+ if (!input || !activeThread) return;
+ const result = await interruptThreadTurn({
+ environmentId: activeThread.environmentId,
+ input,
+ });
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ setThreadError(
+ activeThread.id,
+ error instanceof Error ? error.message : "Failed to interrupt the current turn.",
+ );
+ }
+ }, [interruptThreadTurn]);
+ const canInterruptRunningThread =
+ buildRunningThreadTurnInterruptInput(activeThread, phase) !== null;
+
const focusComposer = useCallback(() => {
composerRef.current?.focusAtEnd();
}, [composerRef]);
@@ -5877,6 +5900,8 @@ export default function ChatView(props: ChatViewProps) {
const shortcutContext = {
terminalFocus: terminalFocusOwner !== null,
terminalOpen: Boolean(terminalUiState.terminalOpen),
+ previewFocus: isPreviewFocused(),
+ previewOpen: previewPanelOpen,
modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
};
@@ -6047,6 +6072,16 @@ export default function ChatView(props: ChatViewProps) {
return;
}
+ if (command === "thread.stop") {
+ // An unavailable command should not shadow contextual shortcuts such as Escape to close a dialog.
+ if (!canInterruptRunningThread) return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.repeat) return;
+ void onInterrupt();
+ return;
+ }
+
const scriptId = projectScriptIdFromCommand(command);
if (!scriptId || !activeProject) return;
const script = activeProjectScripts.find((entry) => entry.id === scriptId);
@@ -6065,6 +6100,7 @@ export default function ChatView(props: ChatViewProps) {
activeThreadRef,
activeThreadPinned,
activeThreadSettled,
+ canInterruptRunningThread,
terminalUiState.terminalOpen,
terminalUiState.activeTerminalId,
activeThreadId,
@@ -6079,6 +6115,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings,
handleUnsettleActiveThread,
isServerThread,
+ onInterrupt,
onToggleDiff,
pinThread,
settleThread,
@@ -6086,6 +6123,7 @@ export default function ChatView(props: ChatViewProps) {
supportsSettlement,
confirmAndUnpinThread,
copyActiveThreadReference,
+ previewPanelOpen,
toggleRightPanel,
toggleRightPanelMaximized,
toggleTerminalVisibility,
@@ -6951,21 +6989,6 @@ export default function ChatView(props: ChatViewProps) {
}
};
- const onInterrupt = async () => {
- if (!activeThread) return;
- const result = await interruptThreadTurn({
- environmentId,
- input: buildThreadTurnInterruptInput(activeThread),
- });
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
- setThreadError(
- activeThread.id,
- error instanceof Error ? error.message : "Failed to interrupt the current turn.",
- );
- }
- };
-
const onRespondToApproval = useCallback(
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
if (!activeThreadId) return;
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
index dd6750b0c41..286eb83f57b 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
+import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import {
buildKeybindingRows,
@@ -149,7 +150,7 @@ describe("KeybindingsSettings.logic", () => {
expect(options).not.toContain("customModeActive");
});
- it("builds command options from built-in commands and resolved project bindings", () => {
+ it("builds command options from all static commands and resolved project bindings", () => {
const options = buildKeybindingCommandOptions([
{
command: "script.setup-db.run",
@@ -165,7 +166,15 @@ describe("KeybindingsSettings.logic", () => {
] satisfies ResolvedKeybindingsConfig);
expect(options).toEqual(
- expect.arrayContaining(["chat.new", "rightPanel.toggleMaximized", "script.setup-db.run"]),
+ expect.arrayContaining([
+ "chat.new",
+ "rightPanel.toggleMaximized",
+ "thread.stop",
+ "script.setup-db.run",
+ ]),
+ );
+ expect(DEFAULT_RESOLVED_KEYBINDINGS.some((binding) => binding.command === "thread.stop")).toBe(
+ false,
);
});
diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts
index df005571193..97ef43b6571 100644
--- a/apps/web/src/keybindings.test.ts
+++ b/apps/web/src/keybindings.test.ts
@@ -738,6 +738,42 @@ describe("cross-command precedence", () => {
});
describe("resolveShortcutCommand", () => {
+ it("resolves a custom stop-thread shortcut", () => {
+ const keybindings = compile([{ shortcut: modShortcut("escape"), command: "thread.stop" }]);
+
+ assert.strictEqual(
+ resolveShortcutCommand(event({ key: "Escape", metaKey: true }), keybindings, {
+ platform: "MacIntel",
+ }),
+ "thread.stop",
+ );
+ });
+
+ it("honors preview conditions for a stop-thread shortcut", () => {
+ const keybindings = compile([
+ {
+ shortcut: modShortcut("escape"),
+ command: "thread.stop",
+ whenAst: whenIdentifier("previewFocus"),
+ },
+ ]);
+ const input = event({ key: "Escape", metaKey: true });
+
+ assert.isNull(
+ resolveShortcutCommand(input, keybindings, {
+ platform: "MacIntel",
+ context: { previewFocus: false },
+ }),
+ );
+ assert.strictEqual(
+ resolveShortcutCommand(input, keybindings, {
+ platform: "MacIntel",
+ context: { previewFocus: true },
+ }),
+ "thread.stop",
+ );
+ });
+
it("returns dynamic script commands", () => {
const keybindings = compile([{ shortcut: modShortcut("r"), command: "script.setup.run" }]);
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index 1c90b5351d3..4e46e97a3a5 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -53,6 +53,9 @@ a shortcut.
## Commands with special behavior
+`thread.stop` interrupts the running turn in the focused thread. It has no default
+shortcut; assign one in **Settings → Keybindings**.
+
`chat.new` may ask you to choose a project when there is more than one.
`chat.newLocal` skips that chooser. Both use your
[new-thread defaults](./thread-sidebar.md#start-a-thread).
diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts
index 411cff23c82..27e096cbb2e 100644
--- a/packages/contracts/src/keybindings.test.ts
+++ b/packages/contracts/src/keybindings.test.ts
@@ -121,6 +121,12 @@ it.effect("parses keybinding rules", () =>
when: "!terminalFocus",
});
assert.strictEqual(parsedThreadCopyReference.command, "thread.copyReference");
+
+ const parsedThreadStop = yield* decode(KeybindingRule, {
+ key: "mod+escape",
+ command: "thread.stop",
+ });
+ assert.strictEqual(parsedThreadStop.command, "thread.stop");
}),
);
diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts
index 43e7645b3eb..f2ba64d6a86 100644
--- a/packages/contracts/src/keybindings.ts
+++ b/packages/contracts/src/keybindings.ts
@@ -35,6 +35,7 @@ export type ModelPickerJumpKeybindingCommand =
(typeof MODEL_PICKER_JUMP_KEYBINDING_COMMANDS)[number];
const THREAD_KEYBINDING_COMMANDS = [
+ "thread.stop",
"thread.previous",
"thread.next",
"thread.copyReference",