agy-git-graph 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,12 +3,9 @@
3
3
  [![npm version](https://img.shields.io/npm/v/agy-git-graph.svg)](https://www.npmjs.com/package/agy-git-graph)
4
4
  [![license](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
5
 
6
- 在 **Google Antigravity 2.0** 中提供两种入口查看 Git 工作区更改、快捷提交、Diff 预览与多分支 SVG 可视化提交图(Commit Graph),运行时零外部 npm 依赖:
6
+ 在 **Google Antigravity 2.0** 左侧主导航栏(`Codex 同步` / `Powertools` 下方)挂载一键快捷按钮 **Git Graph**:点击后保留当前工作会话,自动展开/收起右侧官方 `Git` 侧边栏,支持查看工作区更改、快捷提交、Diff 预览与多分支 SVG 可视化提交图(Commit Graph),零外部 npm 依赖。
7
7
 
8
- - **左侧主导航栏一级入口(MCP App Global View)**:一点直达全页双栏 Git Graph 视图(自适应亮/暗主题)。
9
- - **右侧辅助侧边栏(Sidecar Aux Pane)**:在对话旁常驻窄屏紧凑 Git 面板。
10
-
11
- A lightweight, zero-dependency Git plugin for **Google Antigravity 2.0** with both a **1-click left-sidebar full-page view** (via official MCP App `global` entrypoint) and a **right-hand sidecar panel**, providing working-tree changes, quick commits, colored diffs, branch filtering, and a multi-branch SVG commit graph.
8
+ A lightweight, zero-dependency Git plugin for **Google Antigravity 2.0** that mounts a 1-click **Git Graph** quick-launch button in the left navigation bar to toggle the right-hand `Git` sidecar panel alongside your conversation, providing working-tree changes, quick commits, colored diffs, branch filtering, and a multi-branch SVG commit graph.
12
9
 
13
10
  ---
14
11
 
package/bin/cli.mjs CHANGED
@@ -48,11 +48,9 @@ Usage:
48
48
  function copyRuntimeFiles(targetDir) {
49
49
  const items = [
50
50
  ['plugin.json', false],
51
- ['mcp_config.json', false],
52
51
  ['README.md', false],
53
52
  ['LICENSE', false],
54
53
  ['assets', true],
55
- ['mcp', true],
56
54
  ['skills', true],
57
55
  ['sidecars/git_graph/sidecar.json', false],
58
56
  ['sidecars/git_graph/server.mjs', false],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-git-graph",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "DSH-style Git changes, commit box, diff viewer, and multi-branch SVG commit graph side panel plugin for Google Antigravity 2.0.",
6
6
  "license": "MIT",
@@ -35,8 +35,6 @@
35
35
  "files": [
36
36
  "bin/",
37
37
  "assets/",
38
- "mcp/",
39
- "mcp_config.json",
40
38
  "skills/",
41
39
  "sidecars/git_graph/sidecar.json",
42
40
  "sidecars/git_graph/server.mjs",
package/plugin.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "agy-git-graph",
3
3
  "displayName": "Git Graph (提交图)",
4
- "version": "1.1.0",
5
- "description": "在 Antigravity 右侧侧边栏查看 Git 工作区更改、提交代码、按分支筛选并浏览多分支可视化提交图(Commit Graph)与单次提交 Diff。",
4
+ "version": "1.2.0",
5
+ "description": "在 Antigravity 左侧导航栏挂载一键快捷按钮,点击保留当前会话并弹出/收起右侧 Git 面板:查看工作区更改、提交代码、按分支筛选并浏览多分支可视化提交图与单次提交 Diff。",
6
6
  "author": {
7
7
  "name": "s17765152890-gif",
8
8
  "url": "https://github.com/s17765152890-gif"
@@ -344,7 +344,6 @@
344
344
  </header>
345
345
  <div id="drawerBody"></div>
346
346
  </dialog>
347
- <!--__MCP_APP_BRIDGE__-->
348
347
  <script>
349
348
  'use strict';
350
349
 
@@ -354,10 +353,6 @@
354
353
  const timeFormat = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' });
355
354
  const relativeFormat = new Intl.RelativeTimeFormat('zh-CN', { numeric: 'auto' });
356
355
  const emptyStatus = { staged: [], unstaged: [] };
357
- const mcpBridge = globalThis.__AGY_MCP_EXT_APPS__ || null;
358
- let mcpApp = null;
359
- let mcpConnectPromise = null;
360
- let bootedFromToolResult = false;
361
356
  let selected = '';
362
357
  let repos = [];
363
358
  let repoState = null;
@@ -384,45 +379,7 @@
384
379
  $('notice').dataset.error = isError;
385
380
  }
386
381
 
387
- function applyHostCtx(ctx) {
388
- if (!ctx || !mcpBridge) return;
389
- if (ctx.theme) {
390
- document.documentElement.dataset.theme = ctx.theme;
391
- mcpBridge.applyDocumentTheme?.(ctx.theme);
392
- }
393
- if (ctx.styles?.variables) {
394
- mcpBridge.applyHostStyleVariables?.(ctx.styles.variables);
395
- }
396
- }
397
-
398
- function parseToolResultPayload(result) {
399
- if (result?.structuredContent && typeof result.structuredContent === 'object') {
400
- return result.structuredContent;
401
- }
402
- const text = result?.content?.[0]?.text;
403
- if (typeof text === 'string' && text.trim()) {
404
- try {
405
- return JSON.parse(text);
406
- } catch {
407
- return { ok: !result.isError, message: text };
408
- }
409
- }
410
- return {};
411
- }
412
-
413
382
  async function api(route, data = {}) {
414
- if (mcpApp) {
415
- if (mcpConnectPromise) await mcpConnectPromise;
416
- const result = await mcpApp.callServerTool({
417
- name: 'git_graph_rpc',
418
- arguments: { route, payload: data },
419
- });
420
- const payload = parseToolResultPayload(result);
421
- if (result?.isError || payload?.ok === false) {
422
- throw new Error(payload?.error || payload?.message || 'MCP RPC 调用失败');
423
- }
424
- return payload;
425
- }
426
383
  const response = await fetch('/api/' + route, {
427
384
  method: 'POST',
428
385
  headers: { 'Content-Type': 'application/json' },
@@ -968,30 +925,7 @@
968
925
  });
969
926
 
970
927
  renderState();
971
- if (mcpBridge) {
972
- mcpApp = new mcpBridge.App({ name: 'Git Graph', version: '1.1.0' }, {});
973
- mcpApp.onhostcontextchanged = applyHostCtx;
974
- mcpApp.ontoolresult = (result) => {
975
- const data = parseToolResultPayload(result);
976
- if (Array.isArray(data?.repos)) {
977
- bootedFromToolResult = true;
978
- repos = data.repos;
979
- const preferred = data.initialRepoPath || '';
980
- const next = [preferred, selected].find((path) => repos.some((repo) => repo.path === path));
981
- switchRepo(next || repos[0]?.path || '');
982
- renderRepoOptions();
983
- void refreshState();
984
- }
985
- };
986
- mcpConnectPromise = mcpApp.connect().then(() => {
987
- applyHostCtx(mcpApp.getHostContext());
988
- if (!bootedFromToolResult) return refreshRepos();
989
- }).catch((error) => {
990
- notice(error?.message || '连接 Antigravity MCP App 失败', true);
991
- });
992
- } else {
993
- refreshRepos();
994
- }
928
+ refreshRepos();
995
929
  </script>
996
930
  </body>
997
931
  </html>
@@ -0,0 +1,306 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ const INJECT_VERSION = '1.2.0';
6
+ const SIDECAR_ID = 'agy-git-graph/git_graph';
7
+
8
+ /**
9
+ * Resolve the path to Antigravity's DevToolsActivePort file.
10
+ */
11
+ export function resolveDevToolsPortFile({ platform = process.platform, env = process.env, home = homedir() } = {}) {
12
+ if (env.ANTIGRAVITY_CDP_PORT_FILE) return env.ANTIGRAVITY_CDP_PORT_FILE;
13
+ if (env.AGY_BROWSER_ACTIVE_PORT_FILE) return env.AGY_BROWSER_ACTIVE_PORT_FILE;
14
+ if (env.ANTIGRAVITY_USER_DATA_DIR) return join(env.ANTIGRAVITY_USER_DATA_DIR, 'DevToolsActivePort');
15
+ if (platform === 'win32') {
16
+ const appData = env.APPDATA || join(home, 'AppData', 'Roaming');
17
+ return join(appData, 'Antigravity', 'DevToolsActivePort');
18
+ }
19
+ if (platform === 'darwin') {
20
+ return join(home, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort');
21
+ }
22
+ const xdg = env.XDG_CONFIG_HOME || join(home, '.config');
23
+ return join(xdg, 'Antigravity', 'DevToolsActivePort');
24
+ }
25
+
26
+ /**
27
+ * Read the CDP HTTP port from DevToolsActivePort if available.
28
+ */
29
+ export function readCdpPort(portFile = resolveDevToolsPortFile()) {
30
+ try {
31
+ if (!portFile || !existsSync(portFile)) return 0;
32
+ const firstLine = readFileSync(portFile, 'utf8').split(/\r?\n/)[0]?.trim();
33
+ const port = Number(firstLine);
34
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : 0;
35
+ } catch {
36
+ return 0;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Build the self-contained renderer script injected into Antigravity windows.
42
+ * It adds a quick-launch button in the top left-sidebar nav group (right below
43
+ * Codex Sync / Powertools / Customizations) and toggles Git Graph in the official right side pane.
44
+ */
45
+ export function buildSidebarInjectionScript({ sidecarId = SIDECAR_ID } = {}) {
46
+ const safeSidecarId = JSON.stringify(String(sidecarId));
47
+ const safeVer = JSON.stringify(INJECT_VERSION);
48
+
49
+ return `(() => {
50
+ const SIDECAR_ID = ${safeSidecarId};
51
+ const VERSION = ${safeVer};
52
+ const GLOBAL_KEY = '__agyGitGraphSidebar';
53
+ const BTN_ATTR = 'data-agy-git-graph-root';
54
+ const TAB_TITLES = ['Git', 'Git Graph'];
55
+
56
+ const prev = globalThis[GLOBAL_KEY];
57
+ if (prev && prev.version === VERSION && prev.sidecarId === SIDECAR_ID) {
58
+ prev.sync?.();
59
+ return;
60
+ }
61
+ try { prev?.dispose?.(); } catch {}
62
+
63
+ let observer = null;
64
+ let syncTimer = 0;
65
+ let busy = false;
66
+
67
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
68
+
69
+ const waitFor = async (selector, timeoutMs = 1500) => {
70
+ const deadline = Date.now() + timeoutMs;
71
+ while (Date.now() < deadline) {
72
+ const el = document.querySelector(selector);
73
+ if (el) return el;
74
+ await sleep(30);
75
+ }
76
+ return null;
77
+ };
78
+
79
+ const isOfficialSidePanelOpen = () =>
80
+ document.querySelector('[data-testid="toggle-aux-sidebar"]')?.getAttribute('aria-expanded') === 'true';
81
+
82
+ const isGitGraphVisible = () =>
83
+ isOfficialSidePanelOpen() &&
84
+ document.querySelector(\`[data-testid="sidecar-iframe-slot"][data-sidecar-id="\${SIDECAR_ID}"]\`)?.getAttribute('data-visible') === 'true';
85
+
86
+ const updateButtonState = () => {
87
+ const btn = document.querySelector(\`[\${BTN_ATTR}="sidebar-btn"]\`);
88
+ if (!btn) return;
89
+ const active = isGitGraphVisible();
90
+ btn.setAttribute('aria-pressed', active ? 'true' : 'false');
91
+ if (active) {
92
+ btn.classList.add('bg-sidebar-muted', 'text-foreground');
93
+ btn.classList.remove('bg-transparent', 'text-secondary-foreground');
94
+ } else {
95
+ btn.classList.remove('bg-sidebar-muted', 'text-foreground');
96
+ btn.classList.add('bg-transparent', 'text-secondary-foreground');
97
+ }
98
+ };
99
+
100
+ const findExistingTabButton = () => {
101
+ for (const tab of document.querySelectorAll('.agy-aux-tab')) {
102
+ const text = tab.textContent?.trim() || '';
103
+ if (TAB_TITLES.includes(text)) {
104
+ return tab.querySelector('button');
105
+ }
106
+ }
107
+ return null;
108
+ };
109
+
110
+ const toggleOfficialSidePanel = async () => {
111
+ if (busy) return;
112
+ busy = true;
113
+ try {
114
+ const toggleBtn = document.querySelector('[data-testid="toggle-aux-sidebar"]');
115
+ if (!toggleBtn) return;
116
+
117
+ // If already open and showing Git Graph, collapse the official side panel
118
+ if (isGitGraphVisible()) {
119
+ toggleBtn.click();
120
+ await sleep(80);
121
+ return;
122
+ }
123
+
124
+ // 1. Open the official right-hand side panel if collapsed
125
+ if (!isOfficialSidePanelOpen()) {
126
+ toggleBtn.click();
127
+ await sleep(120);
128
+ }
129
+
130
+ // 2. If the tab is already open in the official tab bar, switch to it
131
+ const existingTabBtn = findExistingTabButton();
132
+ if (existingTabBtn) {
133
+ existingTabBtn.click();
134
+ await sleep(60);
135
+ return;
136
+ }
137
+
138
+ // 3. Otherwise open it via the official New Tab -> Plugins -> Git Graph menu
139
+ let extTrigger = document.querySelector('[data-testid="new-tab-card-extensions"]');
140
+ if (!extTrigger) {
141
+ const newTabBtn = await waitFor('[data-testid="side-panel-new-tab-button"]', 1000);
142
+ if (newTabBtn) {
143
+ newTabBtn.click();
144
+ extTrigger = await waitFor('[data-testid="new-tab-card-extensions"]', 1000);
145
+ }
146
+ }
147
+ if (!extTrigger) return;
148
+
149
+ extTrigger.dispatchEvent(new PointerEvent('pointerenter', { bubbles: true }));
150
+ extTrigger.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
151
+ extTrigger.click();
152
+
153
+ const submenuItem = await waitFor(
154
+ \`[data-testid="plugins-submenu-item"][data-sidecar-id="\${SIDECAR_ID}"]\`,
155
+ 1500
156
+ );
157
+ if (submenuItem) {
158
+ submenuItem.click();
159
+ await sleep(80);
160
+ }
161
+ } finally {
162
+ busy = false;
163
+ updateButtonState();
164
+ }
165
+ };
166
+
167
+ const mountSidebarButton = () => {
168
+ const customizations = document.querySelector('a[href="/customizations"]');
169
+ const navContainer = customizations?.parentElement || document.querySelector('[data-testid="sidebar-navigation-items"]');
170
+ if (!navContainer) return;
171
+
172
+ const codexMount = navContainer.querySelector('[data-agy-codex-sync-root="sidebar-btn"]');
173
+ const powertoolsMount = navContainer.querySelector('[data-agy-powertools-root="management"]');
174
+ const anchor = codexMount || powertoolsMount || customizations;
175
+
176
+ let btn = navContainer.querySelector(\`[\${BTN_ATTR}="sidebar-btn"]\`);
177
+ if (!btn) {
178
+ btn = document.createElement('button');
179
+ btn.type = 'button';
180
+ btn.setAttribute(BTN_ATTR, 'sidebar-btn');
181
+ btn.className = 'agy-button agy-button-custom inline-flex items-center font-medium transition-colors select-none outline-none cursor-pointer disabled:opacity-50 flex-grow w-full justify-start select-none font-normal min-w-0 gap-1.5 px-2 rounded-lg py-1.5 bg-transparent text-secondary-foreground hover:bg-sidebar-muted hover:text-foreground';
182
+ btn.title = '打开/收起官方右侧栏「Git Graph」';
183
+ btn.innerHTML = '<span class="shrink-0 flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="7" r="2.5"/><path d="M6 8.5v7"/><path d="M18 9.5c0 4-12 2.5-12 6"/></svg></span><span class="truncate">Git Graph</span>';
184
+ btn.addEventListener('click', () => { void toggleOfficialSidePanel(); });
185
+ }
186
+
187
+ const expectedNext = anchor ? anchor.nextSibling : null;
188
+ if (btn.parentElement !== navContainer || (anchor && btn.previousSibling !== anchor)) {
189
+ navContainer.insertBefore(btn, expectedNext);
190
+ }
191
+ updateButtonState();
192
+ };
193
+
194
+ const scheduleSync = () => {
195
+ if (syncTimer) return;
196
+ syncTimer = setTimeout(() => {
197
+ syncTimer = 0;
198
+ mountSidebarButton();
199
+ }, 80);
200
+ };
201
+
202
+ observer = new MutationObserver(scheduleSync);
203
+ observer.observe(document.documentElement, {
204
+ childList: true,
205
+ subtree: true,
206
+ attributes: true,
207
+ attributeFilter: ['aria-expanded', 'data-visible'],
208
+ });
209
+ mountSidebarButton();
210
+
211
+ globalThis[GLOBAL_KEY] = {
212
+ version: VERSION,
213
+ sidecarId: SIDECAR_ID,
214
+ sync: mountSidebarButton,
215
+ toggle: toggleOfficialSidePanel,
216
+ dispose: () => {
217
+ clearTimeout(syncTimer);
218
+ observer?.disconnect();
219
+ document.querySelectorAll(\`[\${BTN_ATTR}]\`).forEach((el) => el.remove());
220
+ delete globalThis[GLOBAL_KEY];
221
+ },
222
+ };
223
+ })();`;
224
+ }
225
+
226
+ /**
227
+ * Connect to Antigravity's CDP port and keep the sidebar quick-launch button injected.
228
+ */
229
+ export function startCdpSidebarInjector({ sidecarId = SIDECAR_ID, pollIntervalMs = 3500 } = {}) {
230
+ const attachedTargets = new Set();
231
+ let stopped = false;
232
+
233
+ const evaluateOnTarget = (wsUrl, script) =>
234
+ new Promise((resolve, reject) => {
235
+ const ws = new WebSocket(wsUrl);
236
+ const timer = setTimeout(() => {
237
+ try { ws.close(); } catch {}
238
+ reject(new Error('CDP timeout'));
239
+ }, 6000);
240
+
241
+ ws.addEventListener('open', () => {
242
+ ws.send(JSON.stringify({ id: 1, method: 'Page.addScriptToEvaluateOnNewDocument', params: { source: script } }));
243
+ ws.send(JSON.stringify({ id: 2, method: 'Runtime.evaluate', params: { expression: script } }));
244
+ });
245
+ ws.addEventListener('message', (ev) => {
246
+ try {
247
+ const msg = JSON.parse(ev.data);
248
+ if (msg.id === 2) {
249
+ clearTimeout(timer);
250
+ try { ws.close(); } catch {}
251
+ resolve();
252
+ }
253
+ } catch {}
254
+ });
255
+ ws.addEventListener('error', () => {
256
+ clearTimeout(timer);
257
+ reject(new Error('CDP ws error'));
258
+ });
259
+ });
260
+
261
+ const tick = async () => {
262
+ if (stopped) return;
263
+ const port = readCdpPort();
264
+ if (!port) return;
265
+
266
+ try {
267
+ const res = await fetch(`http://127.0.0.1:${port}/json`, { signal: AbortSignal.timeout(2000) });
268
+ if (!res.ok) return;
269
+ const targets = await res.json();
270
+ const pages = targets.filter(
271
+ (t) =>
272
+ t?.type === 'page' &&
273
+ t?.webSocketDebuggerUrl &&
274
+ typeof t.url === 'string' &&
275
+ (t.url.startsWith('https://127.0.0.1:') || t.url.startsWith('http://127.0.0.1:'))
276
+ );
277
+
278
+ const activeIds = new Set(pages.map((p) => p.id));
279
+ for (const oldId of attachedTargets) {
280
+ if (!activeIds.has(oldId)) attachedTargets.delete(oldId);
281
+ }
282
+
283
+ const script = buildSidebarInjectionScript({ sidecarId });
284
+ for (const page of pages) {
285
+ if (attachedTargets.has(page.id)) continue;
286
+ try {
287
+ await evaluateOnTarget(page.webSocketDebuggerUrl, script);
288
+ attachedTargets.add(page.id);
289
+ } catch {
290
+ // Retry on next poll
291
+ }
292
+ }
293
+ } catch {
294
+ // CDP port not ready yet
295
+ }
296
+ };
297
+
298
+ const interval = setInterval(tick, pollIntervalMs);
299
+ interval.unref?.();
300
+ void tick();
301
+
302
+ return () => {
303
+ stopped = true;
304
+ clearInterval(interval);
305
+ };
306
+ }
@@ -30,12 +30,7 @@ export function powertoolsFontCss() {
30
30
  }
31
31
  }
32
32
 
33
- export function renderIndexHtml({ mcpBridgeScript = '' } = {}) {
34
- let html = readFileSync(new URL('../index.html', import.meta.url), 'utf8')
33
+ export function renderIndexHtml() {
34
+ return readFileSync(new URL('../index.html', import.meta.url), 'utf8')
35
35
  .replace('/*__POWERTOOLS_FONT_CSS__*/', () => powertoolsFontCss());
36
- if (mcpBridgeScript) {
37
- const safeScript = mcpBridgeScript.replace(/<\/script/gi, '<\\/script');
38
- html = html.replace('<!--__MCP_APP_BRIDGE__-->', () => `<script>\n${safeScript}\n</script>`);
39
- }
40
- return html;
41
36
  }
@@ -1,5 +1,5 @@
1
- import { readFileSync } from 'node:fs';
2
1
  import { createServer } from 'node:http';
2
+ import { startCdpSidebarInjector } from './lib/cdp-sidebar.mjs';
3
3
  import { InputError } from './lib/git.mjs';
4
4
  import { createHandlers } from './lib/handlers.mjs';
5
5
  import { renderIndexHtml } from './lib/render.mjs';
@@ -102,5 +102,6 @@ if (process.argv.includes('--standalone')) {
102
102
  const app = new SidecarApp();
103
103
  app.page('/', () => renderHtml());
104
104
  for (const [route, handler] of Object.entries(handlers)) app.api(route, handler);
105
+ startCdpSidebarInjector();
105
106
  app.run();
106
107
  }