Official

tabs

The tabbed detail pane beside the chat: files to edit and diffs (JavaScript UI plugin).

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/tabs@0.2.6

Permissions in 0.2.6

  • Read files fs.readMediumReads files in the listed places.Open workspace files in tabsPlaces: the open workspace
  • Write files fs.writeMediumCreates, changes and deletes files in the listed places.Save the files edited in tabsPlaces: the open workspace
  • Read chats chats.readMediumReads your transcripts and chat lists.Reload the open files when an agent finishes a turn, and find the folders of the workspaces whose files the tabs follow
  • Read git status and diffs git.readLowReads git status and diffs.Read a file's changes for a diff tab dragged from Source Control or brought back after a restart

Files

service.test.ts33.5 KB
// The divergence/tabs service methods and the legacy shared requests.
// Real activation against a fake service bus: calls go through the provided
// implementation, events through its handle, legacy requests through app state.
import { fakeHostTabs } from "../sdk/ui-testing.ts";
import assert from "node:assert/strict";
import { test } from "node:test";
import type {
  Api,
  AppState,
  AppStatePatch,
  HostEvent,
  RenderResult,
  SlotOptions,
  ViewContext,
} from "divergence";
import { testLayer } from "divergence/effect/testing";
import activate from "./main.ts";

const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
const stable = (value: unknown) =>
  JSON.stringify(value, (_key, item: unknown) => (typeof item === "function" ? "@handler" : item));

type ServiceImpl = Record<string, (params: never, ctx: unknown) => Promise<unknown>>;
type Emitted = { event: string; payload: unknown };

