@wengine-ai/ccr-provider-gemini-agy-acp 0.0.2 → 0.2.1

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/dist/src/card.mjs CHANGED
@@ -1,6 +1,18 @@
1
- // Read-only management card: a self-contained ES chunk with no imports and no
2
- // network access. It only explains the local opt-in contract; the operator's
3
- // sidecar file and environment remain the single source of truth.
1
+ // Management card for the local ACP bridge. It renders inside the host
2
+ // settings page, so the host's global stylesheet (Tailwind utilities + the
3
+ // custom .glass-card rule) is part of its runtime environment; class names
4
+ // mirror the gemini-oauth / codex card conventions. Import-free,
5
+ // network-free, and all rendered strings go through textContent, never
6
+ // markup assignment. All traffic rides props.callApi, the host's
7
+ // authenticated, sanitized admin bridge (never the raw browser API).
8
+ const BADGE_BASE = 'inline-flex items-center rounded-lg border px-2.5 py-0.5 text-[10px] font-bold transition-colors';
9
+ const BADGE_OUTLINE = 'border-white/10 text-foreground bg-white/5';
10
+ const BADGE_SECONDARY = 'border-white/5 bg-white/5 text-muted-foreground';
11
+ const BUTTON_BASE = 'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-xl border px-3 py-1.5 text-xs font-semibold shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50';
12
+ const BUTTON_OUTLINE = 'border-input bg-input/50 hover:bg-input/80 hover:border-primary/50';
13
+ const BUTTON_DESTRUCTIVE = 'border-destructive/50 text-destructive hover:bg-destructive hover:text-destructive-foreground';
14
+ const INPUT_CLASS = 'max-w-md flex h-9 w-full rounded-lg border border-input bg-input/50 px-3 py-1 text-sm shadow-sm placeholder:text-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
15
+
4
16
  const el = (tag, className, text) => {
5
17
  const node = document.createElement(tag);
6
18
  if (className) node.className = className;
@@ -8,61 +20,375 @@ const el = (tag, className, text) => {
8
20
  return node;
9
21
  };
10
22
 
23
+ // Stable route-error codes → one-line localized recovery hints. Unknown codes
24
+ // fall back to the sanitized token itself (never an upstream message).
25
+ const CODE_HINTS = {
26
+ acp_unsupported_version: ['需要 agy 1.5.1 或更新版本。', 'agy 1.5.1 or later is required.'],
27
+ acp_invalid_config: ['请检查 binary 路径:必须指向本机存在的可执行文件。', 'Check the binary path: it must point to an executable on this machine.'],
28
+ acp_auth_required: ['缺少可用的 Gemini API key。', 'No usable Gemini API key is configured.'],
29
+ acp_timeout: ['agy 未在时限内响应。', 'agy did not respond in time.'],
30
+ acp_busy: ['worker 池已满,请稍后重试。', 'Worker pool is busy, try again shortly.'],
31
+ acp_worker_failed: ['agy 进程异常退出。', 'The agy process failed.'],
32
+ acp_protocol_error: ['agy 返回了无法解析的协议响应。', 'agy returned an unparseable protocol response.'],
33
+ acp_output_limit: ['agy 输出超出限制。', 'agy output exceeded the limit.'],
34
+ acp_unsupported_option: ['该 CLI 未公开可选模型。', 'This CLI exposes no selectable model options.'],
35
+ agy_disabled: ['尚未启用,请先连接。', 'Not enabled yet — connect first.'],
36
+ agy_config_invalid: ['gemini-agy-acp.json 无效,可在 CCR 配置目录删除后重试。', 'gemini-agy-acp.json is invalid — delete it in the CCR config directory and retry.'],
37
+ agy_config_write_failed: ['写入配置文件失败。', 'Writing the configuration file failed.'],
38
+ agy_unauthorized: ['仅限本机访问。', 'Local access only.'],
39
+ agy_route_failed: ['管理请求失败,请重试。', 'The management request failed, please retry.'],
40
+ agy_install_unsupported_platform: ['当前系统/架构没有官方 agy 构建。', 'No official agy build exists for this OS/architecture.'],
41
+ agy_install_manifest_failed: ['无法访问 agy 发布服务器,请检查网络或代理。', 'Cannot reach the agy release server — check the network or proxy.'],
42
+ agy_install_manifest_invalid: ['agy 发布清单无效。', 'The agy release manifest is invalid.'],
43
+ agy_install_download_failed: ['下载 agy 失败,请检查网络或代理后重试。', 'Downloading agy failed — check the network or proxy and retry.'],
44
+ agy_install_too_large: ['agy 下载体积超出限制。', 'The agy download exceeded the size limit.'],
45
+ agy_install_checksum_mismatch: ['agy 校验失败,已中止安装。', 'The agy checksum failed; installation was aborted.'],
46
+ agy_install_extract_failed: ['解压 agy 失败。', 'Extracting agy failed.'],
47
+ agy_install_write_failed: ['写入 agy 失败,请检查目录权限。', 'Writing agy failed — check directory permissions.'],
48
+ };
49
+
11
50
  export default {
12
- mount(target, props) {
51
+ async mount(target, props) {
13
52
  const zh = props.locale === 'zh';
14
- const t = (en, cn) => (zh ? cn : en);
15
- const root = el('div', 'ccr-agy-acp-card');
16
- const style = root.style;
17
- style.font = '13px/1.6 -apple-system, "Segoe UI", sans-serif';
18
- style.color = 'inherit';
19
-
20
- const head = el('div', null, null);
21
- head.style.display = 'flex';
22
- head.style.alignItems = 'center';
23
- head.style.gap = '8px';
24
- const title = el('strong', null, t('Local Antigravity CLI (ACP) bridge', '本地 Antigravity CLI(ACP)桥'));
25
- const badge = el('span', null, props.disabled ? t('Disabled', '未启用') : t('Enabled', '已启用'));
26
- badge.style.padding = '1px 8px';
27
- badge.style.borderRadius = '999px';
28
- badge.style.fontSize = '12px';
29
- badge.style.border = '1px solid currentColor';
30
- if (!props.disabled) badge.style.opacity = '0.85'; else badge.style.opacity = '0.6';
31
- head.append(title, badge);
32
- root.append(head);
33
-
34
- if (props.plugin?.version) root.append(el('div', null, t('Version', '版本') + ': v' + props.plugin.version));
35
-
36
- for (const line of props.disabled ? [
37
- t('This prototype is off until the operator enables it. In the CCR config directory create gemini-agy-acp.json:',
38
- '原型在运维者显式启用前保持关闭。请在 CCR 配置目录创建 gemini-agy-acp.json:'),
39
- ] : [
40
- t('Workers start only for requests routed to this provider; API-key quotas and charges apply.',
41
- '仅路由到本供应商的请求会启动 worker;调用计入 API key 配额与费用。'),
42
- t('Rotate the key by updating the environment and restarting the isolated CCR host.',
43
- '更换密钥需更新环境变量并重启隔离的 CCR 实例。'),
44
- ]) root.append(el('p', null, line));
45
-
46
- const code = el('pre', null, JSON.stringify({
47
- enabled: true, binary: '/absolute/path/to/agy', authMethod: 'gemini-api-key', maxWorkers: 1, timeoutMs: 60000,
48
- }, null, 2));
49
- code.style.background = 'rgba(127,127,127,.12)';
50
- code.style.padding = '8px 10px';
51
- code.style.borderRadius = '6px';
52
- code.style.overflowX = 'auto';
53
- code.style.whiteSpace = 'pre-wrap';
54
- root.append(code);
55
-
56
- root.append(el('p', null, t(
57
- 'Set GEMINI_API_KEY in the CCR process environment and route a primary model to gemini-agy-acp. Consumer OAuth and subscriptions are unsupported.',
58
- '在 CCR 进程环境设置 GEMINI_API_KEY,并把主路由模型指向 gemini-agy-acp。不支持个人订阅与浏览器 OAuth。')));
59
-
60
- target.append(root);
61
- this._root = root;
53
+ const t = (cn, en) => (zh ? cn : en);
54
+ const call = typeof props.callApi === 'function' ? props.callApi : null;
55
+
56
+ const card = el('div', 'glass-card rounded-2xl overflow-hidden mb-4');
57
+ const layout = el('div', 'flex flex-col gap-4 p-5');
58
+ const body = el('div', 'min-w-0 flex-1 space-y-3');
59
+
60
+ const header = el('div', 'flex flex-wrap items-center gap-2');
61
+ header.append(
62
+ el('p', 'text-lg font-bold tracking-tight text-foreground', t('本地 Antigravity CLI(ACP)桥', 'Local Antigravity CLI (ACP) bridge')),
63
+ el('span', BADGE_BASE + ' ' + BADGE_OUTLINE + ' border-amber-500/40 text-amber-600', t('实验原型', 'Experimental')),
64
+ el('span', BADGE_BASE + ' ' + BADGE_SECONDARY, 'API key'),
65
+ );
66
+ body.append(header);
67
+
68
+ body.append(el('p', 'max-w-md truncate text-xs font-medium text-muted-foreground/60', props.plugin?.version ? 'v' + props.plugin.version : ''));
69
+ body.append(el('p', 'max-w-md text-xs text-muted-foreground',
70
+ t('通过官方 agy 二进制以 ACP stdio 提供纯文本对话,走 Gemini API key 配额或已登录的 Google 账号。',
71
+ 'Text-only chat through the official agy binary over ACP stdio, billed to the Gemini API key or the signed-in Google account.')));
72
+
73
+ const statusLine = el('p', 'max-w-md text-xs font-medium text-muted-foreground', '');
74
+ body.append(statusLine);
75
+ // Synced model list (collapsed by default) and credential fingerprint.
76
+ const modelsBox = el('details', 'max-w-md text-xs text-muted-foreground');
77
+ modelsBox.append(el('summary', null, t('模型列表', 'Model list')));
78
+ const modelsList = el('ul', 'list-disc pl-5');
79
+ modelsBox.append(modelsList);
80
+ const restoreAll = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE + ' mt-1 px-2 py-0.5 text-[10px]',
81
+ t('恢复全部', 'Restore all'));
82
+ restoreAll.type = 'button';
83
+ restoreAll.hidden = true;
84
+ modelsBox.append(restoreAll);
85
+ modelsBox.hidden = true;
86
+ body.append(modelsBox);
87
+
88
+ const binaryInput = el('input', INPUT_CLASS);
89
+ binaryInput.type = 'text';
90
+ binaryInput.placeholder = t('/绝对路径/to/agy', '/absolute/path/to/agy');
91
+ const keyInput = el('input', INPUT_CLASS);
92
+ keyInput.type = 'password';
93
+ keyInput.placeholder = t('Gemini API key(可选,留空沿用现有密钥或环境变量)',
94
+ 'Gemini API key (optional; leave empty to keep the stored key or environment variable)');
95
+ keyInput.setAttribute('autocomplete', 'new-password');
96
+ keyInput.value = ''; // the stored apiKey is never rendered back into the form
97
+ // 登录方式 segmented toggle: the choice persists per connect call as the
98
+ // sidecar's authMethod (reported back by /status). Google-account mode
99
+ // hides the key input entirely — its credential is the CLI's own browser
100
+ // login, verified by connect through one real ACP handshake. The account
101
+ // email is shown only when that handshake explicitly provided one;
102
+ // otherwise the explicit 账号邮箱未提供 placeholder is shown.
103
+ let authMode = 'gemini-api-key';
104
+ const OAUTH_LOGIN_HINT = ['请先在终端运行一次 agy 完成浏览器登录', 'Run agy once in a terminal to complete the browser sign-in first'];
105
+ const authToggle = el('div', 'flex max-w-md items-center gap-2');
106
+ const keyModeButton = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('API key', 'API key'));
107
+ const oauthModeButton = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('Google 账号', 'Google account'));
108
+ keyModeButton.type = oauthModeButton.type = 'button';
109
+ authToggle.append(keyModeButton, oauthModeButton);
110
+ const accountLine = el('p', 'max-w-md truncate text-xs font-semibold text-foreground', '');
111
+ const form = el('div', 'max-w-md space-y-2');
112
+ form.append(binaryInput, keyInput);
113
+ body.append(authToggle, accountLine, form);
114
+
115
+ const renderAuthMode = () => {
116
+ const oauth = authMode === 'oauth-personal';
117
+ keyInput.hidden = oauth;
118
+ accountLine.hidden = !oauth || !accountLine.textContent;
119
+ keyModeButton.className = BUTTON_BASE + ' ' + BUTTON_OUTLINE + (oauth ? ' opacity-60' : ' border-primary/60 bg-input/80');
120
+ oauthModeButton.className = BUTTON_BASE + ' ' + BUTTON_OUTLINE + (oauth ? ' border-primary/60 bg-input/80' : ' opacity-60');
121
+ keyModeButton.setAttribute('aria-pressed', String(!oauth));
122
+ oauthModeButton.setAttribute('aria-pressed', String(oauth));
123
+ };
124
+ keyModeButton.onclick = () => { authMode = 'gemini-api-key'; renderAuthMode(); };
125
+ oauthModeButton.onclick = () => { authMode = 'oauth-personal'; renderAuthMode(); };
126
+
127
+ const statusText = status => {
128
+ if (status?.installing) {
129
+ return t('正在自动安装 agy(官方发布,SHA-512 校验)…', 'Installing agy automatically (official release, SHA-512 verified)…');
130
+ }
131
+ if (!status || status.enabled !== true) {
132
+ return t('未启用 — 填写 binary 后按连接', 'Not enabled — fill in the binary path and press Connect');
133
+ }
134
+ const parts = [status.loaded ? t('已连接', 'Connected') : t('已启用,等待首个请求', 'Enabled, waiting for the first request')];
135
+ if (status.binaryFound === false) parts.push(t('binary 未找到', 'binary not found'));
136
+ else if (status.version) parts.push(`agy ${status.version}`);
137
+ if (Array.isArray(status.models) && status.models.length) {
138
+ // The count stays the TOTAL catalog size; hidden ones are extra info.
139
+ const hiddenCount = Array.isArray(status.hiddenModels) ? status.hiddenModels.length : 0;
140
+ parts.push(t(`${status.models.length} 个模型`, `${status.models.length} models`) +
141
+ (hiddenCount > 0 ? t(`(已隐藏 ${hiddenCount})`, ` (${hiddenCount} hidden)`) : ''));
142
+ } else if (typeof status.modelsSyncedAt === 'number') {
143
+ parts.push(t('0 个模型', '0 models'));
144
+ }
145
+ // Credential line: oauth pools report the handshake-verified account
146
+ // (or the explicit not-provided placeholder); API-key pools keep the
147
+ // fingerprint line.
148
+ if (status?.authMethod === 'oauth-personal') {
149
+ parts.push(status.accountEmail
150
+ ? t(`账号 ${status.accountEmail}`, `account ${status.accountEmail}`)
151
+ : t('账号邮箱未提供', 'account email not provided'));
152
+ } else if (status.apiKeyFingerprint) {
153
+ parts.push(t(`AI Studio key 凭据 ${status.apiKeyFingerprint}…`, `AI Studio key credential ${status.apiKeyFingerprint}…`));
154
+ } else if (status.apiKeyConfigured !== true) parts.push(t('缺少 API key', 'no API key'));
155
+ if (status.lastError?.code) parts.push(t(`上次错误 ${status.lastError.code}`, `last error ${status.lastError.code}`));
156
+ return parts.join(' · ');
157
+ };
158
+
159
+ const message = el('p', 'max-w-md text-xs text-destructive', '');
160
+ const notice = el('p', 'max-w-md text-xs font-medium text-emerald-600', '');
161
+ const setMessage = text => { message.textContent = text || ''; };
162
+ const setNotice = text => { notice.textContent = text || ''; };
163
+ const errorText = error => {
164
+ const code = error?.reason ?? error?.code;
165
+ // OAuth login failures surface the terminal sign-in hint instead of the
166
+ // API-key hint; every other code keeps its static mapping.
167
+ if (code === 'acp_auth_required' && authMode === 'oauth-personal') return t(OAUTH_LOGIN_HINT[0], OAUTH_LOGIN_HINT[1]);
168
+ const hint = typeof code === 'string' ? CODE_HINTS[code] : null;
169
+ if (hint) return t(hint[0], hint[1]);
170
+ return typeof code === 'string' ? `${t('操作失败', 'The action failed')} (${code})` : t('操作失败', 'The action failed');
171
+ };
172
+
173
+ const connect = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('连接', 'Connect'));
174
+ const sync = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('同步模型', 'Sync models'));
175
+ const disconnect = el('button', BUTTON_BASE + ' ' + BUTTON_DESTRUCTIVE, t('断开', 'Disconnect'));
176
+ // Manual install / retry: shown only while no agy is detected anywhere or
177
+ // the last auto-install failed. The first card view auto-starts it.
178
+ const install = el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE, t('安装 agy', 'Install agy'));
179
+ install.hidden = true;
180
+ for (const button of [connect, sync, disconnect, install]) button.type = 'button';
181
+ const controls = [connect, sync, disconnect, install];
182
+ const buttons = el('div', 'flex flex-wrap items-center gap-2');
183
+ buttons.append(connect, sync, disconnect, install);
184
+ body.append(buttons, notice, message);
185
+
186
+ let busyDepth = 0;
187
+ let latestStatus = null;
188
+ let installingNow = false;
189
+ let wasInstalling = false;
190
+ let pollTimer = null;
191
+ const BUSY_LABELS = new Map([[connect, t('连接中…', 'Connecting…')], [sync, t('同步中…', 'Syncing…')], [disconnect, t('断开中…', 'Disconnecting…')], [install, t('安装中…', 'Installing…')]]);
192
+ // Per-model visibility controls live inside the freshly rendered list;
193
+ // setBusy keeps them disabled together with the three fixed actions and
194
+ // the auth-mode toggle.
195
+ let rowButtons = [];
196
+ let currentHiddenIds = [];
197
+ const applyDisabled = () => {
198
+ const busy = busyDepth > 0;
199
+ for (const button of [...controls, ...rowButtons, restoreAll, keyModeButton, oauthModeButton]) {
200
+ // A running background install locks the actions too: connecting a
201
+ // half-downloaded binary must not be possible from the card.
202
+ button.disabled = busy || !call || installingNow;
203
+ const busyLabel = BUSY_LABELS.get(button);
204
+ if (busy && busyLabel) button.textContent = busyLabel;
205
+ }
206
+ if (!busy) {
207
+ connect.textContent = t('连接', 'Connect');
208
+ sync.textContent = t('同步模型', 'Sync models');
209
+ disconnect.textContent = t('断开', 'Disconnect');
210
+ install.textContent = installingNow ? t('安装中…', 'Installing…') : t('安装 agy', 'Install agy');
211
+ }
212
+ };
213
+ const setBusy = active => {
214
+ busyDepth = Math.max(0, busyDepth + (active ? 1 : -1));
215
+ applyDisabled();
216
+ props.onBusy?.(busyDepth > 0);
217
+ };
218
+
219
+ const renderStatus = status => {
220
+ latestStatus = status;
221
+ installingNow = Boolean(status?.installing);
222
+ // Poll while the background download runs; surface the outcome once it
223
+ // finishes (success prefills the detected binary, failure shows the hint).
224
+ if (installingNow && !pollTimer && !target.__agyDisposed) {
225
+ pollTimer = setInterval(() => { void refresh(); }, 3000);
226
+ target.__agyPollTimer = pollTimer;
227
+ } else if (!installingNow && pollTimer) {
228
+ clearInterval(pollTimer);
229
+ pollTimer = null;
230
+ target.__agyPollTimer = null;
231
+ }
232
+ // A detected binary supersedes any stale install failure: the operator
233
+ // may have installed agy manually after a failed auto-install.
234
+ const binaryPresent = Boolean(status?.binary || status?.detectedBinary);
235
+ if (wasInstalling && !installingNow) {
236
+ if (status?.detectedBinary) setNotice(t('agy 已安装,可直接连接', 'agy installed — press Connect'));
237
+ else if (status?.installError && !binaryPresent) setMessage(errorText({ code: status.installError.code }));
238
+ }
239
+ wasInstalling = installingNow;
240
+ install.hidden = binaryPresent;
241
+ if (status?.installError && !installingNow && !binaryPresent) setMessage(errorText({ code: status.installError.code }));
242
+ statusLine.textContent = statusText(status);
243
+ // ACP key auth exposes no account email; the fingerprint lets the
244
+ // operator match WHICH key is connected without revealing it.
245
+ statusLine.title = status?.apiKeyFingerprint
246
+ ? t('凭据指纹 = Gemini API key 的 SHA-256 前 10 位', 'credential fingerprint = first 10 hex of the Gemini API key SHA-256')
247
+ : '';
248
+ const modelEntries = Array.isArray(status?.models) ? status.models : [];
249
+ currentHiddenIds = Array.isArray(status?.hiddenModels) ? status.hiddenModels.filter(id =>
250
+ typeof id === 'string' && modelEntries.some(model => model?.id === id)) : [];
251
+ const hiddenSet = new Set(currentHiddenIds);
252
+ rowButtons = [];
253
+ const busy = busyDepth > 0;
254
+ modelsList.replaceChildren(...modelEntries.map(model => {
255
+ const id = model?.id ?? '';
256
+ const isHidden = hiddenSet.has(id);
257
+ const li = el('li', isHidden ? 'text-muted-foreground/50' : null,
258
+ (typeof model?.name === 'string' && model.name ? model.name + ' · ' : '') + id +
259
+ (isHidden ? t(' 已隐藏', ' hidden') : ''));
260
+ const toggle = isHidden
261
+ ? el('button', BUTTON_BASE + ' ' + BUTTON_OUTLINE + ' ml-2 px-2 py-0.5 text-[10px]', t('恢复', 'Restore'))
262
+ : el('button', 'ml-1 inline-flex items-center align-middle rounded p-0.5 text-muted-foreground/60 transition-colors hover:bg-white/10 hover:text-foreground focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-40');
263
+ if (!isHidden) {
264
+ const ns = 'http://www.w3.org/2000/svg';
265
+ const icon = document.createElementNS(ns, 'svg');
266
+ icon.setAttribute('viewBox', '0 0 24 24');
267
+ icon.setAttribute('width', '12');
268
+ icon.setAttribute('height', '12');
269
+ icon.setAttribute('fill', 'none');
270
+ icon.setAttribute('stroke', 'currentColor');
271
+ icon.setAttribute('stroke-width', '2');
272
+ icon.setAttribute('stroke-linecap', 'round');
273
+ icon.setAttribute('aria-hidden', 'true');
274
+ const path = document.createElementNS(ns, 'path');
275
+ path.setAttribute('d', 'M18 6 6 18 M6 6l12 12');
276
+ icon.append(path);
277
+ toggle.append(icon);
278
+ toggle.title = t('隐藏模型 ' + id, 'Hide model ' + id);
279
+ toggle.setAttribute('aria-label', toggle.title);
280
+ }
281
+ toggle.type = 'button';
282
+ toggle.disabled = busy || !call || installingNow;
283
+ toggle.onclick = () => runAction('/models/visibility', isHidden ? { restore: [id] } : { hide: [id] });
284
+ rowButtons.push(toggle);
285
+ li.append(toggle);
286
+ return li;
287
+ }));
288
+ restoreAll.hidden = modelEntries.length === 0 || currentHiddenIds.length === 0;
289
+ restoreAll.disabled = busy || !call || installingNow;
290
+ restoreAll.onclick = () => runAction('/models/visibility', { restore: [...currentHiddenIds] });
291
+ modelsBox.hidden = modelEntries.length === 0;
292
+ // The persisted auth method wins after every status refresh (it is what
293
+ // the last connect call stored), then the account line re-renders.
294
+ if (status?.authMethod === 'oauth-personal' || status?.authMethod === 'gemini-api-key') authMode = status.authMethod;
295
+ accountLine.textContent = status?.accountEmail ? t('账号:', 'Account: ') + status.accountEmail
296
+ : status?.authMethod === 'oauth-personal' ? t('账号邮箱未提供', 'account email not provided') : '';
297
+ renderAuthMode();
298
+ // Prefill only the binary path (an operator setting, not a secret) —
299
+ // the sidecar's configured path, or an agy detected at the official
300
+ // default location; the key input is never populated from stored state.
301
+ const prefill = typeof status?.binary === 'string' ? status.binary
302
+ : typeof status?.detectedBinary === 'string' ? status.detectedBinary : null;
303
+ if (!binaryInput.value && prefill) binaryInput.value = prefill;
304
+ // Re-apply the lock AFTER the row buttons are rebuilt so a running
305
+ // install disables the freshly created visibility toggles too.
306
+ applyDisabled();
307
+ };
308
+
309
+ const refresh = async () => {
310
+ if (target.__agyDisposed) return;
311
+ if (!call) {
312
+ renderStatus(null);
313
+ return;
314
+ }
315
+ try {
316
+ renderStatus(await call('/status', { timeoutMs: 15000 }));
317
+ } catch (error) {
318
+ setMessage(errorText(error));
319
+ }
320
+ };
321
+
322
+ const runAction = async (path, requestBody, onDone) => {
323
+ if (!call || busyDepth > 0) return;
324
+ setMessage('');
325
+ setNotice('');
326
+ setBusy(true);
327
+ try {
328
+ const response = await call(path, {
329
+ method: 'POST',
330
+ body: JSON.stringify(requestBody ?? {}),
331
+ timeoutMs: 30000,
332
+ });
333
+ const doneNotice = onDone?.(response);
334
+ await refresh();
335
+ // Explicit confirmation: these actions are idempotent, so without a
336
+ // success notice a repeated click looks like it did nothing.
337
+ const done = new Date();
338
+ const at = `${String(done.getHours()).padStart(2, '0')}:${String(done.getMinutes()).padStart(2, '0')}:${String(done.getSeconds()).padStart(2, '0')}`;
339
+ setNotice(`${doneNotice ?? t('已完成', 'Done')} · ${at}`);
340
+ } catch (error) {
341
+ setMessage(errorText(error));
342
+ } finally {
343
+ setBusy(false);
344
+ }
345
+ };
346
+
347
+ connect.onclick = () => runAction('/connect', {
348
+ ...(binaryInput.value.trim() ? { binary: binaryInput.value.trim() } : {}),
349
+ authMethod: authMode,
350
+ // The API key only ever travels in gemini-api-key mode; oauth-personal
351
+ // mode never sends credential material.
352
+ ...(authMode === 'gemini-api-key' && keyInput.value ? { apiKey: keyInput.value } : {}),
353
+ }, response => {
354
+ keyInput.value = ''; // never keep the typed key in the DOM
355
+ return t(`已连接(agy ${response?.version ?? ''})`, `Connected (agy ${response?.version ?? ''})`);
356
+ });
357
+ sync.onclick = () => runAction('/models/sync', {}, response =>
358
+ t(`已同步 ${response?.models?.length ?? 0} 个模型`, `Synced ${response?.models?.length ?? 0} models`));
359
+ disconnect.onclick = () => runAction('/disconnect', {}, () => t('已断开', 'Disconnected'));
360
+ install.onclick = () => runAction('/install', {}, () => t('已开始安装 agy', 'agy install started'));
361
+ setBusy(false);
362
+
363
+ const section = el('details', 'max-w-md text-xs text-muted-foreground');
364
+ section.append(el('summary', 'cursor-pointer select-none font-medium', t('配置说明', 'Setup instructions')));
365
+ section.append(el('p', 'mt-2 text-xs text-muted-foreground',
366
+ t('在上方填入 agy 的绝对路径(可选 API key)并按连接,写入 CCR 配置目录的 gemini-agy-acp.json(API key 以 0600 权限保存);断开仅停用,不删除配置。',
367
+ 'Enter the absolute agy path above (optionally an API key) and press Connect. This writes gemini-agy-acp.json in the CCR config directory (the API key is stored with 0600 permissions); Disconnect only disables, it does not delete settings.')));
368
+ section.append(el('p', 'max-w-md text-[11px] text-muted-foreground/60',
369
+ t('Google 账号模式需先在终端运行一次 agy 完成浏览器登录;连接时通过一次真实 ACP 握手验证登录状态,账号邮箱仅在本次握手明确提供时显示。请为主路由配置 enableFallback: false 的隔离实例。',
370
+ 'Google account mode requires running agy once in a terminal to complete the browser sign-in first; Connect verifies the login with one real ACP handshake. The account email is shown only when that handshake explicitly provides it. Run it as a primary route on an isolated instance with enableFallback: false.')));
371
+
372
+ body.append(section);
373
+ layout.append(body);
374
+ card.append(layout);
375
+ target.append(card);
376
+
377
+ await refresh();
378
+ // First view with no agy anywhere: start the official install right away.
379
+ // A previous failure is never retried automatically — the Install button
380
+ // is the explicit retry, so a broken network cannot loop downloads.
381
+ const first = latestStatus;
382
+ if (call && first && !first.binary && !first.detectedBinary && !first.installing && !first.installError) {
383
+ await runAction('/install', {}, () => t('已开始自动安装 agy', 'Automatic agy install started'));
384
+ }
62
385
  },
63
386
  unmount(el) {
64
- this._root?.remove();
65
- this._root = null;
387
+ el.__agyDisposed = true;
388
+ if (el.__agyPollTimer) {
389
+ clearInterval(el.__agyPollTimer);
390
+ el.__agyPollTimer = null;
391
+ }
66
392
  el.replaceChildren();
67
393
  },
68
394
  };