import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
  createGoatChainBridge,
  resolveInitialGoatChainThread,
} from "../src/best-agent-native-bridge.ts";
import {
  createCliRuntime,
  hydrateDimSdkProviderSelection,
  readCliPersistedState,
  resolveCliStorageRoot,
  resolveProviderConfigFromDimSdkState,
  writeCliPersistedState,
} from "../src/runtime.ts";
const { nextTick, watch } = await import("vue");
const { createTerminalApp } = await import("@simon_he/vue-tui");
const { createDimSdkRouter, DimSdkShell } = await import("../src/dimsdk/index.ts");

const storageRoots: string[] = [];
const tempDirs: string[] = [];

if (typeof globalThis.requestAnimationFrame !== "function") {
  globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {
    cb(0);
    return 1;
  }) as typeof globalThis.requestAnimationFrame;
}

if (typeof globalThis.cancelAnimationFrame !== "function") {
  globalThis.cancelAnimationFrame = (() => {}) as typeof globalThis.cancelAnimationFrame;
}

afterEach(() => {
  while (storageRoots.length > 0) {
    rmSync(storageRoots.pop() as string, { force: true, recursive: true });
  }

  while (tempDirs.length > 0) {
    rmSync(tempDirs.pop() as string, { force: true, recursive: true });
  }
});

function createNoopToolRunner() {
  return async (call: { id?: string; name?: string }) => ({
    toolCallId: String(call?.id ?? "tool"),
    output: `Tool execution stays inside the best-agent runtime. "${String(call?.name ?? "tool")}" cannot be re-run locally from the TUI shell.`,
    status: "error" as const,
  });
}

function modeIdFromThreadMode(mode: "default" | "plan"): "agent" | "plan" {
  return mode === "plan" ? "plan" : "agent";
}

function cloneJson<T>(value: T): T {
  return JSON.parse(JSON.stringify(value ?? null)) as T;
}

function syncProviderSelection(
  input: Readonly<{
    runtime: Awaited<ReturnType<typeof createCliRuntime>>;
    storageRoot: string;
    store: {
      state: {
        config: { model?: unknown };
        provider: Record<string, unknown>;
      };
    };
  }>,
): void {
  const providerConfig = resolveProviderConfigFromDimSdkState(
    input.store.state,
    input.runtime.getProviderConfig(),
  );
  input.runtime.setProviderConfig(providerConfig);
  const persistedState = readCliPersistedState(input.storageRoot);
  writeCliPersistedState(input.storageRoot, {
    ...persistedState,
    dimsdk: {
      ...persistedState?.dimsdk,
      providerState: cloneJson(input.store.state.provider),
    },
    providerConfig,
  });
}

async function flushApp(
  app: {
    scheduler: { flush: () => void };
  },
  ticks = 3,
): Promise<void> {
  for (let index = 0; index < ticks; index += 1) {
    await nextTick();
  }
  app.scheduler.flush();
}

async function waitFor<T>(
  fn: () => T | null | undefined,
  message: string,
  advance: () => Promise<void> = () => nextTick(),
  tries = 40,
  debug?: () => string,
): Promise<T> {
  for (let index = 0; index < tries; index += 1) {
    const value = fn();
    if (value) {
      return value;
    }
    await advance();
  }
  const detail = debug?.();
  throw new Error(detail ? `${message}\n\n${detail}` : message);
}

function snapshotText(app: { terminal: { snapshot: () => { lines: string[] } } }): string {
  return app.terminal.snapshot().lines.join("\n");
}

function findTextCell(
  app: {
    terminal: { snapshot: () => { lines: string[] } };
  },
  text: string,
): { x: number; y: number } | null {
  const wanted = text.toLowerCase();
  const lines = app.terminal.snapshot().lines;
  for (let y = 0; y < lines.length; y += 1) {
    const x = lines[y]?.toLowerCase().indexOf(wanted) ?? -1;
    if (x >= 0) {
      return { x, y };
    }
  }
  return null;
}