// `clients` are the services of other plugins, by name, as their clients.
// `stored` is the plugin's storage, which outlives the plugin like the host's.
function fakeApi(clients: Record<string, unknown> = {}, stored = new Map<string, unknown>(), nativeFiles = false) {
  let state: AppState = {};
  const appListeners = new Set<(state: AppState) => void>();
  const views: { render: (ctx: ViewContext<object>) => RenderResult; active: boolean; state: object }[] = [];
  // The host's part for this plugin's tab kinds.
  const host = fakeHostTabs(() => {
    dirty = true;
  });
  let beforeClose: ((ctx: { key: string }) => string | null) | undefined;
  let kindDefs: Record<string, { render: (ctx: Record<string, unknown>) => unknown }> = {};
  const layoutListeners = new Set<() => void>();
  const watchers: ((paths: readonly string[]) => unknown)[] = [];
  // What git answers for a diff, by path.
  const diffs = new Map<string, string>();
  // A view's `ctx.state` outlives its renders and, as in the runtime, a
  // reload: the view registered again in the same slot takes it back.
  const kept = new Map<string, object>();
  const listeners = new Map<string, Set<(event: HostEvent) => unknown>>();
  const calls: { method: string; params: unknown }[] = [];
  const notices: string[] = [];
  const focused: string[] = [];
  let dirty = true;
  const provided = new Map<string, ServiceImpl>();
  const emitted: Emitted[] = [];
  const update = (patch: AppStatePatch) => {
    state = {
      ...state,
      ...patch,
      workspaceId: patch.workspaceId === null ? undefined : (patch.workspaceId ?? state.workspaceId),
      chatId: patch.chatId === null ? undefined : (patch.chatId ?? state.chatId),
      route: patch.route ?? state.route,
      shared: { ...state.shared, ...patch.shared },
    };
    dirty = true;
    for (const listener of appListeners) listener(state);
  };
  const disk = new Map<string, string>();
  // Reads of a gated path wait until the test lets them go.
  const gates = new Map<string, ReturnType<typeof Promise.withResolvers<void>>>();
  const call = async (method: string, params: unknown) => {
    calls.push({ method, params });
    const { path, text } = params as { path: string; text?: string };
    if (method === "host/fs.read") {
      await gates.get(path)?.promise;
      return { text: disk.get(path) ?? `# ${path}\nbody` };
    }
    if (method === "host/fs.write" && text !== undefined) {
      disk.set(path, text);
      return {};
    }
    if (method === "host/workspaces.list") return { workspaces: [{ id: "w1", name: "w1", path: "/ws" }] };
    if (method === "host/git.diff") {
      // A gate on `diff:<path>` holds only the next read of that path's diff.
      const diff = diffs.get(path) ?? "";
      const gate = gates.get(`diff:${path}`);
      gates.delete(`diff:${path}`);
      await gate?.promise;
      return { diff };
    }
    if (method === "host/layouts.mine") return { items: host.items.map((item) => ({ id: `${item.kind}:${item.key}`, key: item.key })), shown: [] };
    throw new Error(`Unexpected host method ${method}`);
  };
  const kernel = async (method: string, params: unknown) => {
    calls.push({ method, params });
    if (method === "editor.file" && nativeFiles) return { version: 1 };
    throw new Error(`unknown kernel method ${method}`);
  };
  const broker = testLayer({
    fs: {
      watch: async (_path: string, fn: (paths: readonly string[]) => unknown) => {
        watchers.push(fn);
        return { watchId: "w", close: async () => ({}) };
      },
    },
  });
  // This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
  const api = new Proxy(
    {
      ...broker.api,
      plugin: "tabs",
      id: "divergence/tabs",
      services: {
        provide: async (def: { name: string }, impl: ServiceImpl) => {
          provided.set(def.name, impl);
          return {
            emit: (event: string, payload: unknown) => {
              emitted.push({ event, payload });
            },
            remove: () => {
              provided.delete(def.name);
            },
          };
        },
        get: (name: string) => {
          throw new Error(`no provider for ${name}`);
        },
        available: () => false,
        when: (name: string, fn: (client: unknown) => void) => {
          if (clients[name]) fn(clients[name]);
          return () => {};
        },
      },
      host: {
        ...broker.api.host,
        call,
        kernel,
        storage: {
          get: async ({ key }: { key: string }) => ({ value: stored.get(key) ?? null }),
          set: async ({ key, value }: { key: string; value: unknown }) => {
            stored.set(key, value);
            return {};
          },
        },
      },
      app: {
        state: () => state,
        update,
        share: (key: string, value: unknown) => update({ shared: { [key]: value } }),
        onChange: (fn: (state: AppState) => void) => {
          appListeners.add(fn);
          return () => {
            appListeners.delete(fn);
          };
        },
      },
      layouts: {
        ...host.layouts,
        kinds: (kinds: Parameters<typeof host.layouts.kinds>[0]) => {
          beforeClose = (kinds.file as { beforeClose?: (ctx: { key: string }) => string | null })?.beforeClose;
          kindDefs = kinds as typeof kindDefs;
          host.layouts.kinds(kinds);
        },
        // A kind that asks before closing keeps its tab, as the host does.
        close: async (itemId: string) => {
          const key = itemId.slice(itemId.indexOf(":") + 1);
          if (itemId.startsWith("file:") && beforeClose?.({ key })) return false;
          return host.layouts.close(itemId);
        },
        onChange: (fn: () => void) => {
          layoutListeners.add(fn);
          return () => layoutListeners.delete(fn);
        },
      },
      views: { add: (key: string, definition: any) => {
        const { slot: slot, render: render } = definition;
        const options = { ...definition, key };
        const _options = options;
        void slot; void _options; void options;
        const view = { render, active: true, state: kept.get(slot) ?? {} };
        kept.set(slot, view.state);
        views.push(view);
        dirty = true;
        return {
          id: views.length,
          update: () => {
            dirty = true;
          },
          remove: () => {
            view.active = false;
          },
        };
      } },
      on: (name: string, fn: (event: HostEvent) => unknown) => {
        const subscribers = listeners.get(name) ?? new Set();
        listeners.set(name, subscribers);
        subscribers.add(fn);
        return () => {
          subscribers.delete(fn);
        };
      },
      command: () => ({ remove() {} }),
      notify: (message: string) => {
        notices.push(message);
      },
      focus: (id: string) => {
        focused.push(id);
      },
    },
    {
      get(target, key, receiver) {
        if (Reflect.has(target, key)) return Reflect.get(target, key, receiver);
        throw new Error(`Unexpected API ${String(key)}`);
      },
    },
  ) as unknown as Api;
  const render = () => [
    ...views
      .filter((view) => view.active)
      .map((view) =>
        view.render({
          state: view.state,
          set: () => {},
          app: state,
          plugin: "tabs",
          update: () => {
            dirty = true;
          },
        }),
      ),
    host.render({
      set: () => {},
      app: state,
      plugin: "tabs",
      update: () => {
        dirty = true;
      },
    }) as RenderResult,
  ];
  let trees: RenderResult[] = [];
  const settle = async () => {
    for (let round = 0; round < 50; round++) {
      await tick();
      if (!dirty) {
        await tick();
        if (!dirty) return;
      }
      dirty = false;
      trees = render();
    }
    throw new Error("tabs did not settle");
  };
  const ctx = { caller: { plugin: "test/client", id: "test/client" }, signal: AbortSignal.timeout(5000) };
  return {
    api,
    calls,
    notices,
    focused,
    opened: host.opened,
    items: host.items,
    kindTitle: host.kindTitle,
    beforeClose: (key: string) => beforeClose?.({ key }) ?? null,
    callsReset: () => {
      calls.length = 0;
    },
    emitted,
    provided,
    update,
    settle,
    trees: () => stable(trees),
    disk,
    gate: (path: string) => {
      const gate = Promise.withResolvers<void>();
      gates.set(path, gate);
      return () => gate.resolve();
    },
    // A node of the drawn trees by id, to call its handlers.
    node: (id: string) => {
      const find = (node: unknown): Record<string, unknown> | undefined => {
        if (Array.isArray(node)) return node.map(find).find(Boolean);
        if (typeof node !== "object" || node === null) return undefined;
        const record = node as Record<string, unknown>;
        return record["id"] === id ? record : find(record["children"]);
      };
      return find(trees);
    },
    state: () => state,
    callService: (method: string, params: unknown) =>
      provided.get("divergence/tabs")?.[method]?.(params as never, ctx),
    emit: (event: HostEvent) => {
      for (const name of [event.event, "*"]) for (const fn of listeners.get(name) ?? []) fn(event);
    },
    diffs,
    // The workspace's watch reports these absolute paths changed.
    changed: (paths: readonly string[]) => {
      for (const fn of watchers) fn(paths);
    },
    // The host's layouts changed (a tab closed from its strip).
    layoutsChanged: () => {
      for (const fn of layoutListeners) fn();
    },
    // Draws a tab as the runtime does when the host says whether it is on screen.
    drawTab: (kind: string, key: string, visible: boolean) =>
      kindDefs[kind]?.render({ key, chatId: null, visible, state: {}, app: state, plugin: "tabs", set: () => {}, update: () => {} }),
  };
}

