Skip to content

Commit fcf7c95

Browse files
trin94claude
andcommitted
feat(ai): add opencode vcs status sidebar
Opencode ignores TUI plugins given as npm specs (anomalyco/opencode#33884), so the entrypoint is an absolute file:// path into the config dir. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 38cddb5 commit fcf7c95

4 files changed

Lines changed: 245 additions & 2 deletions

File tree

‎.config/prek.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ rev = "v2.5.1"
1515
hooks = [
1616
{
1717
id = "biome-check",
18-
name = "format json",
19-
files = '\.(jsonc?)$',
18+
name = "format json and ts",
19+
files = '\.(jsonc?|tsx?)$',
2020
exclude = '\.config/biome\.jsonc',
2121
args = ["--config-path=.config"],
2222
},
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/** @jsxImportSource @opentui/solid */
2+
3+
// Compact VCS status in the OpenCode sidebar. The branch name is left out on
4+
// purpose: the sidebar header already shows it.
5+
6+
import { createSignal, For, Show } from "solid-js";
7+
import { collectStatus, gitRunner, type StatusSegment, statusSegments } from "./vcs";
8+
9+
const HEADING = "Git";
10+
// Last section in the sidebar, so it lands directly above the footer's branch line.
11+
const SLOT_ORDER = 900;
12+
const REFRESH_MS = 5000;
13+
const REFRESH_EVENTS = ["file.edited", "file.watcher.updated", "session.idle"];
14+
// TextAttributes.BOLD from @opentui/core, inlined: plugins cannot import that module.
15+
const BOLD = 1;
16+
17+
type Theme = { text: string; textMuted: string; diffAdded: string; diffRemoved: string };
18+
19+
type Api = {
20+
state: { path: { worktree: string; directory: string } };
21+
theme: { current: Theme };
22+
event: { on: (type: string, handler: () => void) => () => void };
23+
lifecycle: { onDispose: (fn: () => void) => unknown };
24+
slots: { register: (plugin: unknown) => unknown };
25+
};
26+
27+
function Status(props: { api: Api; segments: () => StatusSegment[] }) {
28+
const theme = () => props.api.theme.current;
29+
return (
30+
<Show when={props.segments().length > 0}>
31+
<box flexDirection="column" flexShrink={0}>
32+
<text fg={theme().text} attributes={BOLD} wrapMode="none">
33+
{HEADING}
34+
</text>
35+
<For each={props.segments()}>
36+
{(segment) => (
37+
<box flexDirection="row" gap={1} flexShrink={0}>
38+
<text fg={theme().textMuted} wrapMode="none">
39+
{segment.label}
40+
</text>
41+
<Show when={segment.additions > 0}>
42+
<text fg={theme().diffAdded} wrapMode="none">
43+
+{segment.additions}
44+
</text>
45+
</Show>
46+
<Show when={segment.deletions > 0}>
47+
<text fg={theme().diffRemoved} wrapMode="none">
48+
-{segment.deletions}
49+
</text>
50+
</Show>
51+
</box>
52+
)}
53+
</For>
54+
</box>
55+
</Show>
56+
);
57+
}
58+
59+
export default {
60+
id: "vcs-status",
61+
tui: async (api: Api) => {
62+
const [segments, setSegments] = createSignal<StatusSegment[]>([]);
63+
64+
let refreshing = false;
65+
const refresh = async () => {
66+
if (refreshing) return;
67+
refreshing = true;
68+
try {
69+
const path = api.state.path;
70+
const status = await collectStatus(gitRunner(path.worktree || path.directory));
71+
setSegments(status ? statusSegments(status) : []);
72+
} catch {
73+
setSegments([]);
74+
} finally {
75+
refreshing = false;
76+
}
77+
};
78+
79+
void refresh();
80+
81+
const timer = setInterval(() => void refresh(), REFRESH_MS);
82+
api.lifecycle.onDispose(() => clearInterval(timer));
83+
for (const event of REFRESH_EVENTS) {
84+
const off = api.event.on(event, () => void refresh());
85+
api.lifecycle.onDispose(off);
86+
}
87+
88+
api.slots.register({
89+
order: SLOT_ORDER,
90+
slots: {
91+
sidebar_content: () => <Status api={api} segments={segments} />,
92+
},
93+
});
94+
},
95+
};
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
// Git metrics for the OpenCode sidebar.
2+
//
3+
// Two independent numbers, deliberately not OpenCode's own diff counters:
4+
// branch = merge-base(<default branch>, HEAD) -> HEAD (committed work on this branch)
5+
// dirty = HEAD -> index + working tree (tracked, not committed yet)
6+
7+
import { execFile } from "node:child_process";
8+
9+
export type Stats = {
10+
files: number;
11+
additions: number;
12+
deletions: number;
13+
};
14+
15+
export type BaseBranch = {
16+
/** What to call it on screen. */
17+
label: string;
18+
/** A ref that actually resolves, which the label may not: a clone need not carry the branch locally. */
19+
ref: string;
20+
};
21+
22+
export type VcsStatus = {
23+
base: string;
24+
branch: Stats;
25+
dirty: Stats;
26+
};
27+
28+
export type StatusSegment = {
29+
label: string;
30+
additions: number;
31+
deletions: number;
32+
};
33+
34+
export type GitRunner = (args: string[]) => Promise<string | undefined>;
35+
36+
const FALLBACK_BASE = "main";
37+
const BASE_CANDIDATES = ["main", "master"];
38+
39+
function emptyStats(): Stats {
40+
return { files: 0, additions: 0, deletions: 0 };
41+
}
42+
43+
/** Sum `git diff --numstat` output. Binary files report "-" and count as changed files only. */
44+
export function parseNumstat(output: string): Stats {
45+
const stats = emptyStats();
46+
for (const line of output.split("\n")) {
47+
if (line.trim() === "") continue;
48+
const [additions = "", deletions = ""] = line.split("\t");
49+
stats.files += 1;
50+
const added = Number.parseInt(additions, 10);
51+
const deleted = Number.parseInt(deletions, 10);
52+
if (Number.isInteger(added)) stats.additions += added;
53+
if (Number.isInteger(deleted)) stats.deletions += deleted;
54+
}
55+
return stats;
56+
}
57+
58+
function hasLines(stats: Stats): boolean {
59+
return stats.additions > 0 || stats.deletions > 0;
60+
}
61+
62+
function fileCount(count: number): string {
63+
return `${count} ${count === 1 ? "file" : "files"}`;
64+
}
65+
66+
/** One line each, kept separate so the sidebar can colour additions and deletions on its own. */
67+
export function statusSegments(status: VcsStatus): StatusSegment[] {
68+
const segments: StatusSegment[] = [];
69+
const { branch, dirty } = status;
70+
if (branch.files > 0) {
71+
// Binary-only changes carry no line counts, so the file count is all that is left to show.
72+
const label = `Since ${status.base}:`;
73+
segments.push({
74+
label: hasLines(branch) ? label : `${label} ${fileCount(branch.files)}`,
75+
additions: branch.additions,
76+
deletions: branch.deletions,
77+
});
78+
}
79+
if (dirty.files > 0) {
80+
segments.push({
81+
label: `Uncommitted: ${fileCount(dirty.files)}`,
82+
additions: dirty.additions,
83+
deletions: dirty.deletions,
84+
});
85+
}
86+
return segments;
87+
}
88+
89+
/** Trimmed stdout, or undefined when git fails (not a repo, unknown ref, ...). */
90+
export function gitRunner(cwd: string): GitRunner {
91+
return (args) =>
92+
new Promise((resolve) => {
93+
execFile("git", ["--no-optional-locks", ...args], { cwd }, (error, stdout) => {
94+
resolve(error ? undefined : stdout.trim());
95+
});
96+
});
97+
}
98+
99+
/** Local branch first so a stale remote does not widen the delta, remote as the fallback. */
100+
async function resolveRef(run: GitRunner, name: string): Promise<string | undefined> {
101+
for (const ref of [`refs/heads/${name}`, `refs/remotes/origin/${name}`]) {
102+
if ((await run(["rev-parse", "--verify", "--quiet", ref])) !== undefined) return ref;
103+
}
104+
return undefined;
105+
}
106+
107+
/** The branch point: whatever the remote calls default, else the first branch that exists. */
108+
export async function detectBase(run: GitRunner): Promise<BaseBranch> {
109+
const remoteHead = await run(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
110+
const names = remoteHead ? [remoteHead.replace(/^origin\//, "")] : BASE_CANDIDATES;
111+
for (const name of names) {
112+
const ref = await resolveRef(run, name);
113+
if (ref) return { label: name, ref };
114+
}
115+
return { label: FALLBACK_BASE, ref: FALLBACK_BASE };
116+
}
117+
118+
async function collectBranch(run: GitRunner, ref: string): Promise<Stats> {
119+
const mergeBase = await run(["merge-base", ref, "HEAD"]);
120+
if (!mergeBase) return emptyStats();
121+
const numstat = await run(["diff", "--numstat", `${mergeBase}..HEAD`]);
122+
return numstat === undefined ? emptyStats() : parseNumstat(numstat);
123+
}
124+
125+
async function collectDirty(run: GitRunner): Promise<Stats> {
126+
const numstat = await run(["diff", "--numstat", "HEAD"]);
127+
return numstat === undefined ? emptyStats() : parseNumstat(numstat);
128+
}
129+
130+
/** Undefined outside a repository. Branch and dirty stats are gathered concurrently. */
131+
export async function collectStatus(run: GitRunner): Promise<VcsStatus | undefined> {
132+
if ((await run(["rev-parse", "--git-dir"])) === undefined) return undefined;
133+
const base = await detectBase(run);
134+
const [branch, dirty] = await Promise.all([collectBranch(run, base.ref), collectDirty(run)]);
135+
return { base: base.label, branch, dirty };
136+
}

‎setups/programs/ai.nix‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,21 @@ in
9494
};
9595
};
9696

97+
# One directory, so the entrypoint can import its sibling. Per-file entries land in
98+
# separate store paths and the relative import breaks.
99+
xdg.configFile."opencode/tui-plugin/vcs-status".source = builtins.path {
100+
name = "opencode-vcs-status";
101+
path = ./agents/opencode/vcs-status;
102+
filter = path: _: !(lib.hasSuffix ".test.ts" path);
103+
};
104+
97105
xdg.configFile."opencode/tui.json".text = builtins.toJSON {
98106
"$schema" = "https://opencode.ai/tui.json";
99107
keybinds.tool_details = "<leader>d";
108+
# TUI plugins only load from an absolute file:// entrypoint, npm specs are broken upstream.
109+
plugin = [
110+
"file://${config.xdg.configHome}/opencode/tui-plugin/vcs-status/index.tsx"
111+
];
100112
};
101113

102114
})

0 commit comments

Comments
 (0)