Compare commits

..
Author SHA1 Message Date
Mohamed Boudra d71ac161e8 fix(app): stop Cmd/Ctrl+click from entering sidebar select mode
Holding Cmd to preview sidebar jump badges or rolling off shortcuts like Cmd+Tab or Cmd+B before clicking a workspace row accidentally entered sticky multi-select mode. Outside select mode, only Shift+click (without Cmd/Ctrl) and the row menu now enter select mode; once select mode is active, Cmd/Ctrl+click and plain clicks continue to toggle rows and Shift+click continues to adjust ranges.

Also make readPressModifiers trust explicit boolean modifier flags on non-touch pointer events instead of ORing with the held-key tracker, so a swallowed key-up cannot cause phantom modifier clicks on desktop while keeping the fallback for native and touch-synthesized presses.
2026-11-30 17:56:44 +01:00
20 changed files with 152 additions and 196 deletions
@@ -1,11 +1,5 @@
import { expect, test, type Page } from "../support/fixtures";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import {
attachImageFromMenu,
composerLocator,
expectComposerVisible,
submitMessage,
} from "../support/helpers/composer";
import { composerLocator, expectComposerVisible, submitMessage } from "../support/helpers/composer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSessionRowArchived,
@@ -146,47 +140,6 @@ async function waitForReplacementAgentId(page: Page, oldAgentId: string): Promis
}
test.describe("Client slash commands", () => {
test("keeps the draft when a typed plugin slash command has an attachment", async ({ page }) => {
test.setTimeout(90_000);
await withDirectoryPlugin({
pluginId: "attachment-slash-e2e",
source: `
export default function contribute(client) {
client.addSlashCommand({name:"picture", description:"Review an attached picture", argumentHint:"<question>", context:"agent",
onSubmit(){throw new Error("Plugin handler unexpectedly received this command");}});
return () => {};
}`,
run: async () => {
await withOpenReadyMockAgent(page, { title: "Attached slash command" }, async () => {
const input = composerLocator(page);
await input.fill("/pict");
await expect(
page.getByText("Review an attached picture", { exact: true }).first(),
).toBeVisible();
await input.fill("");
await attachImageFromMenu(page, {
name: "picture.png",
mimeType: "image/png",
buffer: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
});
await input.fill("/picture what is this?");
await input.press("Enter");
await expect(
page.getByRole("alert").filter({ hasText: "Remove attachments to run /picture." }),
).toBeVisible();
await expect(input).toHaveValue("/picture what is this?");
await expect(page.getByTestId("composer-image-attachment-pill")).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: "/picture what is this?" }),
).toHaveCount(0);
});
},
});
});
test("slash quit archives the active agent and removes its tab", async ({ page }) => {
await withOpenReadyMockAgent(page, { title: "Slash quit e2e" }, async ({ agentId, title }) => {
await runClientSlashCommand(page, "/quit");
@@ -52,17 +52,28 @@ async function exitSelection(page: Page) {
}
/**
* Walks the Finder click matrix on four rows, starting with the first row open: a modifier click
* from normal mode selects only the clicked row, Cmd/Ctrl+click toggles, Shift+click extends and
* shrinks a range from the anchor, and plain clicks keep toggling while select mode is on.
* Walks the sidebar selection click matrix on four rows: Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click)
* from normal mode navigates instead of entering select mode, Shift+click enters select mode on the
* clicked row alone, Cmd/Ctrl+click and plain clicks toggle while select mode is active, and
* Shift+click extends, shrinks, and flips a range from the anchor.
*/
async function exerciseClickMatrix(page: Page, rows: readonly Locator[]) {
const [first, second, third, fourth] = rows;
await first.click();
await expect(first).toHaveAttribute("aria-selected", "true");
// Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode navigate normally.
await third.click({ modifiers: [MOD] });
await expect(third).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
await first.click({ modifiers: [MOD, "Shift"] });
await expect(first).toHaveAttribute("aria-selected", "true");
await expect(page.getByTestId("workspace-selection-toast")).toHaveCount(0);
const openWorkspaceUrl = page.url();
await third.click({ modifiers: [MOD] });
// Shift+click enters select mode on the clicked row alone; Cmd/Ctrl+click and plain clicks toggle.
await third.click({ modifiers: ["Shift"] });
await expectSelectedCount(page, 1);
await expectChecked(rows, [false, false, true, false]);
@@ -102,7 +113,7 @@ test.describe("sidebar workspace selection clicks", () => {
seeded = null;
});
test("Cmd/Ctrl+click and Shift+click select like Finder in project grouping", async ({
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in project grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
@@ -111,7 +122,9 @@ test.describe("sidebar workspace selection clicks", () => {
await exerciseClickMatrix(page, await rowsInSidebarOrder(page, seeded.workspaceIds));
});
test("Cmd/Ctrl+click and Shift+click select like Finder in status grouping", async ({ page }) => {
test("Shift+click enters select mode while Cmd/Ctrl+click navigates in status grouping", async ({
page,
}) => {
seeded = await seedProjectWithWorkspaces(4);
await gotoAppShell(page);
await waitForSidebarHydration(page);
+7 -19
View File
@@ -1671,16 +1671,7 @@ function ComposerContentImpl({
);
const runPluginClientSlashCommand = useCallback(
(
resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string },
hasAttachments: boolean,
) => {
if (hasAttachments) {
setSendError(
t("composer.errors.removePluginCommandAttachments", { command: resolved.command.name }),
);
return;
}
(resolved: { command: (typeof pluginClientSlashCommands)[number]; args: string }): boolean => {
if (blurOnSubmit) messageInputRef.current?.blur();
clearDraft("sent");
replaceUserInput("");
@@ -1695,8 +1686,9 @@ function ComposerContentImpl({
toastErrorRef.current(error instanceof Error ? error.message : String(error));
},
});
return true;
},
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments],
);
const { pickImages } = useImageAttachmentPicker();
@@ -1996,12 +1988,10 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -2271,12 +2261,10 @@ function ComposerContentImpl({
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (pluginSlashCommand && runPluginClientSlashCommand(pluginSlashCommand)) return;
queueMessage(payload.text, outgoingAttachments);
},
[
-1
View File
@@ -195,7 +195,6 @@ export const ar: TranslationResources = {
removeReview: "إزالة مرفق المراجعة",
},
errors: {
removePluginCommandAttachments: "أزل المرفقات لتشغيل الأمر /{{command}}.",
failedToSend: "فشل في إرسال الرسالة",
failedToCreateAgent: "فشل في إنشاء الوكيل",
noHostSelected: "لم يتم تحديد مضيف",
-1
View File
@@ -193,7 +193,6 @@ export const en = {
removeReview: "Remove review attachment",
},
errors: {
removePluginCommandAttachments: "Remove attachments to run /{{command}}.",
failedToSend: "Failed to send message",
failedToCreateAgent: "Failed to create agent",
noHostSelected: "No host selected",
-1
View File
@@ -196,7 +196,6 @@ export const es: TranslationResources = {
removeReview: "Eliminar archivo adjunto de reseña",
},
errors: {
removePluginCommandAttachments: "Quita los archivos adjuntos para ejecutar /{{command}}.",
failedToSend: "No se pudo enviar el mensaje",
failedToCreateAgent: "No se pudo crear el agente",
noHostSelected: "Ningún anfitrión seleccionado",
-1
View File
@@ -197,7 +197,6 @@ export const fr: TranslationResources = {
removeReview: "Retirer la revue jointe",
},
errors: {
removePluginCommandAttachments: "Retirez les pièces jointes pour exécuter /{{command}}.",
failedToSend: "Impossible d’envoyer le message",
failedToCreateAgent: "Impossible de créer l’agent",
noHostSelected: "Aucun hôte sélectionné",
-1
View File
@@ -196,7 +196,6 @@ export const ja: TranslationResources = {
removeReview: "レビュー添付ファイルを削除",
},
errors: {
removePluginCommandAttachments: "/{{command}} を実行するには添付ファイルを削除してください。",
failedToSend: "メッセージの送信に失敗しました",
failedToCreateAgent: "エージェントの作成に失敗しました",
noHostSelected: "ホストが選択されていません",
-1
View File
@@ -195,7 +195,6 @@ export const ko: TranslationResources = {
removeReview: "리뷰 첨부 제거",
},
errors: {
removePluginCommandAttachments: "/{{command}} 명령을 실행하려면 첨부 파일을 제거하세요.",
failedToSend: "메시지를 보내지 못했습니다",
failedToCreateAgent: "에이전트를 생성하지 못했습니다",
noHostSelected: "선택된 호스트가 없습니다",
-1
View File
@@ -196,7 +196,6 @@ export const ptBR: TranslationResources = {
removeReview: "Remover anexo de revisão",
},
errors: {
removePluginCommandAttachments: "Remova os anexos para executar /{{command}}.",
failedToSend: "Falha ao enviar mensagem",
failedToCreateAgent: "Falha ao criar agente",
noHostSelected: "Nenhum host selecionado",
-1
View File
@@ -196,7 +196,6 @@ export const ru: TranslationResources = {
removeReview: "Удалить вложение проверки",
},
errors: {
removePluginCommandAttachments: "Чтобы выполнить /{{command}}, удалите вложения.",
failedToSend: "Не удалось отправить сообщение",
failedToCreateAgent: "Не удалось создать агента.",
noHostSelected: "Хост не выбран",
-1
View File
@@ -195,7 +195,6 @@ export const zhCN: TranslationResources = {
removeReview: "移除 review 附件",
},
errors: {
removePluginCommandAttachments: "请先移除附件,再运行 /{{command}}。",
failedToSend: "发送消息失败",
failedToCreateAgent: "创建 Agent 失败",
noHostSelected: "未选择 Host",
@@ -93,19 +93,54 @@ export function readPressModifiers(
context: PressModifierContext = { isMac: getShortcutOs() === "mac", held: heldModifiers },
): PressModifiers {
const modKey: HeldModifierKey = context.isMac ? "Meta" : "Control";
const trustEventFlags = !isTouchPressEvent(event);
return {
shift: hasPressFlag(event, "shiftKey") || context.held.isDown("Shift"),
mod: hasPressFlag(event, MODIFIER_FLAGS[modKey]) || context.held.isDown(modKey),
shift: resolveModifierFlag(event, "shiftKey", "Shift", trustEventFlags, context.held),
mod: resolveModifierFlag(event, MODIFIER_FLAGS[modKey], modKey, trustEventFlags, context.held),
};
}
function hasPressFlag(event: unknown, flag: "shiftKey" | "metaKey" | "ctrlKey"): boolean {
if (typeof event !== "object" || event === null) return false;
if (Reflect.get(event, flag) === true) return true;
function resolveModifierFlag(
event: unknown,
flag: "shiftKey" | "metaKey" | "ctrlKey",
heldKey: HeldModifierKey,
trustEventFlags: boolean,
held: Pick<HeldModifierTracker, "isDown">,
): boolean {
const eventFlag = readPressFlag(event, flag);
if (trustEventFlags && eventFlag !== undefined) {
return eventFlag;
}
return eventFlag === true || held.isDown(heldKey);
}
function readPressFlag(
event: unknown,
flag: "shiftKey" | "metaKey" | "ctrlKey",
): boolean | undefined {
if (typeof event !== "object" || event === null) return undefined;
const direct = Reflect.get(event, flag);
if (typeof direct === "boolean") return direct;
const nativeEvent = Reflect.get(event, "nativeEvent");
if (typeof nativeEvent !== "object" || nativeEvent === null) return undefined;
const nativeFlag = Reflect.get(nativeEvent, flag);
return typeof nativeFlag === "boolean" ? nativeFlag : undefined;
}
function isTouchPressEvent(event: unknown): boolean {
if (typeof event !== "object" || event === null) return false;
return isTouchEventRecord(event) || isTouchEventRecord(Reflect.get(event, "nativeEvent"));
}
function isTouchEventRecord(record: unknown): boolean {
if (typeof record !== "object" || record === null) return false;
if (Reflect.get(record, "pointerType") === "touch") return true;
const type = Reflect.get(record, "type");
if (typeof type === "string" && type.startsWith("touch")) return true;
const sourceCapabilities = Reflect.get(record, "sourceCapabilities");
return (
typeof nativeEvent === "object" &&
nativeEvent !== null &&
Reflect.get(nativeEvent, flag) === true
typeof sourceCapabilities === "object" &&
sourceCapabilities !== null &&
Reflect.get(sourceCapabilities, "firesTouchEvents") === true
);
}
@@ -407,6 +407,45 @@ describe("press modifiers", () => {
mod: false,
});
});
it("trusts explicit boolean flags on non-touch pointer events over stale held keys", async () => {
const { createHeldModifierTracker, readPressModifiers } =
await import("./internal/press-modifiers");
const held = createHeldModifierTracker();
// Simulate a missed key-up (e.g. OS overlay or native menu swallowing release).
held.handleKeyDown(modifierKey("Shift", "ShiftLeft", { shiftKey: true }));
held.handleKeyDown(modifierKey("Meta", "MetaLeft", { shiftKey: true, metaKey: true }));
const mouseClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "mouse" },
};
expect(readPressModifiers(mouseClick, { isMac: true, held })).toEqual({
shift: false,
mod: false,
});
// Touch-synthesized clicks on web may report false modifier flags while a hardware key is held.
const touchPointerClick = {
nativeEvent: { shiftKey: false, metaKey: false, ctrlKey: false, pointerType: "touch" },
};
expect(readPressModifiers(touchPointerClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
const touchCapabilityClick = {
nativeEvent: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
sourceCapabilities: { firesTouchEvents: true },
},
};
expect(readPressModifiers(touchCapabilityClick, { isMac: true, held })).toEqual({
shift: true,
mod: true,
});
});
});
describe("non-TextInput native focus registration", () => {
@@ -33,12 +33,14 @@ describe("plugin client slash commands", () => {
expect(
resolvePluginClientSlashCommand({
text: " /review foo bar ",
hasAttachments: false,
commands: [command],
}),
).toEqual({ command, args: "foo bar" });
expect(
resolvePluginClientSlashCommand({
text: "/another-command foo",
text: "/review foo",
hasAttachments: true,
commands: [command],
}),
).toBeNull();
@@ -47,8 +47,10 @@ export function mergeSlashCommandSources<
export function resolvePluginClientSlashCommand<Command extends SlashCommandDescriptor>(input: {
text: string;
hasAttachments: boolean;
commands: readonly Command[];
}): { command: Command; args: string } | null {
if (input.hasAttachments) return null;
const match = /^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(input.text.trim());
if (!match) return null;
const command = input.commands.find((candidate) => candidate.name === match[1]);
@@ -218,14 +218,24 @@ async function slowClick(element: HTMLElement) {
const MOD_KEY = getShortcutOs() === "mac" ? "Meta" : "Control";
describe("sidebar workspace row presses", () => {
it("enters select mode on the Cmd/Ctrl+clicked row alone and toggles rows without navigating", async () => {
it("navigates on Cmd/Ctrl+click and Cmd/Ctrl+Shift+click outside select mode, and toggles with Cmd/Ctrl+click once active", async () => {
mountHost(["a", "b", "c", "d"].map(makeEntry));
await userEvent.click(row("a"));
expect(navigatedKeys).toEqual(["srv:a"]);
expect(useSidebarSelectionStore.getState().active).toBe(false);
// Cmd/Ctrl+click (and Cmd/Ctrl+Shift+click) must not enter select mode from idle.
await userEvent.click(row("c"), { modifiers: [MOD_KEY] });
expect(useSidebarSelectionStore.getState().active).toBe(false);
expect(navigatedKeys).toEqual(["srv:a", "srv:c"]);
await userEvent.click(row("d"), { modifiers: [MOD_KEY, "Shift"] });
expect(useSidebarSelectionStore.getState().active).toBe(false);
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
// Once select mode is entered (e.g. via Shift+click), Cmd/Ctrl+click and plain clicks toggle.
await userEvent.click(row("c"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["c"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
@@ -238,31 +248,38 @@ describe("sidebar workspace row presses", () => {
// Plain clicks keep toggling while select mode is on.
await userEvent.click(row("a"));
expect(selectedIds()).toEqual(["a", "b", "d"]);
expect(navigatedKeys).toEqual(["srv:a"]);
expect(navigatedKeys).toEqual(["srv:a", "srv:c", "srv:d"]);
});
it("selects on the first modifier or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b"].map(makeEntry));
it("selects on the first Shift+click or select-mode click after an earlier gesture ended as a long press", async () => {
mountHost(["a", "b", "c"].map(makeEntry));
// A scroll, swipe, drag, or long-press menu leaves the flag set without firing onPress.
// Ctrl+click on Windows/Linux gets no press-in on web, so nothing clears it first.
markGestureCanceled("a");
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
await userEvent.click(row("a"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["a"]);
markGestureCanceled("b");
await userEvent.click(row("b"));
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a", "b"]);
markGestureCanceled("c");
await userEvent.click(row("c"));
expect(selectedIds()).toEqual(["a", "b", "c"]);
});
it("opens a row on a slow click and still selects it on the next Cmd/Ctrl+click", async () => {
it("opens a row on a slow click and still selects it on the next Shift+click and Cmd/Ctrl+click", async () => {
mountHost(["a", "b"].map(makeEntry));
await act(() => slowClick(row("a")));
expect(navigatedKeys).toEqual(["srv:a"]);
await userEvent.click(row("a"), { modifiers: [MOD_KEY] });
await userEvent.click(row("a"), { modifiers: ["Shift"] });
expect(selectedIds()).toEqual(["a"]);
await userEvent.click(row("b"), { modifiers: [MOD_KEY] });
expect(selectedIds()).toEqual(["a", "b"]);
});
it("enters select mode on the Shift+clicked row alone, then extends and shrinks the range", async () => {
@@ -12,10 +12,12 @@ interface WorkspaceSelectionPressInput {
}
/**
* Routes a sidebar workspace row press between navigation and select mode, Finder-style:
* Shift+click selects a range, Cmd+click (Ctrl+click off macOS) toggles one row, and either one
* enters select mode on the clicked row alone. In select mode every press selects, so touch and
* mouse users can keep tapping without a modifier.
* Routes a sidebar workspace row press between navigation and select mode:
* - Outside select mode, Shift+click (without Cmd/Ctrl) enters select mode on the clicked row
* alone; plain clicks and Cmd/Ctrl+clicks navigate normally so shortcut rollover and Cmd-held
* badge peeks never trigger bulk selection.
* - Inside select mode, Shift+click selects a Finder-style range from the anchor, and plain clicks
* or Cmd/Ctrl+clicks toggle one row without navigating.
*
* Selecting presses never consult the row's long-press flag. They never arm the long-press
* gesture, a native long press already cancels the press, and react-native-web gives Ctrl+click
@@ -30,7 +32,7 @@ export function useWorkspaceSelectionPress({
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
const store = useSidebarSelectionStore.getState();
if (!store.active && !modifiers.shift && !modifiers.mod) {
if (!store.active && (!modifiers.shift || modifiers.mod)) {
onNavigate();
return;
}
@@ -43,12 +45,14 @@ export function useWorkspaceSelectionPress({
const handlePressIn = useCallback(
(event: GestureResponderEvent) => {
const modifiers = readPressModifiers(event);
if (modifiers.shift || modifiers.mod) {
const isSelectionMode = useSidebarSelectionStore.getState().active;
const entersSelection = !isSelectionMode && modifiers.shift && !modifiers.mod;
if (entersSelection || (isSelectionMode && (modifiers.shift || modifiers.mod))) {
// Keep the browser from extending a text selection or starting a drag on modifier clicks.
event.preventDefault?.();
return;
}
if (!useSidebarSelectionStore.getState().active) {
if (!isSelectionMode) {
onPressIn?.(event);
}
},
@@ -1548,64 +1548,6 @@ describe("DaemonConfigStore reload", () => {
});
});
describe("plugin entries edited in config.json while the daemon runs", () => {
const other = { source: "directory", path: "/other", enabled: true } as const;
const local = { source: "directory", path: "/local", enabled: true } as const;
function disableOther(store: DaemonConfigStore) {
return store.patch((current) => ({
plugins: { ...current.plugins, other: { ...current.plugins.other!, enabled: false } },
}));
}
function removeOther(store: DaemonConfigStore) {
return store.patch((current) => {
const { other: _removed, ...rest } = current.plugins;
return { plugins: rest };
});
}
test("keeps a hand-added entry on disk when another plugin changes", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other, local } });
await disableOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({
other: { ...other, enabled: false },
local,
});
expect(store.get().plugins).toEqual({ other: { ...other, enabled: false } });
});
test("does not write back an entry removed by hand when another plugin changes", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other, local } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other } });
await disableOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({
other: { ...other, enabled: false },
});
});
test("removing a plugin deletes only that entry from disk", async () => {
const { paseoHome, store, persisted } = createReloadableStore({
initialPersisted: { version: 1, plugins: { other } },
});
writeConfig(paseoHome, { ...persisted, plugins: { other, local } });
await removeOther(store);
expect(loadPersistedConfig(paseoHome).plugins).toEqual({ local });
expect(store.get().plugins).toEqual({});
});
});
test("serializes overlapping patches before committing their combined state", async () => {
const { paseoHome, store } = createReloadableStore();
const first = store.patch({ appendSystemPrompt: "first" });
@@ -1012,7 +1012,6 @@ export class DaemonConfigStore {
patch,
removeProviders,
persistRelayEnabled: this.relayEnabledMutable,
pluginsBeforePatch: this.current.plugins ?? {},
});
const nextPersisted = merge(persisted);
const knownNext = merge(this.lastKnownPersisted);
@@ -1026,9 +1025,8 @@ function mergeMutablePatchIntoPersistedConfig(params: {
patch: Omit<SupportedMutableConfigPatch, "removeProviders">;
removeProviders: readonly string[];
persistRelayEnabled: boolean;
pluginsBeforePatch: PluginSources;
}): PersistedConfig {
const { persisted, patch, removeProviders, persistRelayEnabled, pluginsBeforePatch } = params;
const { persisted, patch, removeProviders, persistRelayEnabled } = params;
const daemon = mergeMutableDaemonPatch(persisted.daemon, patch, persistRelayEnabled);
const agents = mergeMutableAgentPatch(persisted.agents, patch, removeProviders);
const withSpeech = patch.features
@@ -1037,40 +1035,12 @@ function mergeMutablePatchIntoPersistedConfig(params: {
return {
...withSpeech,
...(patch.pluginsEnabled !== undefined ? { pluginsEnabled: patch.pluginsEnabled } : {}),
...(patch.plugins !== undefined
? {
plugins: applyChangedPluginEntries({
persisted: persisted.plugins,
before: pluginsBeforePatch,
after: patch.plugins,
}),
}
: {}),
...(patch.plugins !== undefined ? { plugins: patch.plugins } : {}),
...(daemon ? { daemon } : { daemon: undefined }),
...(agents ? { agents } : { agents: undefined }),
} as PersistedConfig;
}
type PluginSources = NonNullable<MutableDaemonConfig["plugins"]>;
// The daemon never reloads plugin entries from config.json, so its copy can be stale. Writing only
// the entries this patch changed keeps entries other writers put on disk until the next restart.
function applyChangedPluginEntries(params: {
persisted: PersistedConfig["plugins"];
before: PluginSources;
after: PluginSources;
}): PluginSources {
const { persisted, before, after } = params;
const next: PluginSources = { ...persisted };
for (const [pluginId, source] of Object.entries(after)) {
if (!isEqualValue(before[pluginId], source)) next[pluginId] = source;
}
for (const pluginId of Object.keys(before)) {
if (!(pluginId in after)) delete next[pluginId];
}
return next;
}
function mergeMutableAgentPatch(
persistedAgents: PersistedConfig["agents"],
patch: Omit<SupportedMutableConfigPatch, "removeProviders">,