test("the tabs service opens, reports and closes tabs without shared writes", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.ok(fake.provided.has("divergence/tabs"));
    assert.deepEqual(await fake.callService("active", {}), null);
    assert.deepEqual(await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" }), {
      id: "file:w1:a.ts",
    });
    await fake.settle();
    assert.deepEqual(fake.emitted, [{ event: "activeChanged", payload: { kind: "file", path: "a.ts", workspaceId: "w1" } }]);
    // The visible tab left the shared keys behind: nothing announces through them.
    assert.equal(fake.state().shared?.activeTab, undefined);
    assert.equal(fake.state().shared?.activeTabPath, undefined);
    assert.deepEqual(await fake.callService("active", {}), { kind: "file", path: "a.ts", workspaceId: "w1" });
    assert.ok(fake.trees().includes("file:w1:a.ts"));
    fake.callsReset();
    assert.deepEqual(await fake.callService("close", { kind: "file", path: "a.ts" }), null);
    await fake.settle();
    assert.deepEqual(fake.emitted.at(-1), { event: "activeChanged", payload: null });
    assert.deepEqual(await fake.callService("active", {}), null);
    assert.ok(!fake.trees().includes("file:w1:a.ts"));
  } finally {
    await dispose();
  }
});

test("a file opened with focus gives its editor the keyboard", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
    await fake.settle();
    // Opening alone (an agent's file, a reload after a turn) leaves the
    // keyboard where it is.
    assert.deepEqual(fake.focused, []);
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "b.ts", focus: true });
    await fake.settle();
    assert.deepEqual(fake.focused, ["file-file:w1:b.ts"]);
    // The id asked for is the editor's, drawn once the text has loaded.
    assert.ok(fake.trees().includes('"id":"file-file:w1:b.ts"'));
  } finally {
    await dispose();
  }
});

