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.7

Permissions in 0.2.7

  • 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

controller.ts13.8 KB
// Tabs' scoped effects serve the divergence/tabs service and consume legacy shared requests.
// The service emits which tab is visible; third-party plugins still open and
// close through the shared openTab/closeTab keys those writes once were.
// File reads run in the layer scope so closing/unloading never leaves a detached task.
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as z from "zod";
import { App, Host, Kernel, Layouts, Notify, Storage, Views, parse } from "divergence/effect";
import type { AppState, ViewHandle } from "divergence";
import {
  activeTab,
  closeRequest,
  closeTab,
  editorId,
  fileResponse,
  initialState,
  isDirty,
  liveDiff,
  moveTab,
  nativeFileContent,
  nextRevision,
  openRequest,
  openTab,
  PREVIEW_KEY,
  readContent,
  readError,
  tabId,
  tabName,
} from "./tabs.ts";
import type { FileState, Tab, TabInput, TabsState } from "./tabs.ts";
import { makeDiagrams } from "./diagrams.ts";
import { makeFollow } from "./follow.ts";
import { makeVisible, refOf } from "./visible.ts";
import { makeReply } from "./reply.ts";

// How long a file tab with no text yet waits for it before it draws, loading.
// A local read is back well within it, so a file opens with its text.
const READ_WAIT = "100 millis";

// What the divergence/tabs events carry: which tab, or none visible.
export interface TabRef {
  readonly kind: Tab["kind"];
  readonly path: string;
  readonly workspaceId?: string;
}
const names = (tab: Tab, ref: TabRef) =>
  tab.kind === ref.kind && tab.path === ref.path && (ref.workspaceId === undefined || tab.workspaceId === ref.workspaceId);

const hasNativeFileEditor = Effect.fn("Tabs.hasNativeFileEditor")(function* () {
  const kernel = yield* Kernel;
  return yield* kernel.call("editor.file", {}).pipe(
    Effect.as(true),
    Effect.catchTag("KernelCallFailed", (error) =>
      /method not found|unknown kernel method/.test(error.message) ? Effect.succeed(false) : Effect.fail(error),
    ),
  );
});

// The choice between preview and editor that new Markdown and HTML tabs
// open with. It comes back from plugin storage without holding up the first
// draw (a local read is back long before a tab is opened), and what it
// returns keeps a new choice there.
const keepPreviewChoice = Effect.fn("Tabs.keepPreviewChoice")(function* (state: TabsState) {
  const storage = yield* Storage;
  const notify = yield* Notify;
  yield* storage.get(PREVIEW_KEY, z.boolean()).pipe(
    Effect.tap((preview) =>
      Effect.sync(() => {
        if (preview !== undefined) state.preview = preview;
      }),
    ),
    Effect.catch((error) => notify.error(`Could not read the preview choice: ${error.message}`)),
    Effect.forkScoped({ startImmediately: true }),
  );
  return Effect.fn("Tabs.rememberPreview")(function* (preview: boolean) {
    if (state.preview === preview) return;
    state.preview = preview;
    yield* storage
      .set(PREVIEW_KEY, preview)
      .pipe(Effect.catch((error) => notify.error(`Could not keep the preview choice: ${error.message}`)));
  });
});

// The compatibility reader for a kernel without file-backed editors.
const legacyFileReader = (host: Host["Service"], state: TabsState, redraw: () => void) =>
  Effect.fn("Tabs.readFile")(function* (tab: TabInput, id: string) {
    yield* host.call("host/fs.read", { workspaceId: tab.workspaceId, path: tab.path }).pipe(
      Effect.flatMap((result) => parse("file contents", fileResponse, result)),
      Effect.tap((result) =>
        Effect.sync(() => {
          const previous = state.contents[id];
          if (!isDirty(previous)) state.contents[id] = { ...readContent(result), revision: nextRevision(previous) };
        }),
      ),
      Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted", "ParseFailed"], (error) =>
        Effect.sync(() => {
          if (isDirty(state.contents[id])) return;
          state.contents[id] = { error: error._tag === "ParseFailed" ? `${error.what}: ${error.issues.join("; ")}` : readError(error.message) };
        }),
      ),
    );
    if (state.tabs.some((tab) => tab.id === id)) redraw();
  });

