diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index 2a474a2c97c..ef134650e85 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -756,8 +756,14 @@ Usa `--model` solo con `ocx connect antigravity` para fijar el modelo predetermi Conectar registra lo que reemplazó. Desconectar restaura los bytes originales cuando el archivo no ha cambiado y, en caso contrario, revierte solo las entradas propias de OpenCodex y conserva tus otras -ediciones. El bloque marcado de `agy` en un perfil de shell se elimina entero, incluida cualquier edición -hecha dentro de él. Un enlace simbólico de un perfil de `agy` debe apuntar a otro perfil compatible +ediciones. Antigravity puede restaurar la configuración aunque se reordenen las claves JSON y conserva +el archivo y el registro de restauración si hay un conflicto con un ajuste gestionado. +Para resolver un conflicto de Antigravity, repón el valor que aplicó OpenCodex y vuelve a intentarlo. +Si OpenCodex muestra `agy-profile-restore-required`, abre el perfil de shell indicado en el error. +Recupera de una copia el bloque completo de `agy`, incluidas las dos líneas de marcador y la función +entre ellas, y vuelve a intentar la desconexión o la desinstalación. OpenCodex elimina el bloque entero +y conserva los cambios que quedan fuera. También puedes restaurar el perfil original guardado, lo que +reemplaza las ediciones posteriores. Un enlace simbólico de un perfil de `agy` debe apuntar a otro perfil compatible de la misma familia de shells dentro de tu directorio personal. El archivo de configuración de Antigravity debe resolverse a la ruta exacta `~/.antigravity/settings.json`. Reinicia Antigravity, o abre una terminal nueva para `agy`, para aplicar un cambio. Al desconectar, `agy` omite los perfiles diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index 08a5df5ae9e..abdcdeefe61 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1245,8 +1245,13 @@ ocx disconnect antigravity # or: ocx disconnect agy Use `--model` only with `ocx connect antigravity` to set the desktop app's default model. Connect records what it replaced. Disconnect puts the original bytes back when the file is unchanged, and -otherwise reverts only OpenCodex's own entries and keeps your other edits. The marked `agy` block in a -shell profile is removed whole, including any edit made inside it. An `agy` profile symlink must resolve +otherwise reverts only OpenCodex's own entries and keeps your other edits. Antigravity can restore +settings after JSON keys are reordered and keeps the file and restore record when a managed setting conflicts. +To resolve an Antigravity conflict, put the managed setting back to the value OpenCodex applied and +retry. If OpenCodex reports `agy-profile-restore-required`, open the shell profile named in the error. +Restore the complete `agy` block from a copy, including both marker lines and the function between +them, then retry disconnect or uninstall. OpenCodex removes the whole block and keeps edits outside +it. You can also restore the saved original profile, which replaces any later edits. An `agy` profile symlink must resolve to another supported profile for the same shell family under your home. Antigravity settings must resolve to the exact `~/.antigravity/settings.json` path. Restart Antigravity, or open a new terminal for `agy`, to apply a change. During disconnect, `agy` skips profiles without a restore record if they cannot be diff --git a/gui/src/i18n/gateway-clients-copy.ts b/gui/src/i18n/gateway-clients-copy.ts index cd6bfb2ecef..40b4880f134 100644 --- a/gui/src/i18n/gateway-clients-copy.ts +++ b/gui/src/i18n/gateway-clients-copy.ts @@ -2,7 +2,7 @@ * Copy for the Antigravity and agy connect tab. One row per key, columns in the order of * `locales`, kept apart from the per-locale files like remote-link-diagnostics-copy.ts. The * server sends a code for every note, override and refusal; this table is what the user reads. - * Only file paths and the text of an I/O error are shown as sent. + * File paths and diagnostics without a specific translation can be shown as sent. */ type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; @@ -47,6 +47,19 @@ const rows = { refusedIo: ["Could not write the client files:","클라이언트 파일을 쓰지 못했어요:","Die Clientdateien konnten nicht geschrieben werden:","Impossible d’écrire les fichiers du client :","无法写入客户端文件:","無法寫入用戶端檔案:","Не удалось записать файлы клиента:","クライアントのファイルを書き込めませんでした:","İstemci dosyaları yazılamadı:","Không ghi được các tệp của máy khách:","Não foi possível gravar os arquivos do cliente:"], refused: ["The proxy refused the change:","프록시가 변경을 거부했어요:","Der Proxy hat die Änderung abgelehnt:","Le proxy a refusé la modification :","代理拒绝了此更改:","代理拒絕了此變更:","Прокси отклонил изменение:","プロキシが変更を拒否しました:","Proxy değişikliği reddetti:","Proxy đã từ chối thay đổi:","O proxy recusou a alteração:"], actionFailed: ["Could not confirm whether the change was applied. Check the client status before trying again.","변경이 적용됐는지 확인하지 못했어요. 다시 시도하기 전에 클라이언트 상태를 확인하세요.","Es ließ sich nicht bestätigen, ob die Änderung übernommen wurde. Prüfen Sie den Client-Status, bevor Sie es erneut versuchen.","Impossible de confirmer si la modification a été appliquée. Vérifiez l’état du client avant de réessayer.","无法确认更改是否已生效。请先检查客户端状态再重试。","無法確認變更是否已生效。請先檢查用戶端狀態再重試。","Не удалось подтвердить, применено ли изменение. Проверьте состояние клиента, прежде чем повторять попытку.","変更が適用されたか確認できませんでした。再試行する前にクライアントの状態を確認してください。","Değişikliğin uygulanıp uygulanmadığı doğrulanamadı. Yeniden denemeden önce istemci durumunu kontrol edin.","Không xác nhận được thay đổi đã được áp dụng hay chưa. Hãy kiểm tra trạng thái client trước khi thử lại.","Não foi possível confirmar se a alteração foi aplicada. Verifique o status do cliente antes de tentar novamente."], + refusedAgyProfile: [ + "OpenCodex could not verify the agy profile at {path}. Restore the complete marked agy block or the saved original profile, then retry.", + "OpenCodex가 {path}의 agy 프로필을 확인하지 못했어요. 마커가 포함된 agy 블록 전체나 저장된 원본 프로필을 복원한 뒤 다시 시도하세요.", + "OpenCodex konnte das agy-Profil unter {path} nicht überprüfen. Stellen Sie den vollständigen markierten agy-Block oder das gesicherte Originalprofil wieder her und versuchen Sie es erneut.", + "OpenCodex n’a pas pu vérifier le profil agy dans {path}. Rétablissez le bloc agy complet avec ses marqueurs ou le profil d’origine sauvegardé, puis réessayez.", + "OpenCodex 无法验证 {path} 中的 agy 配置文件。请恢复带标记的完整 agy 配置块或已保存的原始配置文件,然后重试。", + "OpenCodex 無法驗證 {path} 中的 agy 設定檔。請還原帶有標記的完整 agy 區塊或已儲存的原始設定檔,然後重試。", + "OpenCodex не удалось проверить профиль agy по пути {path}. Восстановите весь блок agy вместе с маркерами или сохранённый исходный профиль и повторите попытку.", + "OpenCodex は {path} の agy プロファイルを確認できませんでした。マーカーを含む agy ブロック全体か、保存された元のプロファイルを復元してから、もう一度お試しください。", + "OpenCodex, {path} konumundaki agy profilini doğrulayamadı. İşaretleyicileriyle birlikte agy bloğunun tamamını veya kaydedilmiş özgün profili geri yükleyip yeniden deneyin.", + "OpenCodex không xác minh được hồ sơ agy tại {path}. Hãy khôi phục toàn bộ khối agy cùng các dấu đánh dấu hoặc hồ sơ gốc đã lưu, rồi thử lại.", + "O OpenCodex não conseguiu verificar o perfil do agy em {path}. Restaure o bloco completo do agy com seus marcadores ou o perfil original salvo e tente novamente.", + ], } satisfies Record; export type GatewayClientsCopyKey = `gatewayClients.${keyof typeof rows}`; diff --git a/gui/src/pages/integrations/GatewayClientsPage.tsx b/gui/src/pages/integrations/GatewayClientsPage.tsx index 3bf6b550c98..440e509c5f0 100644 --- a/gui/src/pages/integrations/GatewayClientsPage.tsx +++ b/gui/src/pages/integrations/GatewayClientsPage.tsx @@ -51,7 +51,6 @@ const NOTE_KEYS: Record = { const REFUSAL_KEYS: Record = { "requires-admission-token": "gatewayClients.refusedCredential", "invalid-model": "gatewayClients.refusedModel", - "unsupported-file": "gatewayClients.refusedFile", }; const APPLY_HINT: Record = { @@ -59,11 +58,19 @@ const APPLY_HINT: Record = { agy: "gatewayClients.hintAgy", }; -interface OutcomeView { tone: "ok" | "err"; keys: TKey[]; detail: string | null } +interface OutcomeView { tone: "ok" | "err"; keys: TKey[]; detail: string | null; vars?: Record } function describeOutcome(id: GatewayClientId, action: GatewayClientAction, outcome: GatewayClientActionOutcome): OutcomeView { if (!outcome.reached) return { tone: "err", keys: ["gatewayClients.actionFailed"], detail: null }; if (!outcome.ok) { + if (outcome.code === "agy-profile-restore-required") { + return outcome.profilePath + ? { tone: "err", keys: ["gatewayClients.refusedAgyProfile"], detail: null, vars: { path: outcome.profilePath } } + : { tone: "err", keys: ["gatewayClients.actionFailed"], detail: null }; + } + if (id === "antigravity" && outcome.code === "unsupported-file") { + return { tone: "err", keys: ["gatewayClients.refusedFile"], detail: null }; + } const known = outcome.code ? REFUSAL_KEYS[outcome.code] : undefined; if (known) return { tone: "err", keys: [known], detail: null }; // The text of an I/O error is the operating system's; any other unexpected refusal is shown as sent. @@ -173,7 +180,7 @@ function GatewayClientCard({ {result && ( - {result.keys.map(key => t(key)).join(" ")} + {result.keys.map(key => t(key, result.vars)).join(" ")} {result.detail && <> {result.detail}} )} diff --git a/gui/src/pages/integrations/gateway-clients-api.ts b/gui/src/pages/integrations/gateway-clients-api.ts index a6b2e90f027..f9c064ffbc4 100644 --- a/gui/src/pages/integrations/gateway-clients-api.ts +++ b/gui/src/pages/integrations/gateway-clients-api.ts @@ -25,7 +25,7 @@ export interface GatewayClientStatus { /** * `reached` is false when the request never produced a readable answer from the proxy. A refusal - * carries `code` (and `message` for an I/O error, whose text is the operating system's); + * carries a `code`, with a home-relative `profilePath` for agy restore refusals; * a success carries what was done: `changed` and, for a disconnect, `restore`. */ export interface GatewayClientActionOutcome { @@ -33,6 +33,7 @@ export interface GatewayClientActionOutcome { ok: boolean; code: string | null; message: string | null; + profilePath: string | null; changed: boolean; restore: "exact" | "path-wise" | "none" | null; } @@ -65,16 +66,17 @@ export async function runGatewayClientAction( headers: { "Content-Type": "application/json" }, body: JSON.stringify(model ? { model } : {}), }); - const body = await response.json() as { ok?: unknown; code?: unknown; message?: unknown; changed?: unknown; restore?: unknown }; + const body = await response.json() as { ok?: unknown; code?: unknown; message?: unknown; profilePath?: unknown; changed?: unknown; restore?: unknown }; return { reached: true, ok: response.ok && body.ok === true, code: typeof body.code === "string" ? body.code : null, message: typeof body.message === "string" && body.message ? body.message : null, + profilePath: typeof body.profilePath === "string" && body.profilePath.startsWith("~/") ? body.profilePath : null, changed: body.changed === true, restore: typeof body.restore === "string" && RESTORES.has(body.restore) ? body.restore as GatewayClientActionOutcome["restore"] : null, }; } catch { - return { reached: false, ok: false, code: null, message: null, changed: false, restore: null }; + return { reached: false, ok: false, code: null, message: null, profilePath: null, changed: false, restore: null }; } } diff --git a/gui/tests/gateway-clients-page.test.tsx b/gui/tests/gateway-clients-page.test.tsx index ce2a5c86d84..57e862d538a 100644 --- a/gui/tests/gateway-clients-page.test.tsx +++ b/gui/tests/gateway-clients-page.test.tsx @@ -169,14 +169,35 @@ test("an untouched model field sends no model, so the current one is kept", asyn test("a refusal is translated from its code, and an I/O error keeps the system text", async () => { actionResponse = () => json({ ok: false, code: "unsupported-file", message: "settings.json is not a JSON object; left untouched." }, 409); + clients[0]!.state = "connected"; await mount(); - await act(async () => { button(card("agy"), "Disconnect").click(); }); + await act(async () => { button(card("antigravity"), "Disconnect").click(); }); await settle(); - expect(requests.find(request => request.method === "POST")?.url).toBe(`${apiBase}/api/gateway-clients/agy/disconnect`); - expect(card("agy").querySelector(".notice-err")?.textContent).toBe("settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again."); + expect(requests.find(request => request.method === "POST")?.url).toBe(`${apiBase}/api/gateway-clients/antigravity/disconnect`); + expect(card("antigravity").querySelector(".notice-err")?.textContent).toBe("settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again."); actionResponse = () => json({ ok: false, code: "io-error", message: "EACCES: permission denied" }, 409); await act(async () => { button(card("agy"), "Disconnect").click(); }); await settle(); expect(card("agy").querySelector(".notice-err code")?.textContent).toBe("EACCES: permission denied"); }); + +test("agy disconnect shows the affected shell profile and recovery instructions", async () => { + clients[1]!.state = "drifted"; + actionResponse = () => json({ + ok: false, + code: "agy-profile-restore-required", + profilePath: "~/.zshrc", + message: "Server diagnostic that must stay hidden.", + }, 409); + await mount(); + const agy = card("agy"); + await act(async () => { button(agy, "Disconnect").click(); }); + await settle(); + + expect(requests.find(request => request.method === "POST")?.url).toBe(`${apiBase}/api/gateway-clients/agy/disconnect`); + expect(agy.querySelector(".notice-err")?.textContent).toBe( + "OpenCodex could not verify the agy profile at ~/.zshrc. Restore the complete marked agy block or the saved original profile, then retry.", + ); + expect(button(agy, "Disconnect").disabled).toBe(false); +}); diff --git a/scripts/test-layout/layout-clients.json b/scripts/test-layout/layout-clients.json index 6914d2ed71a..6e29996e786 100644 --- a/scripts/test-layout/layout-clients.json +++ b/scripts/test-layout/layout-clients.json @@ -7,6 +7,7 @@ "windows-config-root-integration-writers.test.ts": "windows", "windows-cli-config-root-startup.test.ts": "windows", "t3code-client-lifecycle.test.ts": "clients", + "gateway-client-restore.test.ts": "clients", "gateway-client-safety.test.ts": "clients", "gateway-clients.test.ts": "clients", "gateway-client-command.test.ts": "cli", diff --git a/src/integrations/gateway-clients/agy.ts b/src/integrations/gateway-clients/agy.ts index 6515563fc0d..343302b11e3 100644 --- a/src/integrations/gateway-clients/agy.ts +++ b/src/integrations/gateway-clients/agy.ts @@ -3,7 +3,8 @@ * No agy settings file is changed. Idea follows Magpie (MIT, (c) yetone), internal/agent/agy.go. */ import { existsSync } from "node:fs"; -import { basename, dirname, join } from "node:path"; +import { basename, dirname, join, relative, sep } from "node:path"; +import { redactUserPath } from "../../lib/redact"; import { adminGatewayOverride, assertClientSize, checkedClientDestination, clientRefusal, dropStash, envGatewayOverride, inspectClientFile, inspectStashPresence, isRestoreFile, mkdirTracked, mutateClient, readClientFile, readStash, @@ -24,6 +25,7 @@ interface Entry { createdDirs: string[]; writtenSha256: string; pendingSha256?: string; + restoredSha256?: string; pathWiseOnly?: true; } interface Stash { version: 1; files: Entry[] } @@ -104,16 +106,33 @@ function assertSameTarget(entry: Entry | undefined, target: string | undefined): const recordedHash = (entry: Entry, current: string): boolean => entry.writtenSha256 === current || entry.pendingSha256 === current; -function blockSpan(text: string): { start: number; end: number } | null { - const start = text.indexOf(START); - if (start < 0) return null; - const endMark = text.indexOf(END, start); - if (endMark < 0) return null; - let end = endMark + END.length; +const MARKER_LINE = new RegExp(`(?:^\uFEFF?|\n)(${START}|${END})(?=\r?\n|$)`, "g"); + +// Markerless text alone cannot prove removal: even a bare gateway URL can remain. +function matchesRestoredProfile(entry: Entry, file: ClientFile): boolean { + return entry.restoredSha256 === file.hash + || (entry.originalBytes !== null && file.bytes.equals(Buffer.from(entry.originalBytes, "base64"))); +} + +type BlockSpan = { start: number; end: number }; +function blockSpan(text: string): BlockSpan | "malformed" | null { + const markers = text.matchAll(MARKER_LINE); + const first = markers.next().value; + if (!first) return null; + const last = markers.next().value; + if (first[1] !== START || last?.[1] !== END || !markers.next().done) return "malformed"; + const start = first.index + first[0].length - START.length; + let end = last.index + last[0].length; if (text.startsWith("\r\n", end)) end += 2; else if (text[end] === "\n") end += 1; return { start, end }; } +function profileRestoreRefusal(ctx: GatewayClientContext, path: string): GatewayClientResult { + const profilePath = redactUserPath(`~/${relative(ctx.home, path).split(sep).join("/")}`); + const message = `OpenCodex could not verify the agy profile at ${profilePath}. Restore the complete marked agy block or the saved original profile, then retry.`; + return { ...clientRefusal(message, "agy-profile-restore-required"), profilePath }; +} + type Encoding = "utf8" | "utf16le"; const UTF16LE_BOM = Buffer.from([0xff, 0xfe]); const strictUtf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); @@ -132,10 +151,9 @@ const encode = (text: string, encoding: Encoding): Buffer => encoding === "utf16le" ? Buffer.concat([UTF16LE_BOM, Buffer.from(text, "utf16le")]) : Buffer.from(text); const eolOf = (text: string) => (text.includes("\r\n") ? "\r\n" : "\n"); -const withBlock = (text: string, block: string): string => { +const withBlock = (text: string, block: string, span: BlockSpan | null): string => { const eol = eolOf(text); const b = block.replace(/\n/g, eol) + eol; - const span = blockSpan(text); if (span) return text.slice(0, span.start) + b + text.slice(span.end); if (text === "") return b; let head = text; @@ -143,8 +161,10 @@ const withBlock = (text: string, block: string): string => { if (!/(\r?\n){2}$/.test(head)) head += eol; return head + b; }; -const withoutBlock = (text: string): string => { const s = blockSpan(text); return s ? text.slice(0, s.start) + text.slice(s.end) : text; }; -const blockIn = (text: string): string | null => { const s = blockSpan(text); return s ? text.slice(s.start, s.end).replace(/\r\n/g, "\n").replace(/\n$/, "") : null; }; +function blockIn(text: string): string | null { + const span = blockSpan(text); + return span && span !== "malformed" ? text.slice(span.start, span.end).replace(/\r\n/g, "\n").replace(/\n$/, "") : null; +} function status(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClientStatus { const hasRecord = inspectStashPresence(ctx, ID); @@ -180,9 +200,10 @@ function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClien const available = candidates(ctx); const profiles = targets(ctx, available).sort((a, b) => Number(entries.has(b.path)) - Number(entries.has(a.path))); const seen = new Set(); - const changedFiles: string[] = []; - const staged: { entry: Entry; file: ClientFile | null; out: Buffer; allowedPaths: string[] }[] = []; - for (const profile of profiles) { + const selected = new Set(profiles.map(profile => profile.path)); + const trackedOnly = [...entries.values()].filter(entry => !selected.has(entry.path)); + const checked: (Profile & { file: ClientFile | null; allowedPaths: string[]; text: string; encoding: Encoding; span: BlockSpan | null })[] = []; + for (const profile of [...profiles, ...trackedOnly]) { const { path, kind } = profile; const allowedPaths = allowedProfilePaths(available, kind); const file = readClientFile(ctx, path, allowedPaths); @@ -192,20 +213,28 @@ function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClien if (file) seen.add(file.target); const decoded = file ? decode(file.bytes) : { text: "", encoding: "utf8" as const }; if (!decoded) return clientRefusal(`${path} is not UTF-8 or BOM-prefixed UTF-16LE text.`, "unsupported-file"); - const out = encode(withBlock(decoded.text, agyBlock(kind, target)), decoded.encoding); + const span = blockSpan(decoded.text); + if (span === "malformed" || (!span && prev && file && !matchesRestoredProfile(prev, file))) { + return prev ? profileRestoreRefusal(ctx, path) + : clientRefusal("An agy profile has incomplete or ambiguous block markers.", "unsupported-file"); + } + if (selected.has(path)) checked.push({ path, kind, file, allowedPaths, ...decoded, span }); + } + const changedFiles: string[] = []; + const staged = checked.map(({ path, kind, file, allowedPaths, text, encoding, span }) => { + const prev = entries.get(path); + const out = encode(withBlock(text, agyBlock(kind, target), span), encoding); assertClientSize(out); - const keep = prev !== undefined && file !== null && blockIn(decoded.text) !== null; + const keep = prev !== undefined && file !== null && span !== null; const drifted = keep && (prev.pathWiseOnly === true || !recordedHash(prev, file.hash)); - staged.push({ - entry: { - path, kind, originalBytes: keep ? prev.originalBytes : file?.bytes.toString("base64") ?? null, - createdDirs: prev?.createdDirs ?? [], writtenSha256: file?.hash ?? "", - pendingSha256: sha256(out), - ...(drifted ? { pathWiseOnly: true } : {}), - }, - file, out, allowedPaths, - }); - } + const entry: Entry = { + path, kind, originalBytes: keep ? prev.originalBytes : file?.bytes.toString("base64") ?? null, + createdDirs: prev?.createdDirs ?? [], writtenSha256: file?.hash ?? "", + pendingSha256: sha256(out), + ...(drifted ? { pathWiseOnly: true } : {}), + }; + return { entry, file, out, allowedPaths }; + }); try { for (const { entry, file, allowedPaths } of staged) { entry.resolvedPath = checkedClientDestination(ctx, entry.path, file, allowedPaths); @@ -240,6 +269,7 @@ function disconnect(ctx: GatewayClientContext): GatewayClientResult { const profiles = [...entries.values(), ...targets(ctx, available).filter(({ path }) => !entries.has(path))]; const seen = new Set(); const changes: { path: string; apply: () => void }[] = []; + let journalRestore = false; const createdDirs: string[] = []; let pathWise = false; for (const { path, kind } of profiles) { @@ -266,13 +296,26 @@ function disconnect(ctx: GatewayClientContext): GatewayClientResult { } const decoded = decode(file.bytes); if (!decoded && entry) return clientRefusal(`${path} uses an unsupported encoding. The restore record was kept.`, "unsupported-file"); - if (!decoded || blockIn(decoded.text) === null) continue; - changes.push({ path, apply: () => writeClientFile(ctx, path, file, encode(withoutBlock(decoded.text), decoded.encoding), allowedPaths) }); + if (!decoded) continue; + const { text, encoding } = decoded; + const span = blockSpan(text); + if (!span || span === "malformed") { + if (entry && (span === "malformed" || !matchesRestoredProfile(entry, file))) return profileRestoreRefusal(ctx, path); + continue; + } + const bytes = encode(text.slice(0, span.start) + text.slice(span.end), encoding); + if (entry) { + entry.restoredSha256 = sha256(bytes); + journalRestore = true; + } + changes.push({ path, apply: () => writeClientFile(ctx, path, file, bytes, allowedPaths) }); pathWise = true; } const changedFiles: string[] = []; try { + // If a later write fails, a retry can verify profiles already restored path-wise. + if (journalRestore) writeStash(ctx, ID, { version: 1, files: [...entries.values()] } satisfies Stash); for (const { path, apply } of changes) { apply(); changedFiles.push(path); diff --git a/src/integrations/gateway-clients/antigravity.ts b/src/integrations/gateway-clients/antigravity.ts index d873f68142c..5793c7acc93 100644 --- a/src/integrations/gateway-clients/antigravity.ts +++ b/src/integrations/gateway-clients/antigravity.ts @@ -34,7 +34,7 @@ const ID = "antigravity"; const BOM = String.fromCharCode(0xfeff); const settingsPath = (ctx: GatewayClientContext) => join(ctx.home, ".antigravity", "settings.json"); const isObj = (v: unknown): v is Json => !!v && typeof v === "object" && !Array.isArray(v); -const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); +const same = (a: unknown, b: unknown) => Bun.deepEquals(a, b, true); const prior = (o: Json | undefined, k: string): Prior => o && k in o ? { present: true, value: o[k] } : { present: false }; interface Parsed { doc: Json; indent: string | number | undefined; eol: string; trailing: boolean; bom: boolean } @@ -182,26 +182,39 @@ function disconnect(ctx: GatewayClientContext): GatewayClientResult { const parsed = parseSettings(file.bytes); if (typeof parsed === "string") return clientRefusal(`${GATEWAY_NOTE_TEXT[parsed]} The restore record was kept.`, "unsupported-file"); const { doc } = parsed; - const kept: string[] = []; - if (states.some(st => st.written.gateway !== null && same(doc.gateway, st.written.gateway))) { - if (stash.prior.gateway.present) doc.gateway = stash.prior.gateway.value; else delete doc.gateway; - } else kept.push("gateway"); const models = isObj(doc.models) ? doc.models : undefined; + const saved = stash.prior; const writtenModels = states.map(st => st.written.defaultModelId).filter((id): id is string => id !== null); - if (models && writtenModels.length > 0) { - if (writtenModels.includes(models.defaultModelId as string)) { - if (stash.prior.defaultModelId.present) models.defaultModelId = stash.prior.defaultModelId.value; else delete models.defaultModelId; - } else kept.push("models.defaultModelId"); + const gatewayMatches = states.some(st => st.written.gateway !== null && same(doc.gateway, st.written.gateway)); + const defaultMatches = writtenModels.some(id => models?.defaultModelId === id); + const listWasRemoved = saved.list.present && (models !== undefined || doc.models === undefined) && models?.list === undefined; + + // A prior value may already be in place if a previous restore could not remove the record. + const conflicts: string[] = []; + if (!gatewayMatches && !same(doc.gateway, saved.gateway.value)) conflicts.push("gateway"); + if (writtenModels.length > 0 && !defaultMatches && !same(models?.defaultModelId, saved.defaultModelId.value)) { + conflicts.push("models.defaultModelId"); + } + if (saved.list.present && !listWasRemoved && !same(models?.list, saved.list.value)) conflicts.push("models.list"); + if (conflicts.length) { + return clientRefusal(`Antigravity settings changed at ${conflicts.join(", ")}. The restore record was kept.`, "unsupported-file"); + } + + if (gatewayMatches) { + if (saved.gateway.present) doc.gateway = saved.gateway.value; else delete doc.gateway; + } + if (models && defaultMatches) { + if (saved.defaultModelId.present) models.defaultModelId = saved.defaultModelId.value; else delete models.defaultModelId; } - if (stash.prior.list.present) { + if (listWasRemoved) { const m: Json = models ?? {}; - if (!("list" in m)) m.list = stash.prior.list.value; else kept.push("models.list"); + m.list = saved.list.value; doc.models = m; } const finalModels = isObj(doc.models) ? doc.models : undefined; if (finalModels && Object.keys(finalModels).length === 0 && !stash.prior.modelsPresent) delete doc.models; writeClientFile(ctx, path, file, serialize(parsed)); - return done("path-wise", `The file changed after OpenCodex wrote it, so only the gateway, models.defaultModelId and models.list entries were restored; your other edits were kept.${kept.length ? ` Left as you had them: ${kept.join(", ")}.` : ""}`, [path]); + return done("path-wise", `The file changed after OpenCodex wrote it, so only the gateway, models.defaultModelId and models.list entries were restored; your other edits were kept.`, [path]); } export const ANTIGRAVITY_CONNECTOR: GatewayClientConnector = { diff --git a/src/integrations/gateway-clients/index.ts b/src/integrations/gateway-clients/index.ts index e5b66283417..0d555020e59 100644 --- a/src/integrations/gateway-clients/index.ts +++ b/src/integrations/gateway-clients/index.ts @@ -81,7 +81,8 @@ export function disconnectGatewayClient(id: GatewayClientId, ctx: GatewayClientC export function gatewayActionBody(outcome: GatewayActionOutcome): Record { if (!outcome.ok) { const files = "changedFiles" in outcome ? outcome.changedFiles : []; - return { ok: false, code: outcome.code, message: outcome.message, ...(files.length ? { changedFiles: files } : {}) }; + const profilePath = "profilePath" in outcome ? outcome.profilePath : undefined; + return { ok: false, code: outcome.code, message: outcome.message, ...(profilePath ? { profilePath } : {}), ...(files.length ? { changedFiles: files } : {}) }; } const { ok, id, action, changed, changedFiles, restore, message, notes, status } = outcome; return { ok, id, action, changed, changedFiles, ...(restore ? { restore } : {}), message, notes, status }; diff --git a/src/integrations/gateway-clients/types.ts b/src/integrations/gateway-clients/types.ts index bc72ea88b9b..101fa14e8a6 100644 --- a/src/integrations/gateway-clients/types.ts +++ b/src/integrations/gateway-clients/types.ts @@ -57,11 +57,13 @@ export interface GatewayClientStatus { defaultModel?: string; } -export type GatewayRefusalCode = "unsupported-file" | "io-error"; +export type GatewayRefusalCode = "unsupported-file" | "agy-profile-restore-required" | "io-error"; export interface GatewayClientResult { ok: boolean; code?: GatewayRefusalCode; + /** Home-relative display path for an agy profile that needs repair. */ + profilePath?: string; message: string; changed: boolean; changedFiles: string[]; diff --git a/structure/clients/antigravity-gateway.md b/structure/clients/antigravity-gateway.md index b9d1a5c628a..f7f61c90ba0 100644 --- a/structure/clients/antigravity-gateway.md +++ b/structure/clients/antigravity-gateway.md @@ -50,8 +50,9 @@ Disconnect reports one of three outcomes. and the directories OpenCodex created are removed when it did not exist. - **path-wise.** The user edited the file since. Only OpenCodex's own entries are reverted: `gateway`, `models.defaultModelId` and `models.list` in the app settings, the marked block in a profile. Every edit - outside those is kept, and a settings entry the user changed after connecting is left as the user set it. - A profile block is removed whole, so an edit made inside its markers is not kept. + outside those is kept. Antigravity compares JSON values structurally and refuses the restore if a + managed entry differs from both its applied and prior values. An agy block is removed between its + two standalone marker lines, including edits inside the block. - **none.** There is no record, or the file is already gone; nothing is changed. Reconnect keeps the first record while the client is connected. If the file was edited in between, @@ -62,10 +63,17 @@ URL again and disconnect restores the original gateway block. Connect journals the replacement hash before editing the client file, so disconnect can recognise the original and pending states after an interrupted write. A profile is read as UTF-8 without NUL bytes or as BOM-prefixed UTF-16LE (used by Windows PowerShell 5.1 redirection). It is written back -in the same encoding. During disconnect, an untracked profile that cannot be resolved or read is skipped. -Recorded profiles are checked strictly. If a recorded profile cannot be decoded, disconnect refuses with -`unsupported-file` and keeps the recovery record. A settings file with comments, trailing commas -or a non-object root is refused with `unsupported-file` and left untouched. +in the same encoding. Connect refuses incomplete or ambiguous agy markers before staging any profile +updates. During disconnect, an untracked profile that cannot be resolved or read is skipped. +If a recorded profile cannot be decoded, disconnect refuses with `unsupported-file` and keeps the +recovery record. Incomplete or ambiguous markers in a recorded profile yield +`agy-profile-restore-required`. When both markers are absent, connect and disconnect require its +bytes to match the saved original or a journaled path-wise restore, or return the same refusal. +The refusal names the home-relative profile and asks the user to restore the complete marked block +or the saved original profile before retrying. The CLI and uninstall surface the same repair message. +Disconnect records the expected hash before a path-wise write so a retry can verify profiles whose +restore already finished. +Antigravity uses the same refusal for a managed settings conflict or a settings file it cannot parse. `src/cli/uninstall-client-state.ts` disconnects every gateway client with a restore record before removing config. The production dependency set supplies the current user and config directory. @@ -90,8 +98,9 @@ credential. An override set only in the Antigravity process is invisible to Open `src/server/management-api.ts` does not name it. Every note and override in a status carries a stable `code` beside its English `text` or `detail` (`GATEWAY_NOTE_TEXT` in `types.ts` is the one English source); the CLI prints the English, the dashboard tab translates the code, and an action's outcome is -rendered from `code`, `changed` and `restore` rather than from `message`. A refusal is HTTP 409 with `{ok, code, message}`, an -unknown id is 404. The routes sit behind the ordinary management auth and origin checks, and a sibling +rendered from `code`, `changed` and `restore`. A refusal is HTTP 409 with `{ok, code, message}`. The +agy profile repair refusal also includes a display-only `profilePath` for the translated guidance. +An unknown id is 404. The routes sit behind the ordinary management auth and origin checks, and a sibling instance refuses the mutations. `ocx connect|disconnect antigravity|agy` and `ocx connect antigravity|agy status` in `src/cli/gateway-client-command.ts` call those routes through the running proxy and run the same connectors in-process when the proxy is not running. The dispatch branch sits diff --git a/tests/cli/gateway-client-command.test.ts b/tests/cli/gateway-client-command.test.ts index e4de190099d..42899fc1b5d 100644 --- a/tests/cli/gateway-client-command.test.ts +++ b/tests/cli/gateway-client-command.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { dispatchCommand, type CliDispatchDeps } from "../../src/cli/dispatch"; @@ -61,6 +61,27 @@ describe("ocx connect|disconnect antigravity|agy", () => { } finally { io.restore(); } }); + test("agy disconnect identifies the profile and repair after manual block removal", async () => { + const io = capture(); + try { + const profile = join(ctx.home, ".bashrc"); + writeFileSync(profile, "# user profile\n"); + expect(await runGatewayClientCommand("connect", "agy", [], offline())).toBe(0); + writeFileSync(profile, "# user profile\nexport USER_EDIT=1\n"); + io.out.length = 0; + + expect(await runGatewayClientCommand("disconnect", "agy", [], offline())).toBe(5); + expect(io.err.join("\n")).toContain("~/.bashrc"); + expect(io.err.join("\n")).toContain("Restore the complete marked agy block or the saved original profile, then retry."); + expect(io.err.join("\n")).not.toContain(ctx.home); + + expect(await runGatewayClientCommand("disconnect", "agy", ["--json"], offline())).toBe(5); + expect(JSON.parse(io.out.join("\n"))).toMatchObject({ + ok: false, code: "agy-profile-restore-required", profilePath: "~/.bashrc", + }); + } finally { io.restore(); } + }); + test("with no running proxy and port 0, connect is refused before any file is written", async () => { const io = capture(); try { diff --git a/tests/cli/uninstall.test.ts b/tests/cli/uninstall.test.ts index 788b5dbc217..5af6ae3e244 100644 --- a/tests/cli/uninstall.test.ts +++ b/tests/cli/uninstall.test.ts @@ -985,6 +985,100 @@ describe("uninstall restores recorded third-party integrations before deleting r } finally { rmSync(f.root, { recursive: true, force: true }); } }); + test("uninstall refuses a CRLF lone agy marker after a reconnect attempt", async () => { + const f = await fixture({ gatewayOnly: true }); + try { + const context = f.deps.gatewayContext(); + const profile = join(f.home, ".bashrc"); + const record = join(f.configDir, "gateway-clients", "agy.json"); + const original = "# existing shell profile\r\n"; + writeFileSync(profile, original); + expect(connectGatewayClient("agy", context, config, config.port).ok).toBe(true); + const connected = readFileSync(profile, "utf8"); + const damaged = connected.replace("# <<< opencodex agy <<<\r\n", ""); + const saved = readFileSync(record, "utf8"); + expect(damaged).not.toBe(connected); + writeFileSync(profile, damaged); + expect(GATEWAY_CLIENTS.agy.disconnect(context)).toMatchObject({ ok: false, code: "agy-profile-restore-required" }); + const reconnect = connectGatewayClient("agy", context, config, config.port + 1); + f.deps.remove = () => removeGatewayFixtureConfig(f.configDir); + + await expect(removeOwnedConfigAfterDesktopCleanup(safeTeardown, f.deps)) + .rejects.toThrow("Gateway client cleanup refused for agy"); + expect(reconnect).toMatchObject({ ok: false, code: "agy-profile-restore-required", changed: false }); + expect(readFileSync(profile, "utf8")).toBe(damaged); + expect(readFileSync(record, "utf8")).toBe(saved); + + writeFileSync(profile, connected); + expect(await removeOwnedConfigAfterDesktopCleanup(safeTeardown, f.deps)) + .toEqual({ status: "removed", residualPaths: [] }); + expect(readFileSync(profile, "utf8")).toBe(original); + expect(existsSync(record)).toBe(false); + } finally { rmSync(f.root, { recursive: true, force: true }); } + }); + + test("uninstall can retry after the whole agy block is restored beside an unrelated edit", async () => { + const f = await fixture({ gatewayOnly: true }); + try { + const profile = join(f.home, ".bashrc"); + const record = join(f.configDir, "gateway-clients", "agy.json"); + const original = "# existing shell profile\n"; + writeFileSync(profile, original); + expect(connectGatewayClient("agy", f.deps.gatewayContext(), config, config.port).ok).toBe(true); + const connected = readFileSync(profile, "utf8"); + const completeBlock = connected.slice(connected.indexOf("# >>> opencodex agy >>>")); + expect(completeBlock).toContain("# <<< opencodex agy <<<"); + const saved = readFileSync(record, "utf8"); + const edited = original + "export USER_EDIT=1\n"; + writeFileSync(profile, edited); + f.deps.remove = () => removeGatewayFixtureConfig(f.configDir); + + await expect(removeOwnedConfigAfterDesktopCleanup(safeTeardown, f.deps)) + .rejects.toThrow("OpenCodex could not verify the agy profile at ~/.bashrc. Restore the complete marked agy block or the saved original profile, then retry."); + expect(readFileSync(profile, "utf8")).toBe(edited); + expect(readFileSync(record, "utf8")).toBe(saved); + + writeFileSync(profile, edited + completeBlock); + expect(await removeOwnedConfigAfterDesktopCleanup(safeTeardown, f.deps)) + .toEqual({ status: "removed", residualPaths: [] }); + expect(readFileSync(profile, "utf8")).toBe(edited); + expect(existsSync(record)).toBe(false); + } finally { rmSync(f.root, { recursive: true, force: true }); } + }); + + test.each([ + ["partial wrapper", "agy() { AGY_LLM_GATEWAY_URL='http://127.0.0.1:10100' AGY_LLM_GATEWAY_API_KEY='opencodex-local' command agy \"$@\"; }"], + ["URL variable", "AGY_LLM_GATEWAY_URL='http://127.0.0.1:10100'"], + ["key variable", "AGY_LLM_GATEWAY_API_KEY='opencodex-local'"], + ["protocol variable", "AGY_LLM_GATEWAY_WIRE_PROTOCOL='genai'"], + ["URL value", "redirect='http://127.0.0.1:10100'"], + ])("uninstall preserves the agy journal when a markerless profile keeps the %s", async (_label, remnant) => { + const f = await fixture({ gatewayOnly: true }); + try { + const context = f.deps.gatewayContext(); + const profile = join(f.home, ".bashrc"); + const record = join(f.configDir, "gateway-clients", "agy.json"); + const original = "# existing shell profile\n"; + writeFileSync(profile, original); + expect(connectGatewayClient("agy", context, config, config.port).ok).toBe(true); + const saved = readFileSync(record, "utf8"); + const damaged = original + "\n" + remnant + "\n"; + writeFileSync(profile, damaged); + f.deps.remove = () => removeGatewayFixtureConfig(f.configDir); + + await expect(removeOwnedConfigAfterDesktopCleanup(safeTeardown, f.deps)) + .rejects.toThrow("Gateway client cleanup refused for agy"); + expect(readFileSync(profile, "utf8")).toBe(damaged); + expect(readFileSync(record, "utf8")).toBe(saved); + + writeFileSync(profile, original); + expect(await removeOwnedConfigAfterDesktopCleanup(safeTeardown, f.deps)) + .toEqual({ status: "removed", residualPaths: [] }); + expect(readFileSync(profile, "utf8")).toBe(original); + expect(existsSync(record)).toBe(false); + } finally { rmSync(f.root, { recursive: true, force: true }); } + }); + function addAsideProfiles(f: Awaited>) { const asideRoot = join(f.home, ".aside"); const profiles = [0, 1].map(id => { diff --git a/tests/clients/gateway-client-restore.test.ts b/tests/clients/gateway-client-restore.test.ts new file mode 100644 index 00000000000..ef5ed886bf0 --- /dev/null +++ b/tests/clients/gateway-client-restore.test.ts @@ -0,0 +1,157 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { GATEWAY_CLIENTS, type GatewayClientContext } from "../../src/integrations/gateway-clients"; +import * as gatewayIO from "../../src/integrations/gateway-clients/io"; + +const target = { url: "http://127.0.0.1:10100", apiKey: "opencodex-local", defaultModel: "managed-model" }; +const start = "# >>> opencodex agy >>>"; +const end = "# <<< opencodex agy <<<"; +let root: string; +let ctx: GatewayClientContext; + +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "ocx-gw-restore-"))); + ctx = { home: join(root, "home"), platform: "linux", env: { SHELL: "/bin/zsh" }, stateDir: join(root, "state") }; + mkdirSync(join(ctx.home, ".antigravity"), { recursive: true }); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const read = (path: string) => readFileSync(path, "utf8"); +const record = (id: string) => join(ctx.stateDir, "gateway-clients", id + ".json"); +const settings = () => join(ctx.home, ".antigravity", "settings.json"); +const originalSettings = { + theme: "dark", + gateway: { enabled: false }, + models: { defaultModelId: "mine", list: [{ modelId: "mine" }] }, +}; + +const markerDamage = [ + ["a missing closing marker", (text: string) => text.replace(end, "")], + ["a missing opening marker", (text: string) => text.replace(start, "")], + ["both markers missing", (text: string) => text.replace(start, "").replace(end, "")], + ["an inline closing marker", (text: string) => text.replace(end, "# unrelated " + end)], + ["nested markers", (text: string) => text.replace(end, start + "\necho inside-another-block\n" + end)], + ["duplicate marker pairs", (text: string) => text + text.slice(text.indexOf(start))], +] as const; + +test.each(markerDamage)("agy refuses to disconnect or reconnect a profile with %s", (_label, damage) => { + const agy = GATEWAY_CLIENTS.agy; + const bash = join(ctx.home, ".bashrc"); + const zsh = join(ctx.home, ".zshrc"); + writeFileSync(bash, "# bash\n"); + writeFileSync(zsh, "# zsh\n"); + expect(agy.connect(ctx, target).ok).toBe(true); + const connectedBash = read(bash); + const connectedZsh = read(zsh); + const afterBlock = "export KEEP_ME=1\n"; + const damaged = damage(connectedZsh) + afterBlock; + writeFileSync(zsh, damaged); + const saved = read(record("agy")); + + expect(agy.disconnect(ctx)).toMatchObject({ + ok: false, code: "agy-profile-restore-required", profilePath: "~/.zshrc", changed: false, changedFiles: [], + }); + expect(read(bash)).toBe(connectedBash); + expect(read(zsh)).toBe(damaged); + expect(read(record("agy"))).toBe(saved); + expect(agy.status(ctx, target).state).toBe("drifted"); + + expect(agy.connect(ctx, { ...target, url: "http://127.0.0.1:10200" })).toMatchObject({ + ok: false, code: "agy-profile-restore-required", profilePath: "~/.zshrc", changed: false, changedFiles: [], + }); + expect(read(bash)).toBe(connectedBash); + expect(read(zsh)).toBe(damaged); + expect(read(record("agy"))).toBe(saved); + + writeFileSync(zsh, connectedZsh + afterBlock); + expect(agy.disconnect(ctx)).toMatchObject({ ok: true, restore: "path-wise" }); + expect(read(bash)).toBe("# bash\n"); + expect(read(zsh)).toBe("# zsh\n\n" + afterBlock); + expect(existsSync(record("agy"))).toBe(false); +}); + +test("agy refuses a first connect to a profile with reversed markers", () => { + const profile = join(ctx.home, ".zshrc"); + const original = [end, "# profile", start].join("\r\n"); + writeFileSync(profile, original); + + expect(GATEWAY_CLIENTS.agy.connect(ctx, target)).toMatchObject({ + ok: false, code: "unsupported-file", changed: false, changedFiles: [], + }); + expect(read(profile)).toBe(original); + expect(existsSync(record("agy"))).toBe(false); +}); + +test("agy retries an interrupted path-wise restore without rewriting the restored profile", () => { + const agy = GATEWAY_CLIENTS.agy; + const bash = join(ctx.home, ".bashrc"); + const zsh = join(ctx.home, ".zshrc"); + writeFileSync(bash, "# bash\n"); + writeFileSync(zsh, "# zsh\n"); + expect(agy.connect(ctx, target).ok).toBe(true); + const edit = "export KEEP_ME=1\n"; + writeFileSync(bash, read(bash) + edit); + writeFileSync(zsh, read(zsh) + edit); + + const write = gatewayIO.writeClientFile; + const fault = spyOn(gatewayIO, "writeClientFile").mockImplementation((...args) => { + if (args[1] === zsh) throw new Error("fixture interrupted the second restore"); + write(...args); + }); + try { + expect(agy.disconnect(ctx)).toMatchObject({ ok: false, code: "io-error", changedFiles: [bash] }); + } finally { + fault.mockRestore(); + } + expect(read(bash)).toBe("# bash\n\n" + edit); + expect(existsSync(record("agy"))).toBe(true); + + expect(agy.disconnect(ctx)).toMatchObject({ ok: true, restore: "path-wise", changedFiles: [zsh] }); + expect(read(bash)).toBe("# bash\n\n" + edit); + expect(read(zsh)).toBe("# zsh\n\n" + edit); + expect(existsSync(record("agy"))).toBe(false); +}); + +test("Antigravity restores reordered gateway keys and preserves unrelated edits", () => { + const app = GATEWAY_CLIENTS.antigravity; + writeFileSync(settings(), JSON.stringify(originalSettings)); + expect(app.connect(ctx, target).ok).toBe(true); + const connected = JSON.parse(read(settings())); + const gateway = Object.fromEntries(Object.entries(connected.gateway).reverse()); + writeFileSync(settings(), JSON.stringify({ ...connected, gateway, theme: "light" })); + + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: "path-wise" }); + expect(JSON.parse(read(settings()))).toEqual({ ...originalSettings, theme: "light" }); + expect(existsSync(record("antigravity"))).toBe(false); +}); + +test.each(["gateway", "models.defaultModelId", "models.list"])( + "Antigravity refuses to restore a changed %s and keeps the settings and record", + path => { + const app = GATEWAY_CLIENTS.antigravity; + writeFileSync(settings(), JSON.stringify(originalSettings)); + expect(app.connect(ctx, target).ok).toBe(true); + const saved = read(record("antigravity")); + const applied = JSON.parse(read(settings())); + const edited = structuredClone(applied); + if (path === "gateway") edited.gateway.url = "https://custom.example"; + if (path === "models.defaultModelId") edited.models.defaultModelId = "another-model"; + if (path === "models.list") edited.models.list = [{ modelId: "another-model" }]; + const changed = JSON.stringify({ ...edited, theme: "light" }); + writeFileSync(settings(), changed); + + expect(app.disconnect(ctx)).toMatchObject({ + ok: false, code: "unsupported-file", changed: false, changedFiles: [], + message: expect.stringContaining(path), + }); + expect(read(settings())).toBe(changed); + expect(read(record("antigravity"))).toBe(saved); + + writeFileSync(settings(), JSON.stringify({ ...applied, theme: "light" })); + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: "path-wise" }); + expect(JSON.parse(read(settings()))).toEqual({ ...originalSettings, theme: "light" }); + expect(existsSync(record("antigravity"))).toBe(false); + }, +); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 40316330679..04fd39676f7 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -580,6 +580,7 @@ "cli-codex-log-guard.test.ts": "cli", "cli-companion.test.ts": "cli", "cli-config-bom.test.ts": "cli", "cli-config-command.test.ts": "cli", "cli-config-show-client.test.ts": "cli", "cli-connect-readiness.test.ts": "cli", + "gateway-client-restore.test.ts": "clients", "gateway-client-safety.test.ts": "clients", "gateway-clients.test.ts": "clients", "gateway-client-routes.test.ts": "server", "gateway-client-command.test.ts": "cli", "cli-dispatch.test.ts": "cli", "cli-client-start-fence.test.ts": "cli", diff --git a/tests/server/gateway-client-routes.test.ts b/tests/server/gateway-client-routes.test.ts index 7cea566f084..d4ca402cd3a 100644 --- a/tests/server/gateway-client-routes.test.ts +++ b/tests/server/gateway-client-routes.test.ts @@ -66,6 +66,31 @@ describe("gateway client management routes", () => { expect(readFileSync(settings(), "utf8")).toBe('{\n // note\n}\n'); }); + test("agy restore refusal returns the redacted profile and repair guidance", async () => { + const profile = join(gateway.home, ".bashrc"); + const original = "# user profile\n"; + writeFileSync(profile, original); + expect((await call("POST", "/api/gateway-clients/agy/connect", {})).status).toBe(200); + const edited = original + "export USER_EDIT=1\n"; + writeFileSync(profile, edited); + const record = join(gateway.stateDir, "gateway-clients", "agy.json"); + const saved = readFileSync(record, "utf8"); + + const refused = await call("POST", "/api/gateway-clients/agy/disconnect"); + expect(refused).toEqual({ + status: 409, + json: { + ok: false, + code: "agy-profile-restore-required", + profilePath: "~/.bashrc", + message: expect.stringContaining("Restore the complete marked agy block or the saved original profile, then retry."), + }, + }); + expect(JSON.stringify(refused.json)).not.toContain(gateway.home); + expect(readFileSync(profile, "utf8")).toBe(edited); + expect(readFileSync(record, "utf8")).toBe(saved); + }); + test("status stays available without parsing oversized client files", async () => { mkdirSync(join(gateway.home, ".antigravity")); const text = '{"models":{"defaultModelId":"too-large"}}';