test("a file tab opens with its text, and the file opened last is the one shown", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    // The first file's read is slow and comes back after the second file
    // has opened: the second stays in front.
    const letGo = fake.gate("slow.ts");
    const slow = fake.callService("open", { kind: "file", workspaceId: "w1", path: "slow.ts", focus: true });
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "b.ts", focus: true });
    await fake.settle();
    assert.ok(!fake.trees().includes("Loading…"));
    assert.ok(fake.trees().includes('"id":"file-file:w1:b.ts"'));
    letGo();
    await slow;
    await fake.settle();
    assert.deepEqual(await fake.callService("active", {}), { kind: "file", path: "b.ts", workspaceId: "w1" });
    assert.ok(fake.items.some((item) => item.key === "file:w1:slow.ts"), "both files have tabs");
    assert.deepEqual(fake.emitted, [{ event: "activeChanged", payload: { kind: "file", path: "b.ts", workspaceId: "w1" } }]);
    assert.deepEqual(fake.focused, ["file-file:w1:b.ts"]);
  } finally {
    await dispose();
  }
});

test("a native file tab sends only its reference and reload metadata", async () => {
  const fake = fakeApi({}, new Map(), true);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.equal(fake.calls.filter((call) => call.method === "editor.file").length, 1, "the capability is probed once");
    fake.callsReset();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "src/a.ts", focus: true });
    await fake.settle();
    const editor = () => fake.node("file-file:w1:src/a.ts")!;
    assert.deepEqual(editor()["file"], { workspaceId: "w1", path: "src/a.ts" });
    assert.equal(editor()["revision"], 1);
    assert.equal(editor()["presentation"], "editor");
    assert.equal(editor()["readOnly"], false, "the generic editor's read-only default must not make file tabs read-only");
    for (const field of ["text", "onChange", "onSave"]) assert.ok(!(field in editor()), `${field} stays out of the native node`);
    assert.ok(!fake.calls.some((call) => call.method === "host/fs.read"), "the plugin does not read the native buffer");

    assert.equal(fake.beforeClose("file:w1:src/a.ts"), null);
    (editor()["onFileState"] as (state: { state: "ready"; dirty: boolean }) => void)({ state: "ready", dirty: true });
    await fake.settle();
    assert.equal(fake.beforeClose("file:w1:src/a.ts"), "Discard the unsaved changes to a.ts?");
    fake.emit({ event: "agent", chatId: "c1", kind: { event: "run_finished", outcome: { status: "completed" } } });
    await fake.settle();
    assert.equal(editor()["revision"], 2, "a finished run asks the same native buffer to reload");
    assert.ok(!fake.calls.some((call) => call.method === "host/fs.read"), "a reload still sends no file text through the plugin");
  } finally {
    await dispose();
  }
});

test("a native HTML preview reloads the saved page without replacing its dirty editor", async () => {
  const fake = fakeApi({}, new Map(), true);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "site/index.html" });
    await fake.settle();
    const id = "file:w1:site/index.html";
    const editor = () => fake.node(`file-${id}`)!;
    assert.equal(editor()["presentation"], "html");
    (fake.node(`editor-${id}`)!["onClick"] as () => void)();
    await fake.settle();
    assert.equal(editor()["presentation"], "editor");
    (editor()["onFileState"] as (state: { state: "ready"; dirty: boolean }) => void)({ state: "ready", dirty: true });
    (fake.node(`preview-${id}`)!["onClick"] as () => void)();
    await fake.settle();
    fake.emit({ event: "agent", chatId: "c1", kind: { event: "run_finished", outcome: { status: "completed" } } });
    await fake.settle();
    assert.equal(editor()["presentation"], "html");
    assert.equal(editor()["revision"], 2);
    assert.equal(fake.beforeClose(id), "Discard the unsaved changes to index.html?");
    assert.ok(!fake.calls.some((call) => call.method === "host/fs.read"));
  } finally {
    await dispose();
  }
});