const makeTabs = Effect.fn("Tabs.make")(function* () {
  const host = yield* Host;
  const notify = yield* Notify;
  const slots = yield* Views;
  const scope = yield* Effect.scope;
  const layouts = yield* Layouts;
  const nativeFiles = yield* hasNativeFileEditor();
  const state = initialState();
  // The host's item of each open tab, by tab id, for closing it there.
  const itemIds: Record<string, string> = {};
  const rememberPreview = yield* keepPreviewChoice(state);
  const reply = yield* makeReply();
  const views: ViewHandle[] = [];
  const redraw = () => {
    for (const view of views) view.update();
    layouts.redraw();
  };
  const { announce, visible, ...shown } = makeVisible(state);
  const readFile = legacyFileReader(host, state, redraw);
  const ensureFile = (tab: Tab) => void (state.contents[tab.id] ??= nativeFileContent());
  const fileState = Effect.fn("Tabs.fileState")(function* (id: string, next: FileState) {
    const content = state.contents[id];
    if (!content) return;
    content.fileState = next;
    redraw();
  });
  // The tab redraws only when it gains or loses its unsaved mark; the
  // editor keeps what is typed on its own.
  const edit = Effect.fn("Tabs.edit")(function* (id: string, value: string) {
    const content = state.contents[id];
    if (!content) return;
    const was = isDirty(content);
    content.draft = value;
    if (isDirty(content) !== was) redraw();
  });
  const refreshFile = Effect.fn("Tabs.refreshFile")(function* (tab: Tab) {
    if (!nativeFiles) return yield* readFile(tab, tab.id);
    ensureFile(tab);
    state.contents[tab.id]!.revision = nextRevision(state.contents[tab.id]);
    redraw();
  });
  const { readDiff, follow, unwatch } = yield* makeFollow(state, redraw, refreshFile);
  const diagrams = yield* makeDiagrams(state, redraw);

  const save = Effect.fn("Tabs.save")(function* (tab: Tab, value: string) {
    return yield* host.call("host/fs.write", { workspaceId: tab.workspaceId, path: tab.path, text: value }).pipe(
      Effect.map(() => {
        const content = state.contents[tab.id];
        if (content) Object.assign(content, { text: value, revision: nextRevision(content) });
        redraw();
        return true;
      }),
      Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], (error) =>
        notify.error(`Could not save ${tab.path}: ${error.message}`).pipe(Effect.as(false)),
      ),
    );
  });
  // Opens are numbered so that the latest one is shown even when an earlier
  // file's read comes back after it.
  let opens = 0;
  const open = Effect.fn("Tabs.open")(function* (request: TabInput & { readonly focus?: boolean }) {
    const ticket = ++opens;
    const id = tabId(request);
    const tab = openTab(state, request);
    // The tab itself is the host's: in the side split, or the pane the
    // layout puts it in, with the chat it came from. It opens at once, so
    // the tab asked for last is the one shown.
    yield* layouts.open({ kind: tab.kind, key: tab.id, ...(request.chatId ? { chatId: request.chatId } : {}) }).pipe(
      Effect.tap((opened) => Effect.sync(() => (itemIds[tab.id] = opened.itemId))),
      Effect.catch((error) => notify.error(`Could not open ${tabName(tab)}: ${error.message}`)),
    );
    yield* follow(tab);
    // The text came from a read made before the tab was watched: one more
    // read catches a change in between, and a read already on its way no
    // longer counts.
    if (liveDiff(tab)) yield* Effect.forkIn(readDiff(tab), scope, { startImmediately: true });
    if (request.kind === "diagram") yield* Effect.forkIn(diagrams.keep(tab), scope, { startImmediately: true });
    // A file with no text yet draws once its read is back; only a read slower
    // than READ_WAIT shows it loading.
    if (request.kind === "file" && nativeFiles) {
      ensureFile(tab);
    } else if (request.kind === "file") {
      const read = yield* Effect.forkIn(readFile(request, id), scope, { startImmediately: true });
      if (!state.contents[id]) {
        state.waiting.add(id);
        yield* Fiber.await(read).pipe(Effect.timeoutOption(READ_WAIT), Effect.ensuring(Effect.sync(() => state.waiting.delete(id))));
      }
    }
    // An open that a newer one overtook leaves the newer one in front.
    const latest = ticket === opens;
    if (latest) announce(tab);
    redraw();
    // The kernel holds the request until the editor is drawn, once its
    // text has loaded.
    if (request.kind === "file" && request.focus && latest) yield* slots.focus(editorId(tab));
    return tab;
  });
  // A tab the host no longer holds is forgotten here: its content, its
  // diagram's kept source, and its workspace's watch once nothing else there
  // is followed.
  const forget = Effect.fn("Tabs.forget")(function* (id: string) {
    const tab = state.tabs.find((tab) => tab.id === id);
    if (!tab) return;
    closeTab(state, id);
    delete itemIds[id];
    shown.forget(id);
    redraw();
    if (tab.kind === "diagram") yield* diagrams.drop(id);
    yield* unwatch(tab.workspaceId);
  });
  // Closing through the host first: a file with unsaved changes asks there
  // (`beforeClose`), and its tab stays until the user answers on it.
  const close = Effect.fn("Tabs.close")(function* (id: string) {
    const item = itemIds[id];
    const closed = item
      ? yield* layouts.close(item).pipe(
          Effect.catch((error) => notify.error(`Could not close the tab: ${error.message}`).pipe(Effect.as(false))),
        )
      : true;
    if (!closed) return;
    yield* forget(id);
    shown.closed();
  });
  // The host's open items of this plugin, after the layouts changed: a tab
  // closed from its strip is forgotten, and each known tab's item is noted
  // for closing it by reference.
  const reconcile = Effect.fn("Tabs.reconcile")(function* () {
    const { items } = yield* host.call("host/layouts.mine", {});
    const open = new Set(items.map((item) => item.key));
    for (const item of items) itemIds[item.key] ??= item.id;
    for (const tab of [...state.tabs]) if (!open.has(tab.id)) yield* forget(tab.id);
  });
  // Preview or editor for this tab, and the choice new Markdown and HTML
  // tabs open with from now on.
  const showPreview = Effect.fn("Tabs.showPreview")(function* (tab: Tab, preview: boolean) {
    tab.preview = preview;
    redraw();
    yield* rememberPreview(preview);
  });
  const select = Effect.fn("Tabs.select")(function* (tab: Tab) {
    state.active = tab.id;
    announce(tab);
    redraw();
  });
  const move = Effect.fn("Tabs.move")(function* (id: string, target: string, zone: string) {
    moveTab(state, id, target, zone);
    redraw();
  });
  // The divergence/tabs service methods: open and close by reference, and
  // which tab is visible. They share the open path above, without consuming
  // a legacy request.
  const closeByRef = Effect.fn("Tabs.closeByRef")(function* (ref: TabRef) {
    const tab = state.tabs.find((tab) => names(tab, ref));
    if (tab) yield* close(tab.id);
    return null;
  });
  const activeRef = Effect.fn("Tabs.activeRef")(function* (): Effect.fn.Return<TabRef | null> {
    const tab = state.tabs.find((tab) => tab.id === state.active) ?? state.tabs[0];
    return tab ? refOf(tab) : null;
  });
  return {
    state,
    nativeFiles,
    views,
    open,
    close,
    reconcile,
    visible,
    readDiff,
    restoreDiagram: diagrams.restore,
    follow,
    ensureFile,
    fileState,
    edit,
    save,
    closeByRef,
    activeRef,
    reply,
    showPreview,
    select,
    move,
    readFile,
    refreshFile,
    emitActive: shown.setEmit,
  };
});