async function clickText(
  app: {
    events: { dispatch: (event: unknown) => boolean | void };
    scheduler: { flush: () => void };
    terminal: { snapshot: () => { lines: string[] } };
  },
  text: string,
): Promise<void> {
  const cell = findTextCell(app, text);
  if (!cell) {
    throw new Error(`Unable to find "${text}" in terminal snapshot:\n${snapshotText(app)}`);
  }
  const eventBase = { cellX: cell.x + 1, cellY: cell.y };
  app.events.dispatch({ type: "pointerdown", button: 0, ...eventBase } as const);
  app.events.dispatch({ type: "pointerup", button: 0, ...eventBase } as const);
  app.events.dispatch({ type: "click", ...eventBase } as const);
  await flushApp(app);
}

function bottomSnapshotText(
  app: {
    terminal: { snapshot: () => { lines: string[] } };
  },
  lineCount = 6,
): string {
  const lines = app.terminal.snapshot().lines;
  return lines.slice(-lineCount).join("\n");
}

async function sleep(ms: number): Promise<void> {
  await new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
}

function keyCodeFor(key: string): string {
  if (key === "/") {
    return "Slash";
  }
  if (key === "@") {
    return "Digit2";
  }
  if (key === " ") {
    return "Space";
  }
  if (key === ".") {
    return "Period";
  }
  if (key === "-") {
    return "Minus";
  }
  if (key.length === 1 && /[a-z]/i.test(key)) {
    return `Key${key.toUpperCase()}`;
  }
  if (key.length === 1 && /\d/.test(key)) {
    return `Digit${key}`;
  }
  return key;
}

async function pressKey(
  app: {
    events: { dispatch: (event: unknown) => boolean | void };
    scheduler: { flush: () => void };
  },
  key: string,
  code = keyCodeFor(key),
  options: Readonly<{
    shiftKey?: boolean;
  }> = {},
): Promise<void> {
  app.events.dispatch({ type: "keydown", key, code, ...options } as const);
  await flushApp(app);
}

async function typeText(
  app: {
    events: { dispatch: (event: unknown) => boolean | void };
    scheduler: { flush: () => void };
  },
  text: string,
): Promise<void> {
  for (const character of text) {
    await pressKey(app, character);
  }
}

function createWorkspace(files: Readonly<Record<string, string>>): string {
  const workspace = mkdtempSync(`${tmpdir()}/best-agent-dimsdk-workspace-`);
  tempDirs.push(workspace);
  for (const [relativePath, content] of Object.entries(files)) {
    writeFileSync(resolve(workspace, relativePath), content, "utf8");
  }
  return workspace;
}