test("native Markdown preview keeps the same file-backed editor buffer", async () => {
  const fake = fakeApi({}, new Map(), true);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "README.md" });
    await fake.settle();
    const id = "file:w1:README.md";
    const editor = () => fake.node(`file-${id}`)!;
    assert.equal(editor()["presentation"], "markdown");
    assert.equal(fake.node(`file-content-${id}`)?.["overflowY"], "scroll");
    assert.deepEqual(editor()["file"], { workspaceId: "w1", path: "README.md" });
    assert.ok(!fake.node(`md-${id}`), "the native preview does not create a second text owner");
    (fake.node(`editor-${id}`)!["onClick"] as () => void)();
    await fake.settle();
    assert.equal(editor()["presentation"], "editor");
    assert.equal(fake.node(`file-content-${id}`)?.["overflowY"], undefined);
    assert.deepEqual(editor()["file"], { workspaceId: "w1", path: "README.md" });
  } finally {
    await dispose();
  }
});

test("closing a tab that is not open changes nothing", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
    await fake.settle();
    const seen = fake.emitted.length;
    assert.deepEqual(await fake.callService("close", { kind: "diff", path: "missing.ts" }), null);
    assert.equal(fake.emitted.length, seen);
    assert.equal(fake.items.length, 1);
  } finally {
    await dispose();
  }
});

test("legacy shared open and close requests still work", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.update({ shared: { openTab: { kind: "diff", workspaceId: "w1", path: "b.ts", diff: "@@\n", nonce: 1 } } });
    await fake.settle();
    assert.equal(fake.state().shared?.openTab, null);
    assert.deepEqual(fake.emitted, [{ event: "activeChanged", payload: { kind: "diff", path: "b.ts", workspaceId: "w1" } }]);
    assert.ok(fake.trees().includes("diff:w1:b.ts"));
    fake.update({ shared: { closeTab: { kind: "diff", path: "b.ts", nonce: 2 } } });
    await fake.settle();
    assert.equal(fake.state().shared?.closeTab, null);
    assert.deepEqual(fake.emitted.at(-1), { event: "activeChanged", payload: null });
  } finally {
    await dispose();
  }
});

test("a diagram the kernel asks for opens one tab that draws it, named by its title", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    const source = "flowchart LR\n  a --> b";
    const request = { kind: "diagram", workspaceId: "w1", path: "d1", title: "Flow", language: "mermaid", source };
    fake.update({ shared: { openTab: { ...request, nonce: 1 } } });
    await fake.settle();
    assert.equal(fake.state().shared?.openTab, null);
    assert.deepEqual(fake.node("diagram-diagram:w1:d1"), {
      type: "diagram",
      id: "diagram-diagram:w1:d1",
      source,
      language: "mermaid",
    });
    assert.equal(fake.kindTitle("diagram", "diagram:w1:d1"), "Flow", "the tab is named by the diagram's title");
    // The diagram has no file, so the tab has no path line.
    assert.ok(!fake.trees().includes('"text":"d1"'));
    fake.update({ shared: { openTab: { ...request, nonce: 2 } } });
    await fake.settle();
    assert.equal(fake.items.filter((item) => item.key === "diagram:w1:d1").length, 1, "one tab for it");
  } finally {
    await dispose();
  }
});

test("a file is edited in its tab, saved with Cmd+S and kept over a reload until then", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.disk.set("a.ts", "one");
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
    await fake.settle();
    const editor = () => fake.node("file-file:w1:a.ts")!;
    const handler = (name: string) => editor()[name] as (payload: { value: string }) => void;
    assert.equal(editor()["readOnly"], false);

    handler("onChange")({ value: "two" });
    await fake.settle();
    // An agent's turn ends and the tab reloads: what is typed stays.
    fake.disk.set("a.ts", "changed by an agent");
    fake.emit({ event: "agent", chatId: "c1", kind: { event: "run_finished", outcome: { status: "completed" } } });
    await fake.settle();
    assert.equal(editor()["text"], "two");

    handler("onSave")({ value: "two" });
    await fake.settle();
    assert.equal(fake.disk.get("a.ts"), "two");
    assert.equal(editor()["text"], "two");
  } finally {
    await dispose();
  }
});

