Skip to content
TypeScript

fix(web): mod+enter starts a new thread in the background again (#15060)

Theo Browne263097a8da03
diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts
index fb256f25500..202b5de45c5 100644
--- a/apps/server/src/keybindings.test.ts
+++ b/apps/server/src/keybindings.test.ts
@@ -11,7 +11,7 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ServerConfig from "./config.ts";
import * as Keybindings from "./keybindings.ts";
-import { KeybindingsConfigError } from "@t3tools/contracts";
+import { KeybindingsConfigError, MAX_KEYBINDINGS_COUNT } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
@@ -283,6 +283,76 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
+ it.effect("adds a late default to an existing command once", () =>
+ Effect.gen(function* () {
+ const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+ const keybindings = yield* Keybindings.Keybindings;
+ const when = "composerFocus && draftThreadRoute";
+ const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const;
+ const backgroundRules = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) =>
+ rules.filter((entry) => entry.command === "composer.sendBackground"),
+ );
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
+
+ yield* keybindings.syncDefaultKeybindingsOnStartup;
+ assert.deepStrictEqual(yield* backgroundRules, [
+ existing,
+ { key: "mod+enter", command: "composer.sendBackground", when },
+ ]);
+
+ // Removing the added rule later must survive the next startup.
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
+ yield* keybindings.syncDefaultKeybindingsOnStartup;
+ assert.deepStrictEqual(yield* backgroundRules, [existing]);
+ }).pipe(Effect.provide(makeKeybindingsLayer())),
+ );
+
+ it.effect("leaves a customized command without the late default", () =>
+ Effect.gen(function* () {
+ const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+ const keybindings = yield* Keybindings.Keybindings;
+ const custom = {
+ key: "alt+b",
+ command: "composer.sendBackground",
+ when: "composerFocus && draftThreadRoute",
+ } as const;
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [custom]);
+
+ yield* keybindings.syncDefaultKeybindingsOnStartup;
+ const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
+ assert.deepStrictEqual(
+ persisted.filter((entry) => entry.command === "composer.sendBackground"),
+ [custom],
+ );
+ }).pipe(Effect.provide(makeKeybindingsLayer())),
+ );
+
+ it.effect("keeps a late default pending while the config is full", () =>
+ Effect.gen(function* () {
+ const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+ const keybindings = yield* Keybindings.Keybindings;
+ const when = "composerFocus && draftThreadRoute";
+ const existing = { key: "mod+alt+enter", command: "composer.sendBackground", when } as const;
+ const fillers = Array.from({ length: MAX_KEYBINDINGS_COUNT - 1 }, (_, index) => ({
+ key: "mod+alt+f1",
+ command: `script.filler-${index}.run` as const,
+ }));
+ const hasModEnter = Effect.map(readKeybindingsConfig(keybindingsConfigPath), (rules) =>
+ rules.some(
+ (entry) => entry.command === "composer.sendBackground" && entry.key === "mod+enter",
+ ),
+ );
+
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [existing, ...fillers]);
+ yield* keybindings.syncDefaultKeybindingsOnStartup;
+ assert.isFalse(yield* hasModEnter);
+
+ yield* writeKeybindingsConfig(keybindingsConfigPath, [existing]);
+ yield* keybindings.syncDefaultKeybindingsOnStartup;
+ assert.isTrue(yield* hasModEnter);
+ }).pipe(Effect.provide(makeKeybindingsLayer())),
+ );
+
it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
const messages: string[] = [];
const logger = Logger.make(({ message }) => {
diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts
index 7a1bcd7f356..0484296edd7 100644
--- a/apps/server/src/keybindings.ts
+++ b/apps/server/src/keybindings.ts
@@ -104,6 +104,31 @@ function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): bool
);
}
+// Default rules added to a command after startup sync had already persisted
+// that command. Backfill skips commands a config already has, so startup adds
+// each rule once per config, only next to the untouched earlier default
+// (`alongside`), and records its id. Customized commands and later removals
+// stay as the user set them.
+const LATE_DEFAULT_KEYBINDINGS: ReadonlyArray<{
+ readonly id: string;
+ readonly alongside: KeybindingRule;
+ readonly rule: KeybindingRule;
+}> = [
+ {
+ id: "composer.sendBackground:mod+enter",
+ alongside: {
+ key: "mod+alt+enter",
+ command: "composer.sendBackground",
+ when: "composerFocus && draftThreadRoute",
+ },
+ rule: {
+ key: "mod+enter",
+ command: "composer.sendBackground",
+ when: "composerFocus && draftThreadRoute",
+ },
+ },
+];
+
function keybindingShortcutContext(rule: KeybindingRule): string | null {
const parsed = parseKeybindingShortcut(rule.key);
if (!parsed) return null;
@@ -399,6 +424,32 @@ const make = Effect.gen(function* () {
return { keybindings, issues };
});
+ // One applied migration id per line, next to the config file.
+ const appliedMigrationsPath = path.join(
+ path.dirname(keybindingsConfigPath),
+ "keybindings-migrations",
+ );
+ const readAppliedMigrationIds = fs.readFileString(appliedMigrationsPath).pipe(
+ Effect.map((contents) => new Set(contents.split("\n").filter((line) => line.length > 0))),
+ Effect.orElseSucceed(() => new Set<string>()),
+ );
+ const recordAppliedMigrations = (ids: Iterable<string>) =>
+ writeFileStringAtomically({
+ filePath: appliedMigrationsPath,
+ contents: `${[...new Set(ids)].join("\n")}\n`,
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ Effect.mapError(
+ (cause) =>
+ new KeybindingsConfigError({
+ configPath: keybindingsConfigPath,
+ detail: "failed to record keybinding migrations",
+ cause,
+ }),
+ ),
+ );
+
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
return encodeKeybindingsConfigPrettyJson(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
@@ -450,9 +501,19 @@ const make = Effect.gen(function* () {
const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
Effect.gen(function* () {
+ const appliedMigrationIds = yield* readAppliedMigrationIds;
+ const pendingLateDefaults = LATE_DEFAULT_KEYBINDINGS.filter(
+ (late) => !appliedMigrationIds.has(late.id),
+ );
const configExists = yield* readConfigExists;
if (!configExists) {
yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
+ if (pendingLateDefaults.length > 0) {
+ yield* recordAppliedMigrations([
+ ...appliedMigrationIds,
+ ...LATE_DEFAULT_KEYBINDINGS.map((late) => late.id),
+ ]);
+ }
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
return;
}
@@ -496,6 +557,16 @@ const make = Effect.gen(function* () {
}
missingDefaults.push(defaultRule);
}
+ // The loop above backfills whole missing commands. Late defaults join
+ // an untouched earlier default, when their shortcut is still free.
+ for (const { alongside, rule } of pendingLateDefaults) {
+ if (
+ customConfig.some((entry) => isSameKeybindingRule(entry, alongside)) &&
+ !customConfig.some((entry) => hasSameShortcutContext(entry, rule))
+ ) {
+ missingDefaults.push(rule);
+ }
+ }
for (const conflict of shortcutConflictWarnings) {
yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
path: keybindingsConfigPath,
@@ -506,21 +577,18 @@ const make = Effect.gen(function* () {
reason: "shortcut context already used by existing rule",
});
}
- if (missingDefaults.length === 0) {
- yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
- return;
- }
-
- const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
- customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
- ? Result.succeed(defaultRule.command)
- : Result.failVoid,
- );
- if (matchingDefaults.length > 0) {
- yield* Effect.logWarning("default keybinding rule already defined in user config", {
- path: keybindingsConfigPath,
- commands: matchingDefaults,
- });
+ if (missingDefaults.length > 0) {
+ const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
+ customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
+ ? Result.succeed(defaultRule.command)
+ : Result.failVoid,
+ );
+ if (matchingDefaults.length > 0) {
+ yield* Effect.logWarning("default keybinding rule already defined in user config", {
+ path: keybindingsConfigPath,
+ commands: matchingDefaults,
+ });
+ }
}
// Startup backfill must never evict persisted user rules: append only
@@ -535,12 +603,19 @@ const make = Effect.gen(function* () {
commands: skippedDefaults.map((rule) => rule.command),
});
}
- if (defaultsToAppend.length === 0) {
- yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
- return;
+ if (defaultsToAppend.length > 0) {
+ yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);
+ }
+ // A late default skipped at max entries stays pending for a later start.
+ const settledLateDefaults = pendingLateDefaults.filter(
+ (late) => !skippedDefaults.includes(late.rule),
+ );
+ if (settledLateDefaults.length > 0) {
+ yield* recordAppliedMigrations([
+ ...appliedMigrationIds,
+ ...settledLateDefaults.map((late) => late.id),
+ ]);
}
-
- yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
}),
);
diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts
index 6d81f3be850..f931f9ebc37 100644
--- a/apps/web/src/composer-logic.test.ts
+++ b/apps/web/src/composer-logic.test.ts
@@ -140,7 +140,7 @@ describe("composerSubmissionIntentForKey", () => {
isDraftThread: true,
event: modEnter,
}),
- ).toBe("foreground");
+ ).toBe("background");
expect(
composerSubmissionIntentForKey({ ...running, event: { ...enter, shiftKey: true } }),
).toBeNull();
diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts
index 18604e44e19..c7d69443cdf 100644
--- a/apps/web/src/keybindings.test.ts
+++ b/apps/web/src/keybindings.test.ts
@@ -1287,7 +1287,7 @@ describe("composer and pull request shortcuts", () => {
ctrlKey: platform !== "MacIntel",
};
const queuedKey = event({ key: "Enter", shiftKey: true, ...modifier });
- const backgroundKey = event({ key: "Enter", altKey: true, ...modifier });
+ const backgroundKey = event({ key: "Enter", ...modifier });
assert.strictEqual(
resolveShortcutCommand(queuedKey, DEFAULT_RESOLVED_KEYBINDINGS, {
platform,
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index 63c9577767a..e305b30510e 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -12,11 +12,11 @@ inserts a new line. This applies to the web and desktop composer at desktop widt
**Follow-up behavior** chooses Queue or Steer while the agent runs. Use
`mod+Enter` to do the opposite for one message, even when the send shortcut
requires a modifier. `mod+Alt+Enter` sends, keeps that thread running in the
-background, and opens a fresh new-thread composer. Change these
-shortcuts in **Settings → Keybindings** under **Composer: Opposite Queue or
-Steer Action**, **Composer: Start in Background**, or **Composer: Send and Start
-New Thread**. These bindings take priority over the send shortcut. Click the
-send button to use the configured follow-up behavior.
+background, and opens a fresh new-thread composer. In a new thread, `mod+Enter`
+does the same. Change these shortcuts in **Settings → Keybindings** under
+**Composer: Opposite Queue or Steer Action**, **Composer: Start in Background**,
+or **Composer: Send and Start New Thread**. These bindings take priority over the
+send shortcut. Click the send button to use the configured follow-up behavior.
When an active turn has queued messages, `mod+Shift+Enter` sends the first as a
steer. Change it under **Queue: Send First Queued Message as Steer** in Keybindings.
diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts
index 8cb3fee23e0..634945fe0e6 100644
--- a/packages/shared/src/keybindings.ts
+++ b/packages/shared/src/keybindings.ts
@@ -48,6 +48,11 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" },
{ key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" },
{ key: "mod+enter", command: "composer.sendAlternate", when: "composerFocus && turnRunning" },
+ {
+ key: "mod+enter",
+ command: "composer.sendBackground",
+ when: "composerFocus && draftThreadRoute",
+ },
{
key: "mod+alt+enter",
command: "composer.sendBackground",