async function mountHome(
  input: Readonly<{
    cwd?: string;
    latest?: boolean;
    persistedState?: Parameters<typeof writeCliPersistedState>[1];
    resumeThreadId?: string;
    storageRoot?: string;
  }> = {},
) {
  const storageRoot = resolveCliStorageRoot({
    cwd: input.cwd,
    storageRoot: input.storageRoot ?? mkdtempSync(`${tmpdir()}/best-agent-dimsdk-home-`),
  });
  storageRoots.push(storageRoot);

  if (input.persistedState) {
    writeCliPersistedState(storageRoot, input.persistedState);
  }

  const persistedState = readCliPersistedState(storageRoot);
  const runtime = await createCliRuntime({
    cwd: input.cwd,
    storageRoot,
  });
  const initialProviderConfig = runtime.getProviderConfig();
  const initialThread =
    input.latest || input.resumeThreadId
      ? await resolveInitialGoatChainThread(runtime, {
          latest: input.latest,
          resumeThreadId: input.resumeThreadId,
        })
      : null;
  const bridge = createGoatChainBridge({ runtime });
  const initialMessages = initialThread ? await bridge.hydrateThread(initialThread.id) : [];
  let stopProviderSync: (() => void) | undefined;
  let storeRef: any;

  const app = createTerminalApp({
    cols: 120,
    rows: 36,
    component: DimSdkShell as never,
    props: {
      agent: bridge.agent,
      context: {
        cwd: initialThread?.cwd ?? input.cwd ?? process.cwd(),
        env: {
          ...process.env,
          DIMCODE_VERSION: process.env.DIMCODE_VERSION ?? "0.0.0",
        },
        system:
          "You are best-agent running inside the DimSdk terminal UI. Keep answers concise, tool-grounded, and focused on the current workspace.",
      },
      onStoreCreated: (store: any) => {
        storeRef = store;
        bridge.attachStore(store);
        if (typeof store.setCwd === "function") {
          store.setCwd(initialThread?.cwd ?? input.cwd ?? process.cwd());
        } else {
          store.state.context = {
            ...store.state.context,
            cwd: initialThread?.cwd ?? input.cwd ?? process.cwd(),
          };
        }
        store.state.messages = initialMessages;
        store.state.sessionId = initialThread?.id ?? "";
        if (initialThread) {
          store.state.sessionMeta = {
            ...store.state.sessionMeta,
            ...cloneJson(
              ((initialThread.metadata as Record<string, unknown> | undefined)?.ui ?? {}) as Record<
                string,
                unknown
              >,
            ),
          };
        }
        store.setMode?.(modeIdFromThreadMode(initialThread?.mode ?? "default"));
        hydrateDimSdkProviderSelection(store.state, {
          persistedProviderState: persistedState?.dimsdk?.providerState,
          providerConfig: initialProviderConfig,
        });
        stopProviderSync?.();
        stopProviderSync = watch(
          () => [store.state.provider, store.state.config.model],
          () => {
            syncProviderSelection({ runtime, storageRoot, store });
          },
          { deep: true },
        );
        syncProviderSelection({ runtime, storageRoot, store });
      },
      toolRunner: createNoopToolRunner(),
      uiForcedSkills: new Set<string>(),
      sessions: bridge.sessions,
    },
    defaultStyle: { bg: "black", fg: "whiteBright" },
  });

  app.app.use(createDimSdkRouter({ initialRoute: "home", mode: "cli" }) as never);
  app.mount();
  await flushApp(app, 4);
  const store = await waitFor(() => storeRef, "DimSdk store was not created.");

  return {
    app,
    runtime,
    store,
    snapshot: () => snapshotText(app),
    dispose() {
      app.dispose();
      stopProviderSync?.();
    },
  };
}