test("the open tabs and unsaved changes outlive a reload of the plugin", async () => {
  const fake = fakeApi();
  const before = activate(fake.api);
  await fake.settle();
  fake.disk.set("a.ts", "one");
  await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
  await fake.callService("open", { kind: "file", workspaceId: "w1", path: "b.ts" });
  await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
  await fake.settle();
  (fake.node("file-file:w1:a.ts")!["onChange"] as (payload: { value: string }) => void)({ value: "two" });
  await fake.settle();
  // A save of the plugin's files reloads it.
  await before();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    assert.deepEqual(fake.items.map((item) => item.key), ["file:w1:a.ts", "file:w1:b.ts"], "both tabs are still open");
    assert.equal(fake.node("file-file:w1:a.ts")?.["text"], "two", "what was typed stays");
  } finally {
    await dispose();
  }
});

test("a file whose read a reload cut short is read again", async () => {
  const fake = fakeApi();
  const before = activate(fake.api);
  await fake.settle();
  const release = fake.gate("slow.ts");
  await fake.callService("open", { kind: "file", workspaceId: "w1", path: "slow.ts" });
  await fake.settle();
  await before();
  const dispose = activate(fake.api);
  try {
    release();
    await fake.settle();
    assert.equal(fake.node("file-file:w1:slow.ts")?.["text"], "# slow.ts\nbody");
  } finally {
    await dispose();
  }
});

test("an HTML file previews live and loads again after each read and save", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.disk.set("site/index.html", "<h1>one</h1>");
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "site/index.html" });
    await fake.settle();
    const id = "file:w1:site/index.html";
    const click = (node: string) => (fake.node(node)!["onClick"] as () => void)();
    const page = () => fake.node(`web-${id}`);
    assert.deepEqual(page()?.["file"], { workspaceId: "w1", path: "site/index.html" });
    assert.equal(page()?.["revision"], 1);
    // An agent's turn ends: the file is read again, and the page reloads.
    fake.emit({ event: "agent", chatId: "c1", kind: { event: "run_finished", outcome: { status: "completed" } } });
    await fake.settle();
    assert.equal(page()?.["revision"], 2);
    click(`editor-${id}`);
    await fake.settle();
    (fake.node(`file-${id}`)!["onSave"] as (payload: { value: string }) => void)({ value: "<h1>two</h1>" });
    await fake.settle();
    click(`preview-${id}`);
    await fake.settle();
    assert.equal(page()?.["revision"], 3, "a save reloads the page");
  } finally {
    await dispose();
  }
});

test("Markdown and HTML files open in their preview until the editor is chosen, and the choice is kept", async () => {
  const stored = new Map<string, unknown>();
  const opened = async (fake: ReturnType<typeof fakeApi>, path: string) => {
    await fake.callService("open", { kind: "file", workspaceId: "w1", path });
    await fake.settle();
  };
  const fake = fakeApi({}, stored);
  let dispose = activate(fake.api);
  try {
    await fake.settle();
    await opened(fake, "README.md");
    assert.ok(fake.node("md-file:w1:README.md"), "a first Markdown file opens in its preview");
    (fake.node("editor-file:w1:README.md")!["onClick"] as () => void)();
    await fake.settle();
    assert.ok(fake.node("file-file:w1:README.md"));
    await opened(fake, "site/index.html");
    assert.ok(fake.node("file-file:w1:site/index.html"), "the next file opens in the editor chosen last");
    assert.deepEqual(fake.notices, []);
  } finally {
    await dispose();
  }
  // The choice outlives the plugin.
  const next = fakeApi({}, stored);
  dispose = activate(next.api);
  try {
    await next.settle();
    await opened(next, "docs/guide.md");
    assert.ok(next.node("file-file:w1:docs/guide.md"));
    (next.node("preview-file:w1:docs/guide.md")!["onClick"] as () => void)();
    await next.settle();
    await opened(next, "CHANGES.md");
    assert.ok(next.node("md-file:w1:CHANGES.md"), "choosing the preview again brings it back for new files");
  } finally {
    await dispose();
  }
});

