test(ai): wait composer compact state by event loop turns

This commit is contained in:
zipg authored and GitHub committed 2026-09-29 16:09:16 +08:00
1 parent ff58532dce
commit e3233aacfc
2 files changed
+109 -52

No files matched your search

@@ -5033,6 +5033,16 @@ function dismissAwayUpdates() {
onMounted(async () => { onMounted(async () => {
assistantViewMounted = true; assistantViewMounted = true;
// Size handling has to be live before the first `await`: the bootstrap below
// can take several frames (persisted runs plus the dynamic import of the code
// highlighter), and a panel drag or window resize during that window would
// otherwise be dropped, leaving the composer on a stale compact/expanded state.
window.addEventListener("resize", handleWindowResize);
if (typeof ResizeObserver !== "undefined" && assistantRootRef.value) {
promptPanelResizeObserver = new ResizeObserver(handleObservedPanelResize);
promptPanelResizeObserver.observe(assistantRootRef.value);
if (promptPanelRef.value) promptPanelResizeObserver.observe(promptPanelRef.value);
}
const savedHeight = localStorage.getItem(AI_TEXTAREA_HEIGHT_STORAGE_KEY); const savedHeight = localStorage.getItem(AI_TEXTAREA_HEIGHT_STORAGE_KEY);
if (savedHeight) { if (savedHeight) {
const height = parseInt(savedHeight, 10); const height = parseInt(savedHeight, 10);
@@ -5138,14 +5148,8 @@ onMounted(async () => {
appearance: () => aiCodeAppearance.value, appearance: () => aiCodeAppearance.value,
}).catch(() => undefined); }).catch(() => undefined);
window.addEventListener("resize", handleWindowResize);
document.addEventListener("dbx:tauri-file-drop", onTauriFileDrop as EventListener); document.addEventListener("dbx:tauri-file-drop", onTauriFileDrop as EventListener);
window.addEventListener(DBX_TABLE_REFERENCE_DROP_EVENT, onTableReferenceDropEvent); window.addEventListener(DBX_TABLE_REFERENCE_DROP_EVENT, onTableReferenceDropEvent);
if (typeof ResizeObserver !== "undefined" && assistantRootRef.value) {
promptPanelResizeObserver = new ResizeObserver(handleObservedPanelResize);
promptPanelResizeObserver.observe(assistantRootRef.value);
if (promptPanelRef.value) promptPanelResizeObserver.observe(promptPanelRef.value);
}
scheduleResponsiveControlMeasurement(true); scheduleResponsiveControlMeasurement(true);
}); });
@@ -20,8 +20,23 @@ import type { PluginAiRecommendationHostUpdate } from "@/lib/plugins/pluginHostB
const aiAssistantMountApi = vi.hoisted(() => ({ const aiAssistantMountApi = vi.hoisted(() => ({
conversations: [] as Array<Record<string, unknown>>, conversations: [] as Array<Record<string, unknown>>,
runAgentStream: undefined as undefined | ((onEvent: (event: { type: string; delta?: string }) => void) => Promise<string>), runAgentStream: undefined as undefined | ((onEvent: (event: { type: string; delta?: string }) => void) => Promise<string>),
codeHighlighterDelayMs: 0,
})); }));
// `onMounted` imports the syntax highlighter lazily; this module-level delay stands in for the
// loaded CI runner where that import resolves well after the DOM is ready.
vi.mock("@/lib/ai/aiCodeHighlighter", async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return {
...actual,
createAiShikiCodeHighlighter: async (...args: unknown[]) => {
const delay = aiAssistantMountApi.codeHighlighterDelayMs;
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
return (actual.createAiShikiCodeHighlighter as (...innerArgs: unknown[]) => Promise<unknown>)(...args);
},
};
});
vi.mock("@/lib/ai/ai", async (importOriginal) => { vi.mock("@/lib/ai/ai", async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>(); const actual = await importOriginal<Record<string, unknown>>();
return { return {
@@ -58,9 +73,34 @@ afterEach(() => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
aiAssistantMountApi.conversations = []; aiAssistantMountApi.conversations = [];
aiAssistantMountApi.runAgentStream = undefined; aiAssistantMountApi.runAgentStream = undefined;
aiAssistantMountApi.codeHighlighterDelayMs = 0;
while (cleanups.length) cleanups.pop()?.(); while (cleanups.length) cleanups.pop()?.();
}); });
function stubResizeObserver(): Array<{ callback: ResizeObserverCallback; targets: Element[] }> {
const observers: Array<{ callback: ResizeObserverCallback; targets: Element[] }> = [];
vi.stubGlobal(
"ResizeObserver",
class {
callback: ResizeObserverCallback;
targets: Element[] = [];
constructor(callback: ResizeObserverCallback) {
this.callback = callback;
observers.push(this as unknown as { callback: ResizeObserverCallback; targets: Element[] });
}
observe(target: Element) {
this.targets.push(target);
}
unobserve() {}
disconnect() {}
},
);
return observers;
}
async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig, configureSettings?: (settings: ReturnType<typeof useSettingsStore>) => void, pluginRecommendations?: PluginAiRecommendationHostUpdate) { async function mountPanel(aiConfigLoaded: boolean, connection?: ConnectionConfig, configureSettings?: (settings: ReturnType<typeof useSettingsStore>) => void, pluginRecommendations?: PluginAiRecommendationHostUpdate) {
const pinia = createPinia(); const pinia = createPinia();
const errors: unknown[] = []; const errors: unknown[] = [];
@@ -259,53 +299,64 @@ describe("AiAssistant mount", () => {
expect(modelTrigger?.getAttribute("title")).toBe("deepseek-chat"); expect(modelTrigger?.getAttribute("title")).toBe("deepseek-chat");
}); });
// The compact classes settle through requestAnimationFrame plus async measurement, // These states settle through requestAnimationFrame plus async measurement, and the component
// so a fixed sleep races on loaded CI runners; poll until the state holds. // measures asynchronously, so they can lag the DOM. Budget by event-loop turns rather than
async function waitForCompactState(settled: () => boolean, timeoutMs = 2000): Promise<void> { // wall-clock: a CI worker's event loop can stall for seconds behind another worker's module
const deadline = Date.now() + timeoutMs; // transforms (see `vitest.config.ts`), and a time-based budget trips in that window even though
while (!settled()) { // the component is still progressing.
if (Date.now() > deadline) throw new Error("composer compact state did not settle in time"); async function waitForSettled(what: string, settled: () => boolean, diagnose: () => string): Promise<void> {
for (let turn = 0; turn < 500; turn += 1) {
if (settled()) return;
await new Promise((resolve) => setTimeout(resolve, 10)); await new Promise((resolve) => setTimeout(resolve, 10));
} }
if (settled()) return;
throw new Error(`${what} did not settle in time: ${diagnose()}`);
} }
it("progressively compacts and expands composer controls while the AI panel is dragged", async () => { function configureDeepseekModel(settings: ReturnType<typeof useSettingsStore>): void {
let resizeObserverCallback: ResizeObserverCallback | undefined; settings.aiConfigs = [
let resizeObserver: ResizeObserver | undefined; {
vi.stubGlobal( id: "deepseek-default",
"ResizeObserver", name: "DeepSeek",
class { provider: "deepseek",
constructor(callback: ResizeObserverCallback) { apiKey: "test-key",
resizeObserverCallback = callback; authMethod: "api-key",
resizeObserver = this as unknown as ResizeObserver; endpoint: "https://api.deepseek.com",
} model: "deepseek-chat",
apiStyle: "completions",
observe() {} isDefault: true,
unobserve() {}
disconnect() {}
}, },
); ];
settings.activeModel = { configId: "deepseek-default", modelId: "deepseek-chat" };
}
const { errors, container } = await mountPanel(true, undefined, (settings) => { it("wires panel size handling before the async mount bootstrap resolves", async () => {
settings.aiConfigs = [ const resizeObservers = stubResizeObserver();
{ aiAssistantMountApi.codeHighlighterDelayMs = 1000;
id: "deepseek-default",
name: "DeepSeek", const { errors, container } = await mountPanel(true, undefined, configureDeepseekModel);
provider: "deepseek",
apiKey: "test-key", const panel = container.querySelector<HTMLElement>(".ai-prompt-context-container");
authMethod: "api-key", expect(panel).not.toBeNull();
endpoint: "https://api.deepseek.com", // The bootstrap is still pending here, so the panel can only be observed if the wiring runs
model: "deepseek-chat", // synchronously: a drag or window resize during the bootstrap must not be dropped.
apiStyle: "completions", expect(resizeObservers.some((observer) => observer.targets.includes(panel!))).toBe(true);
isDefault: true, expect(errors.map(String)).toEqual([]);
}, });
];
settings.activeModel = { configId: "deepseek-default", modelId: "deepseek-chat" }; it("progressively compacts and expands composer controls while the AI panel is dragged", async () => {
}); const resizeObservers = stubResizeObserver();
const { errors, container } = await mountPanel(true, undefined, configureDeepseekModel);
const panel = container.querySelector<HTMLElement>(".ai-prompt-context-container")!; const panel = container.querySelector<HTMLElement>(".ai-prompt-context-container")!;
const contextRow = container.querySelector<HTMLElement>("[data-ai-composer-context-row]")!; const contextRow = container.querySelector<HTMLElement>("[data-ai-composer-context-row]")!;
const actionRow = container.querySelector<HTMLElement>("[data-ai-composer-actions]")!; const actionRow = container.querySelector<HTMLElement>("[data-ai-composer-actions]")!;
// Size handling is wired synchronously, so the panel is already observed here; driving a
// resize must never be a no-op that leaves the compact classes unset.
expect(resizeObservers.some((observer) => observer.targets.includes(panel))).toBe(true);
// Other subtrees also build ResizeObservers; drive the one that watches this panel.
const panelObserver = resizeObservers.find((observer) => observer.targets.includes(panel))!;
const compactState = () => `context="${contextRow.className}" actions="${actionRow.className}"`;
let panelWidth = 300; let panelWidth = 300;
let contextClientWidth = 280; let contextClientWidth = 280;
let contextScrollWidth = 320; let contextScrollWidth = 320;
@@ -322,8 +373,8 @@ describe("AiAssistant mount", () => {
}); });
beginPanelResize(); beginPanelResize();
resizeObserverCallback?.([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], resizeObserver!); panelObserver.callback([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], panelObserver as unknown as ResizeObserver);
await waitForCompactState(() => contextRow.classList.contains("ai-prompt-context-row--compact") && actionRow.classList.contains("ai-prompt-action-row--model-compact") && !actionRow.classList.contains("ai-prompt-action-row--mode-compact")); await waitForSettled("composer compact state", () => contextRow.classList.contains("ai-prompt-context-row--compact") && actionRow.classList.contains("ai-prompt-action-row--model-compact") && !actionRow.classList.contains("ai-prompt-action-row--mode-compact"), compactState);
expect(contextRow.classList.contains("ai-prompt-context-row--compact")).toBe(true); expect(contextRow.classList.contains("ai-prompt-context-row--compact")).toBe(true);
expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(true); expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(true);
@@ -332,16 +383,16 @@ describe("AiAssistant mount", () => {
panelWidth = 240; panelWidth = 240;
actionClientWidth = 220; actionClientWidth = 220;
actionModelCompactScrollWidth = 250; actionModelCompactScrollWidth = 250;
resizeObserverCallback?.([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], resizeObserver!); panelObserver.callback([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], panelObserver as unknown as ResizeObserver);
await waitForCompactState(() => actionRow.classList.contains("ai-prompt-action-row--model-compact") && actionRow.classList.contains("ai-prompt-action-row--mode-compact")); await waitForSettled("composer compact state", () => actionRow.classList.contains("ai-prompt-action-row--model-compact") && actionRow.classList.contains("ai-prompt-action-row--mode-compact"), compactState);
expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(true); expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(true);
expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(true); expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(true);
panelWidth = 300; panelWidth = 300;
actionClientWidth = 280; actionClientWidth = 280;
actionModelCompactScrollWidth = 280; actionModelCompactScrollWidth = 280;
resizeObserverCallback?.([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], resizeObserver!); panelObserver.callback([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], panelObserver as unknown as ResizeObserver);
await waitForCompactState(() => actionRow.classList.contains("ai-prompt-action-row--model-compact") && !actionRow.classList.contains("ai-prompt-action-row--mode-compact")); await waitForSettled("composer compact state", () => actionRow.classList.contains("ai-prompt-action-row--model-compact") && !actionRow.classList.contains("ai-prompt-action-row--mode-compact"), compactState);
expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(true); expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(true);
expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(false); expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(false);
@@ -351,8 +402,8 @@ describe("AiAssistant mount", () => {
actionClientWidth = 400; actionClientWidth = 400;
actionFullScrollWidth = 400; actionFullScrollWidth = 400;
actionModelCompactScrollWidth = 400; actionModelCompactScrollWidth = 400;
resizeObserverCallback?.([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], resizeObserver!); panelObserver.callback([{ target: panel, contentRect: { width: panelWidth } } as ResizeObserverEntry], panelObserver as unknown as ResizeObserver);
await waitForCompactState(() => !contextRow.classList.contains("ai-prompt-context-row--compact") && !actionRow.classList.contains("ai-prompt-action-row--model-compact") && !actionRow.classList.contains("ai-prompt-action-row--mode-compact")); await waitForSettled("composer compact state", () => !contextRow.classList.contains("ai-prompt-context-row--compact") && !actionRow.classList.contains("ai-prompt-action-row--model-compact") && !actionRow.classList.contains("ai-prompt-action-row--mode-compact"), compactState);
expect(contextRow.classList.contains("ai-prompt-context-row--compact")).toBe(false); expect(contextRow.classList.contains("ai-prompt-context-row--compact")).toBe(false);
expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(false); expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(false);
expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(false); expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(false);
@@ -363,7 +414,9 @@ describe("AiAssistant mount", () => {
expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(false); expect(actionRow.classList.contains("ai-prompt-action-row--model-compact")).toBe(false);
expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(false); expect(actionRow.classList.contains("ai-prompt-action-row--mode-compact")).toBe(false);
expect(errors.map(String)).toEqual([]); expect(errors.map(String)).toEqual([]);
}); // The turn budget above can take a while on a contended CI worker; keep the diagnostic
// error reachable instead of tripping the default 10s test timeout first.
}, 30_000);
it.each(["plugin", "etcd"] as const)("hides database and schema selectors for %s connections", async (dbType) => { it.each(["plugin", "etcd"] as const)("hides database and schema selectors for %s connections", async (dbType) => {
const { errors, container } = await mountPanel(true, { id: "connection", name: "Connection", db_type: dbType, plugin_id: dbType === "plugin" ? "sample.plugin" : undefined, host: "localhost", port: 22, username: "", password: "" }); const { errors, container } = await mountPanel(true, { id: "connection", name: "Connection", db_type: dbType, plugin_id: dbType === "plugin" ? "sample.plugin" : undefined, host: "localhost", port: 22, username: "", password: "" });