Official
git
Built-in git 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/git@0.3.2
Permissions in 0.3.2
Files
testing.ts11.6 KB
// The git plugin activated against a fake host for tests: git commands answer from `run`, agents from `agents` and
// `prompt`, gh from `gh`, and the tabs service from a canned client. Every host, model, gh and tab call is recorded.
import assert from "node:assert/strict";
import * as z from "zod";
import type {
Api,
AppState,
AppStatePatch,
GitOutput,
GitStatus,
HostEvent,
ModelAgent,
ModelPromptOptions,
ModelPromptResult,
RenderResult,
ViewContext,
} from "divergence";
import { testLayer } from "divergence/effect/testing";
export const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
export interface FakeOptions {
readonly tabs?: boolean;
readonly status?: Partial<GitStatus>;
/** git's answer to `host/git.run`, which may wait; success with no output when it gives none. */
readonly run?: (args: readonly string[]) => Partial<GitOutput> | undefined | Promise<Partial<GitOutput>>;
readonly agents?: readonly ModelAgent[];
readonly prompt?: (options: ModelPromptOptions) => Promise<ModelPromptResult>;
/** gh's answer to a command, which may wait; without `gh`, gh is not installed. */
readonly gh?: (args: readonly string[]) => Partial<GitOutput> | Promise<Partial<GitOutput>>;
}
export const answer = (text: string): ModelPromptResult => ({
text,
usage: null,
status: "completed",
message: null,
agentId: "agent",
model: null,
effort: null,
});
/** A promise that waits until `release` is called, to hold a fake command in flight. */
export function held() {
let release = () => {};
const promise = new Promise<void>((resolve) => {
release = resolve;
});
return { promise, release };
}
/** A prompt that runs until the host cancels it; `aborted.value` turns true then. */
export const untilAborted = (aborted: { value: boolean }) => (options: ModelPromptOptions) =>
new Promise<ModelPromptResult>((_, reject) =>
options.signal?.addEventListener("abort", () => {
aborted.value = true;
reject(options.signal?.reason);
}),
);
function child({ stdout = "", stderr = "", code = 0 }: Partial<GitOutput>) {
const stream = (text: string) => ({
async *[Symbol.asyncIterator]() {
if (text) yield new TextEncoder().encode(text);
},
});
return {
pid: 1,
stdin: { write: async () => ({}), close: async () => ({}) },
stdout: stream(stdout),
stderr: stream(stderr),
exited: Promise.resolve({ code, signal: null }),
kill: async () => ({}),
};
}
export function fakeApi(options: FakeOptions = {}) {
let state: AppState = { workspaceId: "w1", shared: { rightPanel: "git" } };
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 prompts: ModelPromptOptions[] = [];
const ghCalls: (readonly string[])[] = [];
const opened: string[] = [];
const notices: string[] = [];
const focused: string[] = [];
const commands = new Map<string, () => unknown>();
let dirty = true;
let status: GitStatus = {
branch: "main",
upstream: null,
ahead: 0,
behind: 0,
isRepo: true,
entries: [{ path: "src/a.ts", staged: " ", unstaged: "M" }],
...options.status,
};
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 runArgs = z.object({ args: z.array(z.string()) });
const call = async (method: string, params: unknown) => {
calls.push({ method, params });
switch (method) {
case "host/git.watch":
return {};
case "host/git.status":
return status;
case "host/git.diff":
return { diff: "--- a/src/a.ts\n+++ b/src/a.ts\n@@ -1 +1 @@\n-old\n+new" };
case "host/git.run":
return { stdout: "", stderr: "", code: 0, ...(await options.run?.(runArgs.parse(params).args)) };
default:
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 () => null, {
result: async () => ({ ok: true as const, value: null }),
}),
on: () => () => {},
};
const withTabs = options.tabs ?? true;
const broker = testLayer();
// This assertion describes a local fake; unused API methods fail rather than impersonating external replies.
const api = new Proxy(
{
...broker.api,
plugin: "git",
id: "divergence/git",
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,
git: Object.fromEntries(
["status", "watch", "run", "diff"].map((name) => [
name,
(params: unknown) => call(`host/git.${name}`, params),
]),
),
},
models: {
list: async () => ({ agents: options.agents ?? [] }),
prompt: async (prompt: ModelPromptOptions) => {
prompts.push(prompt);
assert.ok(options.prompt, "Provide a fake for models.prompt");
return options.prompt(prompt);
},
},
process: {
...broker.api.process,
which: async (program: string) => {
const path = program === "gh" && options.gh ? "/usr/bin/gh" : null;
return { path, realPath: path };
},
start: async (program: string, args: readonly string[]) => {
assert.equal(program, "gh");
assert.ok(options.gh, "gh is not installed in this fake");
ghCalls.push(args);
return child(await options.gh(args));
},
},
openUrl: async (url: string) => {
opened.push(url);
return { opened: true as const };
},
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: { render: (ctx: ViewContext<object>) => RenderResult }) => {
const view = { render: definition.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: (definition: { id: string; run: () => unknown }) => {
commands.set(definition.id, definition.run);
return { 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: {},
set: () => {},
app: state,
plugin: "git",
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("git 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) : []),
];
}
/** The element with `id` in the last render, or `undefined`. */
const node = (id: string) => trees.flatMap((view) => found(view)).find((node) => node.id === id);
const invoke = (id: string, event = "onClick", payload: unknown = {}) => {
const target = node(id);
assert.ok(target, `Missing ${id}`);
const handler = z
.custom<(payload: unknown) => unknown>((value) => typeof value === "function")
.parse(target[event]);
handler(payload);
};
// A file's hover button in a section's tree, by its icon.
const action = (side: string, path: string, icon: string) => {
const tree = node(`git-tree-${side}`);
assert.ok(tree, `Missing git-tree-${side}`);
const file = z
.array(z.object({ path: z.string(), actions: z.array(z.object({ icon: z.string(), onClick: z.function() })) }))
.parse(tree["files"])
.find((f) => f.path === path);
const button = file?.actions.find((a) => a.icon === icon);
assert.ok(button, `Missing ${icon} of ${path}`);
button.onClick();
};
/** git commands run so far, as their arguments. */
const gitRuns = () =>
calls.filter((call) => call.method === "host/git.run").map((call) => runArgs.parse(call.params).args);
const setStatus = (patch: Partial<GitStatus>) => {
status = { ...status, ...patch };
};
const emit = (event: HostEvent) => {
for (const fn of [...(listeners.get(event.event) ?? []), ...(listeners.get("*") ?? [])]) fn(event);
};
/** Everything the views drew, as text to search. */
const rendered = () => JSON.stringify(trees);
return {
api,
calls,
tabsCalls,
prompts,
ghCalls,
opened,
notices,
update,
settle,
node,
invoke,
action,
gitRuns,
setStatus,
emit,
rendered,
state: () => state,
focused,
/** Runs a command the plugin registered, as its key does. */
command: async (id: string) => {
await commands.get(id)?.();
await settle();
},
};
}
No comments yet.