test("a reply to a selection in a file, a diff or a Markdown preview is quoted in the open chat with its place", async () => {
  const quotes: unknown[] = [];
  // The Effect adapter calls through `result`.
  const quote = Object.assign(async () => null, {
    result: async (params: unknown) => {
      quotes.push(params);
      return { ok: true, value: null };
    },
  });
  const fake = fakeApi({ "divergence/chat": { quote, on: () => () => {} } });
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "src/a.ts" });
    await fake.settle();
    const reply = (id: string, event: object) => (fake.node(id)!["onQuote"] as (event: object) => void)(event);
    reply("file-file:w1:src/a.ts", { text: "```typescript\nconst a = 1;\n```", lines: [2, 2] });
    await fake.settle();
    await fake.callService("open", { kind: "diff", workspaceId: "w1", path: "src/a.ts", diff: "--- a/src/a.ts\n+++ b/src/a.ts\n@@ -3,2 +3,1 @@\n-x\n-y\n" });
    await fake.settle();
    reply("diff-diff:w1:src/a.ts", { text: "```typescript\nx\ny\n```", lines: [3, 4], side: "original", path: "src/a.ts" });
    await fake.settle();
    // A Markdown preview's selection comes as Markdown, without lines.
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "docs/guide.md" });
    await fake.settle();
    (fake.node("preview-file:w1:docs/guide.md")!["onClick"] as () => void)();
    await fake.settle();
    reply("md-file:w1:docs/guide.md", { text: "Some **bold** words" });
    await fake.settle();
    assert.deepEqual(quotes, [
      { text: "`src/a.ts` line 2:\n```typescript\nconst a = 1;\n```" },
      { text: "`src/a.ts` lines 3–4, before the change:\n```typescript\nx\ny\n```" },
      { text: "`docs/guide.md`:\nSome **bold** words" },
    ]);
  } finally {
    await dispose();
  }
});

test("a reply without the chat plugin says so", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
    await fake.settle();
    (fake.node("file-file:w1:a.ts")!["onQuote"] as (event: object) => void)({ text: "```\na\n```", lines: [1, 1] });
    await fake.settle();
    assert.deepEqual(fake.notices, ["Replies need the chat plugin."]);
  } finally {
    await dispose();
  }
});

// An open file changed on disk by anything but its editor used to stay
// stale until a run finished, and a Source Control diff was a snapshot.
test("a file and a Source Control diff follow the workspace's changes on disk", async () => {
  const fake = fakeApi({}, new Map(), true);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "src/a.ts" });
    fake.diffs.set("b.ts", "@@ old");
    await fake.callService("open", { kind: "diff", workspaceId: "w1", path: "b.ts", diff: "@@ old", staged: false });
    await fake.callService("open", { kind: "diff", workspaceId: "w1", path: "turn.ts", diff: "@@ turn", chatId: "c1" });
    await fake.settle();
    const revision = () => Number(JSON.stringify(fake.drawTab("file", "file:w1:src/a.ts", true)).match(/"revision":(\d+)/)?.[1]);
    const before = revision();
    fake.callsReset();
    fake.diffs.set("b.ts", "@@ new");
    fake.changed(["/ws/src/a.ts", "/ws/.git/index", "/elsewhere/x"]);
    await fake.settle();
    const diffReads = fake.calls.filter((call) => call.method === "host/git.diff").map((call) => call.params);
    assert.deepEqual(diffReads, [{ workspaceId: "w1", path: "b.ts", staged: false, wholeFile: true }], "a turn's diff stays a snapshot");
    assert.ok(JSON.stringify(fake.drawTab("diff", "diff:w1:b.ts", true)).includes("@@ new"));
    assert.ok(revision() > before, "the file's editor reloads");
  } finally {
    await dispose();
  }
});

