Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(remote): upgrade stale Codex packages and deduplicate ready events

DavidShen847f9d407361
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 1a7f0db7f2..69bda8e5f2 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -2851,7 +2851,9 @@ export async function listSshCodexProviders(hostId: string) {
const remote = getRemoteSshPool().get(hostId);
if (!remote || remote.getStatus() !== 'ready') throw new Error('SSH host is not connected');
let changed = false;
- const stop = remote.onStatus(() => { changed = true; });
+ const stop = remote.onStatus((snapshot) => {
+ if (snapshot.status !== 'ready') changed = true;
+ });
const assertCurrent = () => {
if (changed || getActiveAppSession().generation !== owner ||
getRemoteSshPool().get(hostId) !== remote || remote.getStatus() !== 'ready') {
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/remoteAgentReadiness.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/remoteAgentReadiness.test.ts
new file mode 100644
index 0000000000..80168dafab
--- /dev/null
+++ b/apps/desktop/src/main/remote-ssh/__tests__/remoteAgentReadiness.test.ts
@@ -0,0 +1,58 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { ScriptTarget, transpileModule } from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+
+const source = readFileSync(resolve(__dirname, '..', 'index.ts'), 'utf8');
+const start = source.indexOf('export async function ensureRemoteAgentInstalled(');
+const end = source.indexOf('\n/**', start);
+const js = transpileModule(source.slice(start, end).replace('export async', 'async'), {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+}).outputText;
+
+describe('SSH Codex managed installation admission', () => {
+ it.each([false, true])('uses full-package probe (installed=%s) before caching', async (installed) => {
+ const host = { getStatus: () => 'ready', exec: vi.fn() };
+ const cache = new Map();
+ const probe = vi.fn().mockResolvedValue({ installed, installedVersion: 'managed-version' });
+ const ensure = new Function('remoteAgentInstalledCache', 'isAgentCacheHit', 'getPool',
+ 'probeRemoteAgent', 'throwIpcError', js + '; return ensureRemoteAgentInstalled;')(
+ cache, (cached: Map<string, unknown> | undefined, kind: string) => cached?.has(kind),
+ () => new Map([['builder', host]]), probe,
+ (code: string) => { throw new Error(code); },
+ );
+ if (installed) {
+ await ensure('builder', 'codex');
+ await ensure('builder', 'codex');
+ expect(cache.get('builder').get('codex')).toEqual({ installedVersion: 'managed-version' });
+ } else {
+ await expect(ensure('builder', 'codex')).rejects.toThrow('SSH_AGENT_NOT_INSTALLED');
+ expect(cache.size).toBe(0);
+ }
+ expect(probe).toHaveBeenCalledExactlyOnceWith(host, 'codex');
+ expect(host.exec).not.toHaveBeenCalled();
+ });
+});
+
+describe('SSH Codex model read status ownership', () => {
+ it.each(['ready', 'disconnected'])('handles a %s snapshot during discovery', async (status) => {
+ const hostSource = readFileSync(resolve(__dirname, '..', '..', 'maker-host', 'index.ts'), 'utf8');
+ const begin = hostSource.indexOf('export async function listSshCodexProviders(');
+ const code = hostSource.slice(begin, hostSource.indexOf('\nexport async function', begin + 1));
+ const compiled = transpileModule(code.replace('export async', 'async'), {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+ }).outputText;
+ let onStatus!: (snapshot: { status: string }) => void;
+ const stop = vi.fn();
+ const remote = { getStatus: () => 'ready', onStatus: (fn: typeof onStatus) => { onStatus = fn; return stop; } };
+ const agent = { listRemoteModels: async () => { onStatus({ status }); return ['remote-model']; } };
+ const read = new Function('getActiveAppSession', 'getRemoteSshPool', 'ensureRemoteAgentInstalledOrInstall',
+ 'getMaker', '_codexAgent', 'remoteCodexProvider', compiled + '; return listSshCodexProviders;')(
+ () => ({ generation: 1 }), () => new Map([['builder', remote]]), async () => {},
+ () => {}, agent, (models: string[]) => models,
+ );
+ if (status === 'ready') await expect(read('builder')).resolves.toEqual([['remote-model']]);
+ else await expect(read('builder')).rejects.toThrow('SSH model request is stale');
+ expect(stop).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.ts
index 9eedc0dbf3..1bef850ee6 100644
--- a/apps/desktop/src/main/remote-ssh/index.ts
+++ b/apps/desktop/src/main/remote-ssh/index.ts
@@ -396,8 +396,8 @@ function isAgentCacheHit(
* 能正确 toast 的 SSH_AGENT_NOT_INSTALLED IPC error, 引导用户去 Settings 安装。
*
* Claude Code 首次检查走完整 probeRemoteAgent,确保 Cindy 管理的远端 runtime
- * 与当前 pin 一致;否则客户端升级后旧 binary 会永久命中 `test -x`。Codex 仍
- * 只做存在性检查。两者命中内存 cache 后续都是 ~0ms。
+ * 与当前 pin 一致;Codex 同样探测版本及完整包布局,旧 standalone 触发升级。
+ * 各引擎命中内存 cache 后续都是 ~0ms。
*/
export async function ensureRemoteAgentInstalled(
hostId: string,
@@ -412,20 +412,9 @@ export async function ensureRemoteAgentInstalled(
throwIpcError('SSH_NOT_CONNECTED', `ssh host ${hostId} not connected`);
}
- let ok: boolean;
- let installedVersion: string | null = null;
- if (agentKind === 'claude-code' || agentKind === 'pi') {
- const probe = await probeRemoteAgent(host, agentKind);
- ok = probe.installed;
- installedVersion = probe.installedVersion;
- } else {
- const binPath = '$HOME/.xdt-server/v1/codex-home/packages/standalone/current/codex';
- const result = await host.exec(`test -x ${binPath} && echo OK || echo MISSING`, {
- timeoutMs: 5_000,
- label: 'check-agent-installed',
- });
- ok = result.stdout.trim() === 'OK';
- }
+ const probe = await probeRemoteAgent(host, agentKind);
+ const ok = probe.installed;
+ const installedVersion = probe.installedVersion;
if (!ok) {
const friendlyKind = agentKind === 'codex' ? 'Codex' : agentKind === 'pi' ? 'Pi' : 'Claude Code';
throwIpcError(
diff --git a/apps/desktop/src/renderer/__tests__/sshCodexModels.test.tsx b/apps/desktop/src/renderer/__tests__/sshCodexModels.test.tsx
index 3d4bc308dc..3fc43c5695 100644
--- a/apps/desktop/src/renderer/__tests__/sshCodexModels.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sshCodexModels.test.tsx
@@ -20,6 +20,23 @@ afterEach(cleanup);
const providers = (model: string) => [sshNativeCodexProvider([sshModel(model)])];
describe('SSH Codex model discovery', () => {
+ it('keeps the catalog on repeated ready snapshots and reloads once on reconnect', async () => {
+ list.mockResolvedValue(providers('remote-model'));
+ const view = renderHook(() => useSshCodexProviders('a'));
+ const status = (value: string) => statusChanged({ config: { id: 'a' }, status: value } as RemoteHostSnapshot);
+ act(() => { status('ready'); status('ready'); });
+ await waitFor(() => expect(view.result.current.status).toBe('ready'));
+ const catalog = view.result.current.providers;
+ act(() => { status('ready'); status('ready'); });
+ expect(list).toHaveBeenCalledTimes(1);
+ expect(view.result.current.providers).toBe(catalog);
+ expect(view.result.current.status).toBe('ready');
+ act(() => { status('disconnected'); status('connecting'); status('ready'); status('ready'); });
+ await waitFor(() => expect(view.result.current.status).toBe('ready'));
+ expect(list).toHaveBeenCalledTimes(2);
+ act(() => view.result.current.refresh());
+ await waitFor(() => expect(list).toHaveBeenCalledTimes(3));
+ });
it('ignores late results from a previous host and invalidates on disconnect', async () => {
let finish!: (value: ReturnType<typeof providers>) => void;
list.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }))
diff --git a/apps/desktop/src/renderer/hooks/useSshCodexProviders.ts b/apps/desktop/src/renderer/hooks/useSshCodexProviders.ts
index ece7d5a24a..6a47c56456 100644
--- a/apps/desktop/src/renderer/hooks/useSshCodexProviders.ts
+++ b/apps/desktop/src/renderer/hooks/useSshCodexProviders.ts
@@ -28,10 +28,17 @@ export function useSshCodexProviders(hostId?: string | null) {
useEffect(() => {
if (!hostId) return;
refresh();
+ // Initial discovery already covers an existing ready connection. Status
+ // snapshots also carry preference/proxy changes; only reconnects reload it.
+ let wasReady = true;
const stop = window.electronAPI.remoteSsh.onStatusChanged((snapshot) => {
if (snapshot.config.id !== hostId) return;
- if (snapshot.status === 'ready') refresh();
+ if (snapshot.status === 'ready') {
+ if (!wasReady) refresh();
+ wasReady = true;
+ }
else {
+ wasReady = false;
++sequence.current;
setState({ key, providers: EMPTY, status: 'error' });
}
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
index 14867f0e7d..af152310fd 100644
--- a/docs/dev-rules/model-catalog-maintenance.md
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -112,8 +112,10 @@ app-server 的完整 `model/list`,不使用控制端 OpenAI 登录或网关目
结果只用于该主机,断连、换主机或换账号后的迟到结果丢弃,不发布到本机公共目录。
新任务从远端清单解析默认模型及推理强度/Fast;已有任务保留原模型和历史,由用户改选。
-`model/list` 不提供的真实窗口保持未知;普通 SSH Codex 切换交给 main 现有窗口保护和回合中延后规则,
-不能因前端尚无用量报告而静默丢弃点击。目录成员资格不等于认证、网络和实际推理已验证。
+`model/list` 不提供的真实窗口保持未知;普通 SSH Codex 切换沿用 main 的窗口策略:
+未知窗口允许切换且不主动重建,已核实的高风险缩窗在远端拒绝,回合中延期。
+不能因前端尚无用量报告而静默丢弃点击。未知窗口不代表已证明切换安全,后续上下文处理仍由原生 Codex 决定。
+目录成员资格不等于认证、网络和实际推理已验证。
实现:`maker-host/ssh-codex-models.ts`、`remote-ssh/codex-model-list.ts`、
`useSshCodexProviders.ts`;回归:`codex-model-list.test.ts`、`sshCodexModels.test.tsx`、
diff --git a/packages/maker-remote-ssh/src/__tests__/remote-agent-installer.test.ts b/packages/maker-remote-ssh/src/__tests__/remote-agent-installer.test.ts
index 9a41dd8615..ed09317e61 100644
--- a/packages/maker-remote-ssh/src/__tests__/remote-agent-installer.test.ts
+++ b/packages/maker-remote-ssh/src/__tests__/remote-agent-installer.test.ts
@@ -58,7 +58,7 @@ describe('remote agent installer', () => {
});
it.each([
- { name: 'legacy standalone', os: 'Darwin', legacy: true, missing: '', ok: true },
+ { name: 'legacy standalone requires upgrade', os: 'Darwin', legacy: true, missing: '', ok: false },
{ name: 'complete macOS package', os: 'Darwin', legacy: false, missing: 'codex-resources/bwrap', ok: true },
{ name: 'complete Linux package', os: 'Linux', legacy: false, missing: '', ok: true },
{ name: 'missing code-mode host', os: 'Darwin', legacy: false, missing: 'bin/codex-code-mode-host', ok: false },
@@ -121,10 +121,54 @@ describe('remote agent installer', () => {
'NPM_PKG="@anthropic-ai/claude-code@$CLAUDE_RELEASE"',
);
expect(calls[1].input).toContain(
- 'Claude Code version ${V%% *} != managed pin $CLAUDE_RELEASE',
+ '$AGENT_KIND version $V does not match managed pin',
);
});
+ it.each([
+ { name: 'legacy standalone', complete: false, version: PINNED_CODEX_RELEASE_VERSION, ready: false },
+ { name: 'old full package', complete: true, version: '0.0.1', ready: false },
+ { name: 'current full package', complete: true, version: PINNED_CODEX_RELEASE_VERSION, ready: true },
+ ])('probe and bootstrap agree on $name readiness', async ({ complete, version, ready }) => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-codex-readiness-'));
+ try {
+ // Simulate the POSIX remote home, never the developer home. All downloads
+ // are stubbed so an upgrade request cannot reach the network in this test.
+ const install = path.join(root, '.xdt-server', 'v1');
+ const current = path.join(install, 'codex-home', 'packages', 'standalone', 'current');
+ const files = complete
+ ? ['codex', 'bin/codex', 'bin/codex-code-mode-host', 'codex-path/rg', 'codex-resources/bwrap', 'codex-package.json']
+ : ['codex'];
+ for (const file of files) {
+ const target = path.join(current, file);
+ mkdirSync(path.dirname(target), { recursive: true });
+ writeFileSync(target, '#!/bin/sh\nprintf "codex-cli ' + version + '\\n"\n');
+ chmodSync(target, 0o755);
+ }
+ writeFileSync(path.join(install, '.installed-codex'), '');
+ const outputs: string[] = [];
+ const host = {
+ exec: async (command: string, opts: { input?: string }) => {
+ const args = [...command.matchAll(/'([^']*)'/g)].map((match) => match[1]);
+ expect(args).toContain(PINNED_CODEX_RELEASE_VERSION);
+ const result = spawnSync('bash', ['-s', '--', ...args], {
+ cwd: root, encoding: 'utf8',
+ input: 'export HOME="$PWD"\ncurl() { return 1; }\nwget() { return 1; }\n' + opts.input,
+ });
+ expect(result.error).toBeUndefined();
+ outputs.push(result.stdout);
+ return { exitCode: result.status, stdout: result.stdout, stderr: result.stderr };
+ },
+ } as Pick<RemoteHost, 'exec'> as RemoteHost;
+ expect((await probeRemoteAgent(host, 'codex')).installed).toBe(ready);
+ expect((await installRemoteAgent(host, 'codex')).ready).toBe(ready);
+ if (!ready) expect(outputs[1]).toContain('INSTALL_START codex-package');
+ else expect(outputs[1]).not.toContain('INSTALL_START');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
it('probes pi binary presence + version match', async () => {
const calls: Array<{ command: string; input: string }> = [];
const host = {
diff --git a/packages/maker-remote-ssh/src/bootstrap/bootstrap-script.ts b/packages/maker-remote-ssh/src/bootstrap/bootstrap-script.ts
index 5b6d5d1f4a..bbf14e2f53 100644
--- a/packages/maker-remote-ssh/src/bootstrap/bootstrap-script.ts
+++ b/packages/maker-remote-ssh/src/bootstrap/bootstrap-script.ts
@@ -131,21 +131,19 @@ export const NODE_DIST_BASE_URL_DEFAULT = 'https://nodejs.org/dist';
export const CODEX_RELEASE_INSTALLER_URL_BASE = 'https://github.com/openai/codex/releases/download';
export const CODEX_LATEST_INSTALLER_URL = 'https://chatgpt.com/codex/install.sh';
-/** Shared by probe and bootstrap. Keep legacy standalone installs usable, but
- * never accept a partially installed full package just because --version runs.
- * The official installer preserves current/codex -> bin/codex for old callers. */
+/** Shared by probe and bootstrap. Legacy standalone and incomplete packages
+ * need an upgrade, even when --version runs. The official installer preserves
+ * current/codex -> bin/codex for existing callers. */
export const VERIFY_CODEX_LAYOUT_SH = String.raw`verify_codex_layout() {
local root
root="$(dirname "$BIN_PATH")"
- if [ -e "$root/codex-package.json" ] || [ -d "$root/bin" ]; then
- [ -f "$root/codex-package.json" ] &&
- [ -x "$root/bin/codex" ] &&
- [ -x "$root/bin/codex-code-mode-host" ] &&
- [ -x "$root/codex-path/rg" ] &&
- [ -d "$root/codex-resources" ] || return 1
- if [ "$(uname -s)" = "Linux" ]; then
- [ -x "$root/codex-resources/bwrap" ] || return 1
- fi
+ [ -f "$root/codex-package.json" ] &&
+ [ -x "$root/bin/codex" ] &&
+ [ -x "$root/bin/codex-code-mode-host" ] &&
+ [ -x "$root/codex-path/rg" ] &&
+ [ -d "$root/codex-resources" ] || return 1
+ if [ "$(uname -s)" = "Linux" ]; then
+ [ -x "$root/codex-resources/bwrap" ] || return 1
fi
}
`;
@@ -347,13 +345,14 @@ verify_binary() {
fi
if [ -n "$V" ] &&
- { [ "$AGENT_KIND" != "claude-code" ] || [ "${'$'}{V%% *}" = "$CLAUDE_RELEASE" ]; }; then
+ { [ "$AGENT_KIND" != "claude-code" ] || [ "${'$'}{V%% *}" = "$CLAUDE_RELEASE" ]; } &&
+ { [ "$AGENT_KIND" != "codex" ] || [ "${'$'}{V##* }" = "$CODEX_RELEASE" ]; }; then
emit "READY $V"
rm -f "$_STDERR_LOG"
return 0
fi
if [ -n "$V" ]; then
- emit "INSTALL_LOG [verify-fail] Claude Code version ${'$'}{V%% *} != managed pin $CLAUDE_RELEASE"
+ emit "INSTALL_LOG [verify-fail] $AGENT_KIND version $V does not match managed pin"
fi
# Diagnostics on failure — these go to INSTALL_LOG so the desktop main process
# logs them (silent install pipeline forwards INSTALL_LOG lines verbatim).
diff --git a/packages/maker-remote-ssh/src/bootstrap/installer.ts b/packages/maker-remote-ssh/src/bootstrap/installer.ts
index 5e08ed296c..7ab4f10065 100644
--- a/packages/maker-remote-ssh/src/bootstrap/installer.ts
+++ b/packages/maker-remote-ssh/src/bootstrap/installer.ts
@@ -193,6 +193,7 @@ set -u
AGENT_KIND="${'$'}{1:-}"
SERVER_VER="${'$'}{2:-v1}"
CLAUDE_RELEASE="${'$'}{3:-}"
+CODEX_RELEASE="${'$'}{4:-}"
case "$AGENT_KIND" in
claude-code) BIN_NAME="claude" ;;
codex) BIN_NAME="codex" ;;
@@ -224,7 +225,8 @@ if [ -f "$SENTINEL" ] && { [ -x "$BIN_PATH" ] || [ -f "$BIN_PATH" ]; }; then
fi
V="$("$BIN_PATH" --version 2>/dev/null | head -1 || true)"
if [ -n "$V" ]; then
- if [ "$AGENT_KIND" != "claude-code" ] || [ "${'$'}{V%% *}" = "$CLAUDE_RELEASE" ]; then
+ if { [ "$AGENT_KIND" != "claude-code" ] || [ "${'$'}{V%% *}" = "$CLAUDE_RELEASE" ]; } &&
+ { [ "$AGENT_KIND" != "codex" ] || [ "${'$'}{V##* }" = "$CODEX_RELEASE" ]; }; then
printf 'READY %s\n' "$V"
exit 0
fi
@@ -240,6 +242,7 @@ printf 'NOT_INSTALLED\n'; exit 0
agentKind,
REMOTE_SERVER_SCHEMA_VERSION,
PINNED_CLAUDE_CODE_VERSION,
+ PINNED_CODEX_RELEASE_VERSION,
].map(shellQuoteArg).join(' ');
const result = await host.exec(`bash -l -s -- ${args}`, {
input: probeScript,