describe("dimsdk home e2e", () => {
  it("starts on the home page and accepts typed input", async () => {
    const mounted = await mountHome();
    try {
      expect(mounted.snapshot()).toContain("Welcome! Quick start:");
      expect(mounted.store.state.sessionId).toBe("");

      await typeText(mounted.app, "hello");

      expect(mounted.snapshot()).toContain("hello");
    } finally {
      mounted.dispose();
    }
  });

  it("shows slash suggestions from the home page input", async () => {
    const mounted = await mountHome();
    try {
      await pressKey(mounted.app, "/");

      const snapshot = mounted.snapshot();
      expect(snapshot).toContain("Connect a provider");
      expect(snapshot).toContain("Select a model");
      expect(snapshot).toContain("List loaded skills");
    } finally {
      mounted.dispose();
    }
  });

  it("opens /sessions with real history records in the list", async () => {
    const workspace = createWorkspace({
      "README.md": "history workspace\n",
    });
    const storageRoot = resolveCliStorageRoot({
      cwd: workspace,
      storageRoot: mkdtempSync(`${tmpdir()}/best-agent-dimsdk-home-sessions-`),
    });
    storageRoots.push(storageRoot);

    const seedRuntime = await createCliRuntime({ cwd: workspace, storageRoot });
    try {
      const { thread: alphaThread } = await seedRuntime.startThread({ title: "Alpha history" });
      await seedRuntime.runTurn({
        prompt: "tool:echo alpha history payload",
        threadId: alphaThread.id,
      });

      const { thread: betaThread } = await seedRuntime.startThread({ title: "Beta history" });
      await seedRuntime.runTurn({
        prompt: "tool:echo beta history payload",
        threadId: betaThread.id,
      });
    } finally {
      await seedRuntime.close();
    }

    const mounted = await mountHome({ cwd: workspace, storageRoot });
    try {
      await typeText(mounted.app, "/ses");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () => {
          const snapshot = mounted.snapshot();
          return snapshot.includes("Sessions (2)") &&
            snapshot.includes("Alpha history") &&
            snapshot.includes("Beta history")
            ? true
            : null;
        },
        "Opening /sessions did not render the seeded history records.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        80,
        () => mounted.snapshot(),
      );

      const snapshot = mounted.snapshot();
      expect(snapshot).toContain("Sessions (2)");
      expect(snapshot).toContain("Alpha history");
      expect(snapshot).toContain("Beta history");
    } finally {
      mounted.dispose();
    }
  });

  it("clears the input after accepting a slash prompt suggestion on the home page", async () => {
    const mounted = await mountHome();
    try {
      await typeText(mounted.app, "/co");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect a provider") && mounted.snapshot().includes("OpenAI")
            ? true
            : null,
        "Accepting /connect from home prompt suggestions did not open the provider picker.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        80,
        () => mounted.snapshot(),
      );

      await waitFor(
        () => (bottomSnapshotText(mounted.app).includes("/co") ? null : true),
        "Accepted home slash prompt suggestion left stale command text in the input.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        80,
        () => bottomSnapshotText(mounted.app),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("cycles between agent and plan mode from the home page input with Tab", async () => {
    const mounted = await mountHome();
    try {
      expect(mounted.store.state.ui.mode).toBe("agent");
      expect(mounted.snapshot()).toContain("AGENT");

      await pressKey(mounted.app, "Tab", "Tab");

      expect(mounted.store.state.ui.mode).toBe("plan");
      expect(mounted.snapshot()).toContain("PLAN");

      await pressKey(mounted.app, "Tab", "Tab");

      expect(mounted.store.state.ui.mode).toBe("agent");
      expect(mounted.snapshot()).toContain("AGENT");
    } finally {
      mounted.dispose();
    }
  });

  it("opens the connect dialog from a committed /connect command on the home page", async () => {
    const mounted = await mountHome();
    try {
      await typeText(mounted.app, "/connect");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect a provider") && mounted.snapshot().includes("OpenAI")
            ? true
            : null,
        "Committed /connect did not open the connect dialog.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("opens the models dialog from a committed /models command on the home page", async () => {
    const mounted = await mountHome({
      persistedState: {
        dimsdk: {
          providerState: {
            activeId: "openai",
            activeModelByProvider: {
              openai: "gpt-5",
            },
            connections: {
              openai: {
                apiKey: "sk-test",
                baseUrl: "https://api.openai.com/v1",
              },
            },
            custom: { models: [] },
            customProviders: [],
          },
        },
        providerConfig: {
          kind: "openai",
          apiKey: "sk-test",
          baseURL: "https://api.openai.com/v1",
          model: "gpt-5",
        },
      },
    });
    try {
      await typeText(mounted.app, "/models");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Select a model") &&
          mounted.snapshot().toLowerCase().includes("gpt")
            ? true
            : null,
        "Committed /models did not open the models dialog.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("filters the connect dialog search and opens Anthropic on the home page", async () => {
    const mounted = await mountHome();
    try {
      await typeText(mounted.app, "/connect");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect a provider") &&
          mounted.snapshot().includes("Anthropic")
            ? true
            : null,
        "Committed /connect did not open the provider picker.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );

      await typeText(mounted.app, "anth");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect Anthropic") &&
          mounted.snapshot().includes("Base URL") &&
          mounted.snapshot().includes("API Key")
            ? true
            : null,
        "Typing inside the connect picker did not select Anthropic.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("uses arrow keys to change the selected provider inside the connect dialog", async () => {
    const mounted = await mountHome();
    try {
      await typeText(mounted.app, "/connect");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect a provider") &&
          mounted.snapshot().includes("OpenRouter")
            ? true
            : null,
        "Committed /connect did not open the provider picker.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );

      await pressKey(mounted.app, "ArrowDown", "ArrowDown");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect OpenRouter") &&
          mounted.snapshot().includes("Base URL") &&
          mounted.snapshot().includes("API Key")
            ? true
            : null,
        "Arrow navigation inside the connect picker did not select OpenRouter.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("opens the custom provider connect dialog after confirming a custom type with Enter", async () => {
    const mounted = await mountHome();
    try {
      await typeText(mounted.app, "/connect");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect a provider") && mounted.snapshot().includes("OpenAI")
            ? true
            : null,
        "Committed /connect did not open the provider picker.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );

      await typeText(mounted.app, "custom");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Add custom provider") &&
          mounted.snapshot().includes("OpenAI Responses")
            ? true
            : null,
        "Selecting Add custom provider did not open the custom type picker.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );

      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect Custom") &&
          mounted.snapshot().includes("Base URL") &&
          mounted.snapshot().includes("API Key")
            ? true
            : null,
        "Pressing Enter on the custom type picker did not open the custom provider connect dialog.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("opens the custom provider connect dialog after clicking a custom type", async () => {
    const mounted = await mountHome();
    try {
      await typeText(mounted.app, "/connect");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect a provider") && mounted.snapshot().includes("OpenAI")
            ? true
            : null,
        "Committed /connect did not open the provider picker.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );

      await typeText(mounted.app, "custom");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Add custom provider") &&
          mounted.snapshot().includes("Gemini")
            ? true
            : null,
        "Selecting Add custom provider did not open the custom type picker.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );

      await clickText(mounted.app, "Gemini");

      await waitFor(
        () =>
          mounted.snapshot().includes("Connect Custom") &&
          mounted.snapshot().includes("Base URL") &&
          mounted.snapshot().includes("API Key")
            ? true
            : null,
        "Clicking a custom type did not open the custom provider connect dialog.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("uses arrow keys inside the models dialog on the home page", async () => {
    const mounted = await mountHome({
      persistedState: {
        dimsdk: {
          providerState: {
            activeId: "openai",
            activeModelByProvider: {
              openai: "gpt-5",
            },
            connections: {
              openai: {
                apiKey: "sk-test",
                baseUrl: "https://api.openai.com/v1",
              },
            },
            custom: { models: [] },
            customProviders: [],
          },
        },
        providerConfig: {
          kind: "openai",
          apiKey: "sk-test",
          baseURL: "https://api.openai.com/v1",
          model: "gpt-5",
        },
      },
    });
    try {
      await typeText(mounted.app, "/models");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () =>
          mounted.snapshot().includes("Select a model") &&
          mounted.snapshot().toLowerCase().includes("gpt")
            ? true
            : null,
        "Committed /models did not open the models picker.",
        () => flushApp(mounted.app),
        40,
        () => mounted.snapshot(),
      );

      await pressKey(mounted.app, "ArrowDown", "ArrowDown");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () => {
          const model = String(mounted.store.state.config.model ?? "").trim();
          return model && model !== "gpt-5" ? true : null;
        },
        "Arrow navigation inside the models picker did not select the next model.",
        async () => {
          await sleep(40);
          await flushApp(mounted.app);
        },
        60,
        () => mounted.snapshot(),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("opens the @ prompt overlay from the home page input", async () => {
    const workspace = createWorkspace({
      "a-note.md": "first\n",
      "z-note.md": "last\n",
    });
    const mounted = await mountHome({ cwd: workspace });
    try {
      await pressKey(mounted.app, "@", "Digit2", { shiftKey: true });
      await typeText(mounted.app, "note");
      await waitFor(
        () =>
          mounted.snapshot().includes("a-note.md") && mounted.snapshot().includes("z-note.md")
            ? true
            : null,
        "Mention prompt overlay did not open.",
        async () => {
          await sleep(120);
          await flushApp(mounted.app);
        },
      );
      expect(mounted.snapshot()).toContain("@note");

      await pressKey(mounted.app, "Escape", "Escape");
      await waitFor(
        () => (!mounted.snapshot().includes("a-note.md") ? true : null),
        "Mention prompt overlay did not close.",
        () => flushApp(mounted.app),
      );
    } finally {
      mounted.dispose();
    }
  });

  it("wraps @ mention selection from the bottom back to the first item on the home page", async () => {
    const workspace = createWorkspace({
      "a-note.md": "first\n",
      "z-note.md": "last\n",
    });
    const mounted = await mountHome({ cwd: workspace });
    try {
      mounted.store.state.userHistory = ["history should not replace mention selection"];

      await pressKey(mounted.app, "@", "Digit2", { shiftKey: true });
      await typeText(mounted.app, "note");
      await waitFor(
        () =>
          mounted.snapshot().includes("a-note.md") && mounted.snapshot().includes("z-note.md")
            ? true
            : null,
        "Mention suggestions did not render.",
        async () => {
          await sleep(120);
          await flushApp(mounted.app);
        },
      );

      await pressKey(mounted.app, "ArrowUp", "ArrowUp");
      await pressKey(mounted.app, "ArrowDown", "ArrowDown");
      await pressKey(mounted.app, "Tab", "Tab");

      await waitFor(
        () =>
          Array.isArray(mounted.store.state.context?.focusFiles) &&
          mounted.store.state.context.focusFiles[0] === resolve(workspace, "a-note.md")
            ? true
            : null,
        "Wrapped mention selection did not insert the first item.",
        () => flushApp(mounted.app),
        40,
        () =>
          `${mounted.snapshot()}\n\nfocusFiles=${JSON.stringify(mounted.store.state.context?.focusFiles ?? null)}`,
      );
      expect(mounted.snapshot()).not.toContain("history should not replace mention selection");
      expect(mounted.snapshot()).not.toContain("z-note.md");
    } finally {
      mounted.dispose();
    }
  });

  it("creates a real thread on the first send from the home page", async () => {
    const previousDimcodeTest = process.env.DIMCODE_TEST;
    process.env.DIMCODE_TEST = "1";
    const mounted = await mountHome();
    try {
      expect(mounted.store.state.sessionId).toBe("");

      await typeText(mounted.app, "tool:echo hello from lazy home");
      await pressKey(mounted.app, "Enter", "Enter");

      await waitFor(
        () => (String(mounted.store.state.sessionId ?? "").startsWith("thread_") ? true : null),
        "Home page send did not create a real runtime thread.",
        () => flushApp(mounted.app),
        80,
        () => `${mounted.snapshot()}\n\nsessionId=${String(mounted.store.state.sessionId ?? "")}`,
      );
      await waitFor(
        () =>
          JSON.stringify(mounted.store.state.messages).includes("hello from lazy home")
            ? true
            : null,
        "Home page send did not render the assistant response.",
        async () => {
          await sleep(50);
          await flushApp(mounted.app);
        },
        120,
        () =>
          `${mounted.snapshot()}\n\nmessages=${JSON.stringify(mounted.store.state.messages, null, 2)}`,
      );

      expect(mounted.snapshot()).toContain("hello from lazy home");
      expect((await mounted.runtime.listThreads({})).threads).toHaveLength(1);
      expect(bottomSnapshotText(mounted.app)).not.toContain("tool:echo hello from lazy home");
    } finally {
      mounted.dispose();
      if (previousDimcodeTest == null) {
        delete process.env.DIMCODE_TEST;
      } else {
        process.env.DIMCODE_TEST = previousDimcodeTest;
      }
    }
  });
});
