- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/view/hooks/register.tsx?format=json
315 linesFirst import 89% · review 9% · rename 2% · infra-split 1% · pinch 1%Last change rename in version 100, 7 versions changed it
1// abso-view: what abso knows about this chat's folder, at a glance (#12).
2//
3// A status line entry, kept current: the space the folder is in, how many
4// files the draft changes, how far shared has moved on, who else has
5// unpushed changes in the same files, and news not yet looked at.
6// `/abso-view` opens a pane with the whole picture.
7//
8// Outside an abso folder it costs one folder lookup at session start and
9// nothing after. Inside one, it asks the server for /status and /where at
10// most every 30 seconds, and a few seconds after an edit.
12import type { Register } from "claude-code";
13import { atom, read, update } from "claude-code";
15import type { AvcsView } from "../types";
16import { STAMP } from "./stamp.ts";
18const PANE = "abso-view";
19const COMMAND = "abso-view";
20const TICK_MS = 3_000;
21const REFRESH_MS = 30_000;
22const AFTER_EDIT_MS = 2_000;
23const NEWS_SHOWN = 12;
24const EDIT_TOOLS = ["Edit", "MultiEdit", "Write", "NotebookEdit", "Bash"];
25/** Sent with each call, so the server can tell which mod, from which commit, made it (#29). */
26const CLIENT = `abso-view/${STAMP ?? "checkout"}`;
28const view = atom({ plugin: "abso-view", key: "view" } as const, null);
29const seenNewsAt = atom({ plugin: "abso-view", key: "seenNewsAt" } as const, "");
31// The engine interface, passed along (the validator refuses keeping it).
32type Engine = any;
34type Folder = { root: string; server: string; project: string; agent: string };
36let folder: Folder | undefined;
37let lastRefresh = 0;
38let editedAt = 0;
39let refreshing = false;
41function slash(path: string): string {
42 return path.replace(/\\/g, "/").replace(/\/+$/, "");
43}
45async function readOr($: Engine, path: string): Promise<string | undefined> {
46 try {
47 return await $.fs.read(path);
48 } catch {
49 return undefined;
50 }
51}
53/** A folder's state folder: .abso, or .avcs in a folder from before the rename. (A mod can't import the client's state-dir.ts.) */
54async function stateOf($: Engine, root: string): Promise<string> {
55 return (await $.fs.exists(`${root}/.abso/config.json`)) ? `${root}/.abso` : `${root}/.avcs`;
56}
58/** A file under the user's home: ~/.abso/<name>, else the older ~/.avcs/<name>. */
59async function readHome($: Engine, home: string, name: string): Promise<string | undefined> {
60 return (await readOr($, `${slash(home)}/.abso/${name}`)) ?? (await readOr($, `${slash(home)}/.avcs/${name}`));
61}
63/** The abso folder at or above `dir`, with its settings. */
64async function findFolder($: Engine, dir: string): Promise<Folder | undefined> {
65 for (let at = slash(dir); at !== ""; ) {
66 const raw = await readOr($, `${await stateOf($, at)}/config.json`);
67 if (raw !== undefined) {
68 try {
69 const c = JSON.parse(raw) as { server: string; project: string; agent: string };
70 return { root: at, server: c.server, project: c.project, agent: c.agent };
71 } catch {
72 return undefined;
73 }
74 }
75 const up = at.slice(0, at.lastIndexOf("/"));
76 if (up === at || up === "" || /^[A-Za-z]:$/.test(up)) break;
77 at = up;
78 }
79 return undefined;
80}
82/**
83 * The servers the token goes to: the same rule as the client's core.ts tokenGoesTo (#30), copied because this
84 * mod installs alone. abso's hosted server and its Issues Worker, then this machine's ~/.avcs/servers.json and AVCS_TRUSTED_SERVERS.
85 */
86const TOKEN_SERVERS = ["https://api.abso.dev", "https://issues.abso.dev"];
88/** The servers ~/.avcs/servers.json names, and their Issues Workers: core.ts machineServers, copied. */
89function machineTrusted(text: string | undefined): string[] {
90 const out: string[] = [];
91 try {
92 const servers = (JSON.parse(text ?? "{}") as { servers?: unknown }).servers;
93 if (servers && typeof servers === "object")
94 for (const [server, about] of Object.entries(servers as Record<string, unknown>)) {
95 out.push(server);
96 const i = (about as { issues?: unknown } | null)?.issues;
97 if (typeof i === "string") out.push(i);
98 }
99 } catch {}
100 return out;
101}
103function tokenGoesTo(server: string, trusted: string | undefined): boolean {
104 const origin = (s: string): string | undefined => {
105 const m = /^(https?):\/\/([^/?#\\]+)\/*$/i.exec(s.trim());
106 if (!m || m[2]!.includes("@")) return undefined;
107 return `${m[1]!.toLowerCase()}://${m[2]!.toLowerCase()}`;
108 };
109 const o = origin(server);
110 if (o === undefined) return false;
111 const host = o.replace(/^https?:\/\//, "").replace(/:\d+$/, "");
112 if (host === "localhost" || host === "127.0.0.1" || host === "[::1]") return true;
113 if (!o.startsWith("https://")) return false;
114 return [...TOKEN_SERVERS, ...(trusted ?? "").split(",")].some((t) => t.trim() !== "" && origin(t) === o);
115}
117async function token($: Engine, server: string): Promise<string | undefined> {
118 const home = (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME"));
119 const machine = home ? machineTrusted(await readHome($, home, "servers.json")) : [];
120 const trusted = [(await $.env.get("AVCS_TRUSTED_SERVERS")) ?? "", ...machine].join(",");
121 if (!tokenGoesTo(server, trusted)) return undefined;
122 const env = await $.env.get("AVCS_TOKEN");
123 if (env) return env.trim();
124 return home ? (await readHome($, home, "token"))?.trim() || undefined : undefined;
125}
127async function get($: Engine, f: Folder, path: string): Promise<any> {
128 const bearer = await token($, f.server);
129 const r = await $.http.fetch(`${f.server.replace(/\/+$/, "")}/p/${encodeURIComponent(f.project)}${path}`, {
130 headers: { "x-abso-client": CLIENT, ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) },
131 });
132 if (!r.ok) throw new Error(`${path} answered ${r.status}`);
133 return JSON.parse(r.text);
134}
136/** The last news lines from .avcs/news.log, oldest first. */
137async function newsOf($: Engine, root: string): Promise<[string, string][]> {
138 const text = (await readOr($, `${await stateOf($, root)}/news.log`)) ?? "";
139 return text
140 .split("\n")
141 .filter((line) => line.includes("\t"))
142 .slice(-NEWS_SHOWN)
143 .map((line) => [line.slice(0, line.indexOf("\t")), line.slice(line.indexOf("\t") + 1)] as [string, string]);
144}
146async function refresh($: Engine): Promise<void> {
147 const f = folder;
148 if (f === undefined || refreshing) return;
149 refreshing = true;
150 lastRefresh = await $.clock.now();
151 try {
152 const [status, where, news] = await Promise.all([get($, f, "/status"), get($, f, "/where"), newsOf($, f.root)]);
153 const me = (status.agents ?? []).find((a: any) => a.agent === f.agent);
154 const space: string = me?.draft ?? "shared";
155 const draft = space === "shared" ? undefined : (status.drafts ?? []).find((d: any) => d.name === space);
156 const files: string[] = Array.isArray(me?.files) ? me.files : [];
157 const mine = new Set(files);
158 const overlap = new Map<string, Set<string>>();
159 for (const [file, entries] of Object.entries(where.files ?? {}) as [string, any[]][]) {
160 if (!mine.has(file)) continue;
161 for (const entry of entries) {
162 if (entry.agent === f.agent) continue;
163 overlap.set(entry.agent, (overlap.get(entry.agent) ?? new Set()).add(file));
164 }
165 }
166 const next: AvcsView = {
167 folder: { root: f.root, project: f.project, agent: f.agent },
168 space,
169 version: draft?.version ?? status.version,
170 base: me?.base ?? null,
171 files,
172 changes: me?.draftChanges ?? 0,
173 parked: (me?.parked ?? [])
174 .filter((p: any) => p.draftChanges > 0)
175 .map((p: any) => ({ space: p.draft ?? "shared", changes: p.draftChanges })),
176 overlap: [...overlap].map(([agent, set]) => ({ agent, files: [...set].sort() })),
177 news,
178 at: lastRefresh,
179 error: null,
180 };
181 await update($, view, () => next);
182 $.ui.status(statusLine(next, await read($, seenNewsAt)));
183 } catch (err) {
184 const message = (err as Error).message;
185 await update($, view, (old) => (old === null ? null : { ...old, error: message }));
186 $.ui.status(`abso: can't reach the server (${message})`);
187 } finally {
188 refreshing = false;
189 }
190}
192function plural(n: number, word: string): string {
193 return `${n} ${word}${n === 1 ? "" : "s"}`;
194}
196function unread(v: AvcsView, seen: string): number {
197 return v.news.filter(([at]) => at > seen).length;
198}
200function statusLine(v: AvcsView, seen: string): string {
201 const parts = [`abso: ${v.space === "shared" ? "shared" : `draft ${v.space}`}`];
202 parts.push(v.files.length === 0 ? "nothing unpushed" : `${plural(v.files.length, "file")} unpushed`);
203 if (v.base !== null && v.base < v.version)
204 parts.push(`${v.space === "shared" ? "shared" : "the draft"} is ${v.version - v.base} ahead (abso pull)`);
205 if (v.overlap.length > 0) parts.push(`${v.overlap.map((o) => o.agent).join(", ")} also on your files`);
206 const fresh = unread(v, seen);
207 if (fresh > 0) parts.push(`${plural(fresh, "news item")} (/abso-view)`);
208 return parts.join(" · ");
209}
211export const register: Register = (on) => {
212 on("session.start", async ($, e, next) => {
213 await $.command.register({
214 name: COMMAND,
215 description: "Show this folder's abso state: space, draft, who else is on your files, news",
216 });
217 folder = await findFolder($, await $.session.cwd());
218 if (folder !== undefined) {
219 void refresh($);
220 $.clock.every(TICK_MS, async () => {
221 const now = await $.clock.now();
222 const due = now - lastRefresh >= REFRESH_MS || (editedAt > lastRefresh && now - editedAt >= AFTER_EDIT_MS);
223 if (due) void refresh($);
224 });
225 }
226 return next(e);
227 });
229 on("tool.call", { tool: EDIT_TOOLS }, async ($, e, next) => {
230 const ran = await next(e);
231 if (folder !== undefined) editedAt = await $.clock.now();
232 return ran;
233 });
235 on("command.run", { command: COMMAND }, async ($) => {
236 if (folder === undefined)
237 return { text: "This chat is not in an abso folder (no .abso/config.json at or above its folder)." };
238 await refresh($);
239 await $.ui.open({ id: PANE, title: `abso: ${folder.project} as ${folder.agent}` });
240 // Opening the view reads the news: the status line stops counting it.
241 const v = await read($, view);
242 const newest = v?.news.at(-1)?.[0];
243 if (v !== null && newest !== undefined) {
244 await update($, seenNewsAt, () => newest);
245 $.ui.status(statusLine(v, newest));
246 }
247 return { text: "Opened the abso view." };
248 });
250 on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
251 const { Box, Text } = $.ui.resolve(e);
252 const v = await read($, view);
253 if (v === null) return <Text dimColor>Asking the server...</Text>;
254 return (
255 <Box flexDirection="column">
256 {v.error !== null && <Text color="red">The last refresh failed: {v.error}</Text>}
257 <Text bold>
258 {v.space === "shared" ? "Working in shared" : `Working in draft ${v.space}`}, at version {v.version}
259 {v.base !== null && v.base < v.version
260 ? ` (your draft builds on ${v.base}; abso pull brings in the rest)`
261 : ""}
262 </Text>
263 <Text> </Text>
264 <Text bold>Your unpushed changes</Text>
265 {v.files.length === 0 ? (
266 <Text dimColor> None.</Text>
267 ) : (
268 <Box flexDirection="column">
269 <Text>
270 {" "}
271 {plural(v.changes, "change")} in {plural(v.files.length, "file")}:
272 </Text>
273 {v.files.slice(0, 20).map((file) => (
274 <Text> {file}</Text>
275 ))}
276 {v.files.length > 20 && <Text dimColor> and {v.files.length - 20} more</Text>}
277 </Box>
278 )}
279 {v.parked.length > 0 && (
280 <Text>
281 {" "}
282 Parked: {v.parked.map((p) => `${p.space} (${plural(p.changes, "change")})`).join(", ")}; abso switch brings
283 it back.
284 </Text>
285 )}
286 <Text> </Text>
287 <Text bold>Others on your files</Text>
288 {v.overlap.length === 0 ? (
289 <Text dimColor> Nobody else has unpushed changes in them.</Text>
290 ) : (
291 v.overlap.map((o) => (
292 <Text>
293 {" "}
294 {o.agent}: {o.files.join(", ")}
295 </Text>
296 ))
297 )}
298 <Text> </Text>
299 <Text bold>News</Text>
300 {v.news.length === 0 ? (
301 <Text dimColor> None yet.</Text>
302 ) : (
303 v.news.map(([at, line]) => (
304 <Text>
305 {" "}
306 {at.slice(11, 16)} {line}
307 </Text>
308 ))
309 )}
310 <Text> </Text>
311 <Text dimColor>Refreshed {new Date(v.at).toISOString().slice(11, 19)} UTC; every 30 s, and after edits.</Text>
312 </Box>
313 );
314 });
315};