// Two changes close together read the diff twice; the first read answering
// last must not bring the older changes back.
test("a live diff shows the latest read, whatever order the reads answer in", async () => {
  const fake = fakeApi({}, new Map(), true);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.diffs.set("b.ts", "@@ one");
    await fake.callService("open", { kind: "diff", workspaceId: "w1", path: "b.ts", diff: "@@ one", staged: false });
    await fake.settle();
    fake.diffs.set("b.ts", "@@ two");
    const letGo = fake.gate("diff:b.ts");
    fake.changed(["/ws/b.ts"]);
    await fake.settle();
    fake.diffs.set("b.ts", "@@ three");
    fake.changed(["/ws/b.ts"]);
    await fake.settle();
    letGo();
    await fake.settle();
    const drawn = JSON.stringify(fake.drawTab("diff", "diff:w1:b.ts", true));
    assert.ok(drawn.includes("@@ three") && !drawn.includes("@@ two"), drawn);
  } finally {
    await dispose();
  }
});

// The service's close used to drop a dirty file's state before the host
// could ask whether to discard its changes.
test("closing a file with unsaved changes through the service keeps it until the user answers", async () => {
  const fake = fakeApi({}, new Map(), true);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
    await fake.settle();
    const onFileState = fake.node("file-file:w1:a.ts")?.onFileState as (event: unknown) => void;
    onFileState({ state: "ready", dirty: true });
    await fake.settle();
    await fake.callService("close", { kind: "file", path: "a.ts", workspaceId: "w1" });
    await fake.settle();
    assert.deepEqual(fake.items.map((item) => item.key), ["file:w1:a.ts"]);
    assert.equal(fake.beforeClose("file:w1:a.ts"), "Discard the unsaved changes to a.ts?");
  } finally {
    await dispose();
  }
});

// The visible tab used to be announced only when a tab opened, and a tab
// closed from its strip stayed the active one.
test("the visible tab is announced as tabs come on screen, and a strip close is forgotten", async () => {
  const fake = fakeApi();
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    await fake.callService("open", { kind: "file", workspaceId: "w1", path: "a.ts" });
    await fake.callService("open", { kind: "file", workspaceId: "w2", path: "a.ts" });
    await fake.settle();
    fake.emitted.length = 0;
    fake.drawTab("file", "file:w2:a.ts", false);
    fake.drawTab("file", "file:w1:a.ts", true);
    assert.deepEqual(fake.emitted, [{ event: "activeChanged", payload: { kind: "file", path: "a.ts", workspaceId: "w1" } }]);
    // The same path in another workspace is another tab.
    await fake.callService("close", { kind: "file", path: "a.ts", workspaceId: "w2" });
    assert.deepEqual(fake.items.map((item) => item.key), ["file:w1:a.ts"]);
    // Closed from its strip: the host drops it and the layouts change.
    fake.items.splice(0);
    fake.layoutsChanged();
    await fake.settle();
    assert.deepEqual(fake.emitted.at(-1), { event: "activeChanged", payload: null });
  } finally {
    await dispose();
  }
});

test("a diagram tab draws its source again after a restart", async () => {
  const stored = new Map<string, unknown>();
  const source = "flowchart LR\n  a --> b";
  const first = fakeApi({}, stored);
  const stop = activate(first.api);
  try {
    await first.settle();
    await first.callService("open", { kind: "diagram", workspaceId: "w1", path: "d1", title: "Flow", language: "mermaid", source });
    await first.settle();
  } finally {
    await stop();
  }
  const fake = fakeApi({}, stored);
  const dispose = activate(fake.api);
  try {
    await fake.settle();
    fake.drawTab("diagram", "diagram:w1:d1", true);
    await fake.settle();
    assert.ok(JSON.stringify(fake.drawTab("diagram", "diagram:w1:d1", true)).includes("a --> b"));
  } finally {
    await dispose();
  }
});

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.2.7latestNov 21, 2026>=5 <635.3 KB4 permissionsListed
0.2.6Nov 11, 2026>=5 <635 KB4 permissionsListed
0.2.5Nov 11, 2026>=5 <634.9 KB4 permissionsListed
0.2.4Nov 9, 2026>=5 <630 KB4 permissionsListed
0.2.3Oct 27, 2026>=2 <422 KB4 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.