Official
files
Built-in files UI (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/files@0.2.6
Permissions in 0.2.6
Files
tabs.test.ts20.1 KB
// Files open through the divergence/tabs service and follow its visible
// tab. Real activation with a canned tabs client: opening calls the
// service, the active event selects the file, and without a provider
// opening does nothing.
import assert from "node:assert/strict";
import { test } from "node:test";
import * as z from "zod";
import type { Api, AppState, AppStatePatch, HostEvent, RenderResult, SlotOptions, ViewContext } from "divergence";
import { testLayer } from "divergence/effect/testing";
import activate from "./main.ts";
import { touchedFolders } from "./panel.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 Search = (params: {
depth?: number;
path?: string;
query?: string;
}) => Promise<{ paths: string[]; folders?: string[] }>;
// The default answers like a host before `depth`: every path, no folders.
const everyPath: Search = async () => ({ paths: ["README.md", "src/a.ts", "src/z.ts"] });
function fakeApi(withTabs: boolean, activeTab: { kind: string; path: string } | null, search: Search = everyPath) {
const watchers: ((paths: readonly string[]) => unknown)[] = [];
let state: AppState = { workspaceId: "w1", shared: { rightPanel: "files" } };
const appListeners = new Set<(state: AppState) => void>();
const views: { render: (ctx: ViewContext<object>) => RenderResult; active: boolean }[] = [];
const listeners = new Map<string, Set<(event: HostEvent) => unknown>>();
const calls: { method: string; params: unknown }[] = [];
const tabsCalls: { method: string; params: unknown }[] = [];
const tabsSubs = new Map<string, Set<(payload: unknown) => void>>();
const commands = new Map<string, () => unknown>();
const focused: string[] = [];
let dirty = true;
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 call = async (method: string, params: unknown) => {
calls.push({ method, params });
if (method === "host/workspaces.list") return { workspaces: [{ id: "w1", name: "w1", path: "/ws" }] };
if (method === "host/fs.search")
return search(
z
.object({ depth: z.number().optional(), path: z.string().optional(), query: z.string().optional() })
.parse(params),
);
throw new Error(`Unexpected host method ${method}`);
};
const tabsClient = {
open: Object.assign(async (params: unknown) => ({ id: "tab" }), {
// The Effect adapter calls through `result`, never the direct call.
result: async (params: unknown) => {
tabsCalls.push({ method: "open", params });
return { ok: true as const, value: { id: "tab" } };
},
}),
close: Object.assign(async () => null, {
result: async (params: unknown) => {
tabsCalls.push({ method: "close", params });
return { ok: true as const, value: null };
},
}),
active: Object.assign(async () => activeTab, {
result: async () => ({ ok: true as const, value: activeTab }),
}),
on: (event: string, fn: (payload: unknown) => void) => {
const key = `divergence/tabs|${event}`;
const set = tabsSubs.get(key) ?? new Set<(payload: unknown) => void>();
tabsSubs.set(key, set);
set.add(fn);
return () => {
set.delete(fn);
};
},
};
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: "files",
id: "divergence/files",
services: {
provide: async () => ({ emit: () => {}, remove: () => {} }),
get: (name: string) => {
if (name === "divergence/tabs" && withTabs) return tabsClient;
throw new Error(`no provider for ${name}`);
},
available: (name: string) => name === "divergence/tabs" && withTabs,
when: (name: string, fn: (client: unknown) => void) => {
fn(name === "divergence/tabs" && withTabs ? tabsClient : undefined);
return () => {};
},
},
host: { ...broker.api.host, call, kernel: call },
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);
};
},
},
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 };
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: (def: { id: string; run: () => unknown }) => {
commands.set(def.id, def.run);
return { remove() {} };
},
notify: () => {},
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: {},
set: () => {},
app: state,
plugin: "files",
update: () => {
dirty = true;
},
}),
);
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("files did not settle");
};
const nodeSchema = z.object({ id: z.string().optional(), children: z.array(z.unknown()).optional() }).passthrough();
function found(tree: unknown): Record<string, unknown>[] {
if (Array.isArray(tree)) return tree.flatMap(found);
const parsed = nodeSchema.safeParse(tree);
if (!parsed.success) return [];
return [
parsed.data,
...(parsed.data.children ?? []).flatMap(found),
...(Array.isArray(parsed.data.items) ? parsed.data.items.flatMap(found) : []),
];
}
const invoke = (id: string, event = "onClick", payload: unknown = {}) => {
const node = trees.flatMap((view) => found(view)).find((node) => node.id === id);
assert.ok(node, `Missing ${id}`);
const handler = z.custom<(payload: unknown) => unknown>((value) => typeof value === "function").parse(node[event]);
handler(payload);
};
return {
api,
calls,
tabsCalls,
update,
settle,
invoke,
trees: () => stable(trees),
command: async (id: string) => {
await commands.get(id)?.();
await settle();
},
focused,
state: () => state,
changed: (paths: readonly string[]) => {
for (const fn of watchers) fn(paths);
},
tabsActive: (tab: { kind: string; path: string; workspaceId?: string } | null) => {
for (const fn of tabsSubs.get("divergence/tabs|activeChanged") ?? []) fn(tab);
},
};
}
test("selecting a file calls the tabs service, and the visible tab selects it", async () => {
const fake = fakeApi(true, { kind: "file", path: "README.md" });
const dispose = activate(fake.api);
try {
await fake.settle();
// The initial visible tab arrives through the service, not shared state.
assert.ok(fake.trees().includes('"selected":"README.md"'));
fake.invoke("files-w1", "onSelect", { id: "src/a.ts", folder: false });
await fake.settle();
assert.deepEqual(fake.tabsCalls, [
{ method: "open", params: { kind: "file", workspaceId: "w1", path: "src/a.ts", focus: true } },
]);
fake.tabsActive({ kind: "file", path: "src/a.ts" });
await fake.settle();
assert.ok(fake.trees().includes('"selected":"src/a.ts"'));
// The same path in another workspace is not this tree's file.
fake.tabsActive({ kind: "file", path: "src/a.ts", workspaceId: "w2" });
await fake.settle();
assert.ok(fake.trees().includes('"selected":null'));
fake.tabsActive({ kind: "file", path: "src/a.ts", workspaceId: "w1" });
await fake.settle();
assert.ok(fake.trees().includes('"selected":"src/a.ts"'));
// A non-file tab clears the selection.
fake.tabsActive({ kind: "terminal", path: "t1" });
await fake.settle();
assert.ok(fake.trees().includes('"selected":null'));
} finally {
await dispose();
}
});
test("Show Files opens the panel with its tree holding the keyboard, and closes it again", async () => {
const fake = fakeApi(false, null);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.update({ shared: { rightPanel: null } });
await fake.command("files.toggle");
assert.equal(fake.state().shared?.rightPanel, "files");
assert.deepEqual(fake.focused, ["files-w1"]);
await fake.command("files.toggle");
assert.equal(fake.state().shared?.rightPanel, null);
assert.deepEqual(fake.focused, ["files-w1"], "closing leaves the keyboard where it is");
} finally {
await dispose();
}
});
test("without the tabs plugin selecting a file does nothing", async () => {
const fake = fakeApi(false, null);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.invoke("files-w1", "onSelect", { id: "src/a.ts", folder: false });
await fake.settle();
assert.deepEqual(fake.tabsCalls, []);
assert.ok(fake.trees().includes('"selected":null'));
} finally {
await dispose();
}
});
/// The workspace is watched: a file made or removed anywhere shows at once,
/// and only the shown folders it touched are listed again. The tree used
/// to change only after an agent's turn or a click on Refresh.
test("a change in the workspace lists again only the shown folders it touched", async () => {
const listings: Record<string, { paths: string[]; folders: string[] }> = {
"": { paths: ["README.md"], folders: ["src"] },
"src/": { paths: ["a.ts"], folders: [] },
};
const fake = fakeApi(true, null, async ({ path }) => listings[path ?? ""]!);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true });
await fake.settle();
const before = fake.calls.length;
listings["src/"] = { paths: ["a.ts", "new file.ts"], folders: [] };
fake.changed(["/ws/src/new file.ts", "/ws/.git/index.lock", "/ws/target/debug/x"]);
await fake.settle();
assert.ok(fake.trees().includes('{"id":"src/new file.ts","label":"new file.ts","children":[]}'));
assert.deepEqual(
fake.calls.slice(before).map((call) => call.params),
[{ workspaceId: "w1", limit: 100000, depth: 1, path: "src/" }],
);
} finally {
await dispose();
}
});
test("a change names the listed folders it touched, or all of them when it is elsewhere", () => {
const listed = new Set(["", "src/", "src/deep/"]);
assert.deepEqual(touchedFolders("/ws", ["/ws/a.md", "/ws/src/deep", "/ws/other/x.ts"], listed), ["", "src/", "src/deep/"]);
assert.deepEqual(touchedFolders("/ws", ["/ws/.git/HEAD", "/ws/.divergence/x"], listed), []);
assert.equal(touchedFolders("/ws", ["/private/ws/a.md"], listed), null);
assert.equal(touchedFolders(null, ["/ws/a.md"], listed), null);
});
test("folders list when opened, the query goes to the host, and an older host answers once", async () => {
const listings: Record<string, { paths: string[]; folders: string[] }> = {
"": { paths: ["README.md"], folders: ["src"] },
"src/": { paths: ["a.ts"], folders: [] },
};
const fake = fakeApi(true, null, async ({ path, query }) =>
query ? { paths: ["src/a.ts"] } : listings[path ?? ""]!,
);
const dispose = activate(fake.api);
try {
await fake.settle();
const top = fake.trees();
assert.ok(top.includes('"id":"src/","label":"src","children":[{"id":"src/…","label":"Loading…","children":[]}]'));
assert.ok(!top.includes("Loading files"));
// The row a folder holds while it loads opens nothing.
fake.invoke("files-w1", "onSelect", { id: "src/…", folder: false });
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true });
await fake.settle();
assert.ok(fake.trees().includes('{"id":"src/a.ts","label":"a.ts","children":[]}'));
assert.ok(!fake.trees().includes("Loading…"));
fake.invoke("files-search", "onChange", { value: " a " });
await fake.settle();
// The matches open every folder they sit in, and the browsing tree
// stays behind them with the folder the user opened.
assert.ok(fake.trees().includes('"id":"files-search-w1","rowDrag":{"type":"divergence/item","itemKind":"tabs.file","keyPrefix":"file:w1:"},"openFolders":true,"files":[{"path":"src/a.ts"}]'));
assert.ok(fake.trees().includes('{"id":"src/a.ts","label":"a.ts","children":[]}'));
fake.invoke("files-search-w1", "onSelect", { id: "src/", folder: true });
fake.invoke("files-search-w1", "onSelect", { id: "src/a.ts", folder: false });
await fake.settle();
assert.deepEqual(fake.tabsCalls, [
{ method: "open", params: { kind: "file", workspaceId: "w1", path: "src/a.ts", focus: true } },
]);
const searches = fake.calls.filter((call) => call.method === "host/fs.search").map((call) => call.params);
assert.deepEqual(searches, [
{ workspaceId: "w1", limit: 100000, depth: 1, path: "" },
{ workspaceId: "w1", limit: 100000, depth: 1, path: "src/" },
{ workspaceId: "w1", query: "a", limit: 500 },
]);
} finally {
await dispose();
}
const older = fakeApi(true, null);
const stop = activate(older.api);
try {
await older.settle();
older.invoke("files-w1", "onSelect", { id: "src/", folder: true });
await older.settle();
assert.equal(older.calls.filter((call) => call.method === "host/fs.search").length, 1);
assert.ok(older.trees().includes('{"path":"src/a.ts"}'));
} finally {
await stop();
}
});
// A listing host for w1 and w2: `src/` holds `deep/`, which holds a file.
const listingHost: Search = async ({ path }) =>
({
"": { paths: ["README.md"], folders: ["src"] },
"src/": { paths: ["a.ts"], folders: ["deep"] },
"src/deep/": { paths: ["x.ts"], folders: [] },
})[path ?? ""] ?? { paths: [], folders: [] };
test("open folders come back as they were when the panel shows again and in each workspace", async () => {
const fake = fakeApi(true, null, listingHost);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true, expanded: true });
await fake.settle();
assert.ok(fake.trees().includes('"id":"src/","label":"src","open":true'));
fake.update({ shared: { rightPanel: null } });
await fake.settle();
assert.ok(!fake.trees().includes("files-w1"));
fake.update({ shared: { rightPanel: "files" } });
await fake.settle();
assert.ok(fake.trees().includes('"id":"src/","label":"src","open":true'), "the hidden panel kept it open");
fake.update({ workspaceId: "w2" });
await fake.settle();
assert.ok(!fake.trees().includes('"open":true'), "another workspace has its own folders");
fake.update({ workspaceId: "w1" });
await fake.settle();
// Back in w1, the open folder is listed again with the top, so it
// shows its files rather than a loading row.
assert.ok(fake.trees().includes('"id":"src/","label":"src","open":true,"children":[{"id":"src/deep/"'));
const listed = fake.calls.filter((call) => call.method === "host/fs.search").map((call) => z.object({ workspaceId: z.string(), path: z.string() }).parse(call.params));
assert.deepEqual(listed.slice(-2), [
{ workspaceId: "w1", path: "" },
{ workspaceId: "w1", path: "src/" },
]);
// Closing it, by pointer or keyboard, is kept too.
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true, expanded: false });
fake.update({ shared: { rightPanel: null } });
fake.update({ shared: { rightPanel: "files" } });
await fake.settle();
assert.ok(!fake.trees().includes('"open":true'));
} finally {
await dispose();
}
});
test("the open file's folders open in the tree, and Collapse All Folders closes them", async () => {
const fake = fakeApi(true, null, listingHost);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.tabsActive({ kind: "file", path: "src/deep/x.ts" });
await fake.settle();
const tree = fake.trees();
assert.ok(tree.includes('"id":"src/","label":"src","open":true'));
assert.ok(tree.includes('"id":"src/deep/","label":"deep","open":true,"children":[{"id":"src/deep/x.ts"'));
assert.ok(tree.includes('"selected":"src/deep/x.ts"'));
// A file of another workspace names folders this one does not have.
fake.tabsActive({ kind: "file", path: "lib/other/y.ts" });
await fake.settle();
assert.ok(!fake.trees().includes('"id":"lib/'));
await fake.command("files.collapseAll");
await fake.settle();
assert.ok(!fake.trees().includes('"open":true'));
} finally {
await dispose();
}
});
// The search used to show a blank panel for an answer with no matches, and
// a query typed before a workspace switch stood over an empty tree there.
test("an empty answer says No matches, and a workspace switch searches the new workspace", async () => {
const fake = fakeApi(true, null, async ({ path, query }) =>
query ? { paths: query === "readme" ? [] : ["README.md"] } : (await listingHost({ path }))!,
);
const dispose = activate(fake.api);
try {
await fake.settle();
fake.invoke("files-search", "onChange", { value: "readme" });
await fake.settle();
assert.ok(fake.trees().includes("No matches"));
fake.update({ workspaceId: "w2" });
await fake.settle();
const searches = fake.calls.filter((call) => call.method === "host/fs.search").map((call) => call.params);
assert.deepEqual(
searches.filter((params) => (params as { query?: string }).query),
[
{ workspaceId: "w1", query: "readme", limit: 500 },
{ workspaceId: "w2", query: "readme", limit: 500 },
],
);
} finally {
await dispose();
}
});
// A folder whose listing failed kept its "Loading…" row forever.
test("a folder that cannot be listed says so, and opening it again lists it again", async () => {
let broken = true;
const fake = fakeApi(true, null, async ({ path }) => {
if (path === "src/" && broken) throw new Error("permission denied");
return (await listingHost({ path }))!;
});
const dispose = activate(fake.api);
try {
await fake.settle();
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true, expanded: true });
await fake.settle();
assert.ok(fake.trees().includes('{"id":"src/…","label":"Could not list this folder"'));
broken = false;
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true, expanded: false });
fake.invoke("files-w1", "onSelect", { id: "src/", folder: true, expanded: true });
await fake.settle();
assert.ok(fake.trees().includes('{"id":"src/a.ts","label":"a.ts","children":[]}'));
} finally {
await dispose();
}
});
No comments yet.