export class Tabs extends Context.Service<Tabs, Effect.Success<ReturnType<typeof makeTabs>>>()("tabs/Tabs") {
  static readonly layer = Layer.effect(Tabs, makeTabs());
}

// Once the first render after a reload has brought the strip back
// (`keepStrip`), the visible tab is told again and the files whose reads
// the reload cut short are read again.
export const restore = Effect.fn("Tabs.restore")(function* (tabs: Tabs["Service"]) {
  const shown = activeTab(tabs.state);
  if (shown) yield* tabs.select(shown);
  const unread = tabs.state.tabs.filter((tab) => tab.kind === "file" && !tabs.nativeFiles && !tabs.state.contents[tab.id]);
  if (tabs.nativeFiles) for (const tab of tabs.state.tabs) if (tab.kind === "file") tabs.ensureFile(tab);
  yield* Effect.forEach(unread, (tab) => tabs.readFile(tab, tab.id), { concurrency: "unbounded", discard: true });
});

// Requests third-party plugins still write to the shared openTab/closeTab
// keys: each is handled once, by its nonce, and then cleared.
export const followApp = Effect.fn("Tabs.followApp")(
  function* (tabs: Tabs["Service"], next: AppState) {
    const { state } = tabs;
    const app = yield* App;
    const request = next.shared?.openTab;
    if (request) {
      const parsed = yield* parse("openTab", openRequest, request);
      if (parsed.nonce !== state.handled) {
        state.handled = parsed.nonce;
        yield* tabs.open(parsed);
        // Consumed requests must not reopen closed tabs after the app restarts.
        yield* app.update({ shared: { openTab: null } });
      }
    }
    const gone = next.shared?.closeTab;
    if (gone) {
      const parsed = yield* parse("closeTab", closeRequest, gone);
      if (parsed.nonce !== state.handledClose) {
        state.handledClose = parsed.nonce;
        yield* app.update({ shared: { closeTab: null } });
        const tab = state.tabs.find((tab) => names(tab, parsed));
        if (tab) yield* tabs.close(tab.id);
      }
    }
  },
  // Invalid shared data is reported without ending the request subscription.
  Effect.catchTag("ParseFailed", (error) =>
    Effect.gen(function* () {
      yield* (yield* Notify).error(`${error.what}: ${error.issues.join("; ")}`);
    }),
  ),
);

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.