Skip to content

Show it a video you love. Get a new video in the same style. An AI crew (Claude Code or Codex) plans, builds and reviews it with you.

Agent probe: async, served stale while refreshing, missing agents re-checked every 30 s

許元豪2b97c3f025be
diff --git a/README.md b/README.md
index 01c2a90..a5175a5 100644
--- a/README.md
+++ b/README.md
@@ -131,6 +131,7 @@ committed. See [`secrets.example.json`](secrets.example.json) for the format.
| `CODEX_SANDBOX` | Codex sandbox mode (default `danger-full-access`, like Claude Code with Bash allowed; `workspace-write` blocks the Chrome renderer) |
| `BUILDERS`, `MAX_AGENTS` | How many agents work on one video at once (default 6), and the limit across all projects (default 12) |
| `PORT` | Web port (default 4318) |
+| `AGENTS_TTL_MS` | How long the detected Claude Code / Codex list is reused (default 300000 = 5 min; a missing agent is re-checked every 30 s; `0` re-checks on every request). Click the agent pill in the header to re-check now. A CLI installed into a new PATH folder still needs a server restart |
| `REELMIMIC_SECRETS` | Path to a different secrets file (legacy: `CLONE_STUDIO_SECRETS`) |
| `UPLOAD_POST_KEY`, `UPLOAD_POST_USER` | Optional. Post a finished video to TikTok, Instagram, YouTube and others with `npm run post-video` (see below); `UPLOAD_POST_API` overrides the API address |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 769cff2..7ff436f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -117,6 +117,7 @@ Claude Code 会自己读到 repo 里的 skills,Codex 会读 `AGENTS.md`,不
| `CODEX_SANDBOX` | Codex 的沙盒模式(默认 `danger-full-access`,和 Claude Code 允许 Bash 时一样;`workspace-write` 会让 Chrome 渲染跑不起来) |
| `BUILDERS`、`MAX_AGENTS` | 一支片同时几个 AI 在做(默认 6)、所有项目加起来最多几个(默认 12) |
| `PORT` | 网站用的端口(默认 4318) |
+| `AGENTS_TTL_MS` | 检测到的 Claude Code / Codex 沿用多久(默认 300000 = 5 分钟;没检测到的每 30 秒重查;`0` 每次都查)。点右上角的 AI 状态可以立刻重查。装到新的 PATH 文件夹的话还是要重启服务器 |
## 文档
diff --git a/README.zh-TW.md b/README.zh-TW.md
index e28cdc6..22cd86c 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -117,6 +117,7 @@ Claude Code 會自己讀到 repo 裡的 skills,Codex 會讀 `AGENTS.md`,不
| `CODEX_SANDBOX` | Codex 的沙盒模式(預設 `danger-full-access`,和 Claude Code 允許 Bash 時一樣;`workspace-write` 會讓 Chrome 渲染跑不起來) |
| `BUILDERS`、`MAX_AGENTS` | 一支片同時幾個 AI 在做(預設 6)、所有專案加起來最多幾個(預設 12) |
| `PORT` | 網站用的埠號(預設 4318) |
+| `AGENTS_TTL_MS` | 偵測到的 Claude Code / Codex 沿用多久(預設 300000 = 5 分鐘;沒偵測到的每 30 秒重查;`0` 每次都查)。點右上角的 AI 狀態可以立刻重查。裝到新的 PATH 資料夾的話還是要重開伺服器 |
## 文件
diff --git a/app/server/agents-cache.test.ts b/app/server/agents-cache.test.ts
index 8823164..ae2114a 100644
--- a/app/server/agents-cache.test.ts
+++ b/app/server/agents-cache.test.ts
@@ -1,40 +1,76 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
-import { createAgentCache } from './agents-cache.ts';
+import { createAgentCache, ttlFromEnv, DEFAULT_TTL_MS, MISS_TTL_MS } from './agents-cache.ts';
import type { AgentStatus } from '../shared/types.ts';
function clock(start = 1_000) {
let t = start;
return { now: () => t, advance: (ms: number) => { t += ms; } };
}
+// A detector whose answers are scripted per call; counts the calls
+function detector(answer: (call: number) => AgentStatus) {
+ const d = { calls: 0, detect: async () => answer(++d.calls) };
+ return d;
+}
+const tick = () => new Promise((r) => setImmediate(r));
-test('reuses the detection inside the ttl', () => {
- const c = clock();
- let calls = 0;
- const detect = (): AgentStatus => { calls += 1; return { claude: `v${calls}`, codex: null }; };
- const status = createAgentCache(detect, 1000, c.now);
- assert.equal(status().claude, 'v1');
+test('reuses the detection inside the ttl', async () => {
+ const c = clock(), d = detector((n) => ({ claude: `v${n}`, codex: 'codex 1' }));
+ const status = createAgentCache(d.detect, 1000, c.now);
+ assert.equal((await status()).claude, 'v1');
c.advance(999);
- assert.equal(status().claude, 'v1');
- assert.equal(calls, 1);
+ assert.equal((await status()).claude, 'v1');
+ assert.equal(d.calls, 1);
});
-test('re-detects once the ttl has passed, so a new CLI shows up without a restart', () => {
- const c = clock();
- let calls = 0;
- const detect = (): AgentStatus => { calls += 1; return { claude: null, codex: calls > 1 ? 'codex 1.0' : null }; };
- const status = createAgentCache(detect, 1000, c.now);
- assert.equal(status().codex, null);
+test('a stale answer is served at once and refreshed in the background', async () => {
+ const c = clock(), d = detector((n) => ({ claude: `v${n}`, codex: 'codex 1' }));
+ const status = createAgentCache(d.detect, 1000, c.now);
+ await status();
c.advance(1000);
- assert.equal(status().codex, 'codex 1.0');
- assert.equal(calls, 2);
+ assert.equal((await status()).claude, 'v1'); // no request waits on the re-probe
+ await tick();
+ assert.equal(d.calls, 2);
+ assert.equal((await status()).claude, 'v2');
+});
+
+test('a missing agent is re-checked sooner, so a new install shows up without a restart', async () => {
+ const c = clock(), d = detector((n) => ({ claude: 'claude 1', codex: n > 1 ? 'codex 1' : null }));
+ const status = createAgentCache(d.detect, DEFAULT_TTL_MS, c.now);
+ assert.equal((await status()).codex, null);
+ c.advance(MISS_TTL_MS);
+ await status();
+ await tick();
+ assert.equal((await status()).codex, 'codex 1');
+});
+
+test('refresh waits for a new probe', async () => {
+ const c = clock(), d = detector((n) => ({ claude: null, codex: n > 1 ? 'codex 1' : null }));
+ const status = createAgentCache(d.detect, DEFAULT_TTL_MS, c.now);
+ await status();
+ assert.equal((await status(true)).codex, 'codex 1');
+});
+
+test('concurrent requests share one probe', async () => {
+ const d = detector(() => ({ claude: 'claude 1', codex: null }));
+ const status = createAgentCache(d.detect, 1000, clock().now);
+ await Promise.all([status(), status(), status(true)]);
+ assert.equal(d.calls, 1);
+});
+
+test('a ttl of zero disables the cache', async () => {
+ const d = detector(() => ({ claude: null, codex: null }));
+ const status = createAgentCache(d.detect, 0, () => 0);
+ await status();
+ await status();
+ assert.equal(d.calls, 2);
});
-test('a ttl of zero disables the cache', () => {
- let calls = 0;
- const detect = (): AgentStatus => { calls += 1; return { claude: null, codex: null }; };
- const status = createAgentCache(detect, 0, () => 0);
- status();
- status();
- assert.equal(calls, 2);
+test('AGENTS_TTL_MS: only a real non-negative number overrides the default', () => {
+ assert.equal(ttlFromEnv(undefined), DEFAULT_TTL_MS);
+ assert.equal(ttlFromEnv(''), DEFAULT_TTL_MS);
+ assert.equal(ttlFromEnv('5m'), DEFAULT_TTL_MS);
+ assert.equal(ttlFromEnv('-1'), DEFAULT_TTL_MS);
+ assert.equal(ttlFromEnv('0'), 0);
+ assert.equal(ttlFromEnv('60000'), 60000);
});
diff --git a/app/server/agents-cache.ts b/app/server/agents-cache.ts
index bae6cf7..04ec22a 100644
--- a/app/server/agents-cache.ts
+++ b/app/server/agents-cache.ts
@@ -1,27 +1,40 @@
// Cache for the installed-agent probe.
//
-// agentStatus() spawns each CLI with --version, which is far too expensive to run on every
-// request and cheap enough to re-run occasionally. It used to be cached for the lifetime of the
-// process, so a Claude Code or Codex installed while the server was running never appeared in the
-// picker until the next restart.
+// agentStatus() spawns each CLI with --version, which is too slow to run on every request. It used to be cached for
+// the lifetime of the process, so a Claude Code or Codex installed while the server was running never appeared in the
+// picker until the next restart. Now:
+// - a stale answer is served at once while a background probe refreshes it (no request waits on a re-probe);
+// - an answer with a missing agent goes stale sooner (MISS_TTL_MS), so a fresh install shows up quickly;
+// - status(true) (GET /api/agents?refresh=1, the header's agent pill) waits for a new probe.
//
// AGENTS_TTL_MS overrides the window; 0 disables the cache (useful when testing the picker).
import { agentStatus } from './agents/index.ts';
import type { AgentStatus } from '../shared/types.ts';
-const DEFAULT_TTL_MS = 5 * 60 * 1000;
+export const DEFAULT_TTL_MS = 5 * 60 * 1000;
+export const MISS_TTL_MS = 30 * 1000;
+
+// Unset, empty or not a non-negative number ('5m', '-1') → the default, never a silently disabled cache
+export function ttlFromEnv(v: string | undefined): number {
+ const n = v === undefined || v.trim() === '' ? NaN : Number(v);
+ return Number.isFinite(n) && n >= 0 ? n : DEFAULT_TTL_MS;
+}
export function createAgentCache(
- detect: () => AgentStatus = agentStatus,
- ttlMs: number = Number(process.env.AGENTS_TTL_MS ?? DEFAULT_TTL_MS),
+ detect: () => Promise<AgentStatus> = agentStatus,
+ ttlMs: number = ttlFromEnv(process.env.AGENTS_TTL_MS),
now: () => number = Date.now,
) {
let cached: AgentStatus | null = null;
let at = 0;
- return function status(): AgentStatus {
- if (cached && ttlMs > 0 && now() - at < ttlMs) return cached;
- cached = detect();
- at = now();
+ let running: Promise<AgentStatus> | null = null;
+ const probe = () => running ??= detect()
+ .then((s) => { cached = s; at = now(); return s; })
+ .finally(() => { running = null; });
+ return async function status(force = false): Promise<AgentStatus> {
+ if (!cached || force || ttlMs === 0) return probe();
+ const ttl = cached.claude && cached.codex ? ttlMs : Math.min(ttlMs, MISS_TTL_MS);
+ if (now() - at >= ttl) probe().catch(() => {}); // refresh in the background, answer with what we have
return cached;
};
}
diff --git a/app/server/agents/index.ts b/app/server/agents/index.ts
index ecafab7..75ff3ce 100644
--- a/app/server/agents/index.ts
+++ b/app/server/agents/index.ts
@@ -20,7 +20,8 @@ import type { AgentEvent, AgentKind, AgentStatus } from '../../shared/types.ts';
const IS_WIN = process.platform === 'win32';
// An old codex-cli can shadow a current one on PATH (e.g. a runtime manager's copy). Prefer CODEX_BIN, then npm's global shim.
const NPM_CODEX = IS_WIN && process.env.APPDATA ? join(process.env.APPDATA, 'npm', 'codex.cmd') : null;
-const CODEX_BIN = process.env.CODEX_BIN || (NPM_CODEX && existsSync(NPM_CODEX) ? NPM_CODEX : 'codex');
+// Resolved per call, not at load, so a codex installed through npm after the server started is found on the next probe
+const codexBin = () => process.env.CODEX_BIN || (NPM_CODEX && existsSync(NPM_CODEX) ? NPM_CODEX : 'codex');
const CLAUDE_TOOLS = 'Bash,Read,Write,Edit,Glob,Grep,Skill,WebFetch,WebSearch,TodoWrite';
export interface AgentRun {
@@ -38,12 +39,22 @@ type Emit = (e: AgentEvent) => void;
// One line of the CLIs' JSON streams; only the fields read below
type Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
-export function agentStatus(): AgentStatus {
- const probe = (cmd: string) => {
- const r = spawnSync(cmd, ['--version'], { shell: IS_WIN, encoding: 'utf8', timeout: 20000 });
- return r.status === 0 ? (r.stdout || '').trim().split('\n')[0] : null;
- };
- return { claude: probe('claude'), codex: probe(CODEX_BIN) };
+// Async: the probe re-runs while agent turns are streaming, and a blocking --version (slow on a cold Windows shell) would stall the server.
+// Note the server keeps the PATH it started with: a CLI installed into a new PATH directory still needs a restart.
+function probe(cmd: string): Promise<string | null> {
+ return new Promise((done) => {
+ let out = '';
+ const child = spawn(cmd, ['--version'], { shell: IS_WIN, stdio: ['ignore', 'pipe', 'ignore'], timeout: 20000 });
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (d: string) => { out += d; });
+ child.on('error', () => done(null));
+ child.on('close', (code) => done(code === 0 ? out.trim().split('\n')[0] || null : null));
+ });
+}
+
+export async function agentStatus(): Promise<AgentStatus> {
+ const [claude, codex] = await Promise.all([probe('claude'), probe(codexBin())]);
+ return { claude, codex };
}
function lines(stream: Readable, onLine: (l: string) => void) {
@@ -98,7 +109,7 @@ export function runAgent({ kind, cwd, prompt, sessionId, onEvent = () => {}, sig
const st: TurnState = { sessionId, text: '', ok: false, cost: null, lastError: '' };
const emit: Emit = (e) => { if (e.type === 'error') st.lastError = e.text; onEvent(e); }; // keep the last error for the job's error card
const isClaude = kind === 'claude';
- const cmd = isClaude ? 'claude' : CODEX_BIN;
+ const cmd = isClaude ? 'claude' : codexBin();
const args = isClaude ? claudeArgs(sessionId) : codexArgs(sessionId, cwd);
// Windows: npm shims (claude.cmd) need a shell; args are fixed literals, the prompt goes through stdin.
const child = spawn(cmd, args, { cwd, shell: IS_WIN, env: { ...process.env, HYPERFRAMES_NO_TELEMETRY: '1', DO_NOT_TRACK: '1' } });
diff --git a/app/server/index.ts b/app/server/index.ts
index 40e49ea..ed66ae6 100644
--- a/app/server/index.ts
+++ b/app/server/index.ts
@@ -27,7 +27,7 @@ const guard = (res: Response, id: string) => { if (!/^[\w-]+$/.test(id) || !exis
// Answers as soon as the server is listening: start.bat / start.sh poll it before opening the browser
app.get('/api/health', (req, res) => res.json({ ok: true }));
const agents = createAgentCache();
-app.get('/api/agents', (req, res) => res.json(agents()));
+app.get('/api/agents', async (req, res) => { res.json(await agents(req.query.refresh === '1')); });
app.get('/api/projects', (req, res) => res.json(J.listJobs()));
// New project: a reference (file upload or URL) + brief + agent, optional music / assets / lyrics files.
diff --git a/app/web/src/App.tsx b/app/web/src/App.tsx
index a753e4e..81a00be 100644
--- a/app/web/src/App.tsx
+++ b/app/web/src/App.tsx
@@ -24,16 +24,17 @@ function useTheme(): [string, () => void] {
export default function App() {
const r = useRoute(), [theme, toggle] = useTheme();
const [agents, setAgents] = useState<Partial<AgentStatus> | undefined>(undefined);
- useEffect(() => { api.agents().then(setAgents).catch(() => setAgents({})); }, []);
+ const loadAgents = (refresh = false) => { setAgents(undefined); api.agents(refresh).then(setAgents).catch(() => setAgents({})); };
+ useEffect(() => loadAgents(), []);
return (
<>
<header className="nav">
<a className="brand" href="#/"><BrandMark />ReelMimic</a>
<span className="sp" />
- <div className="agents-cap" title="已連線的 AI 導演">
+ <button className="agents-cap" title="已連線的 AI 導演(點一下重新偵測)" disabled={agents === undefined} onClick={() => loadAgents(true)}>
<span><i className={`dot ${agents === undefined ? '' : agents?.claude ? 'on' : 'bad'}`} /><span className="lbl">Claude Code</span></span>
<span><i className={`dot ${agents === undefined ? '' : agents?.codex ? 'on' : 'bad'}`} /><span className="lbl">Codex</span></span>
- </div>
+ </button>
<LangMenu />
<button className="icon-btn" onClick={toggle} aria-label="切換外觀"><I n={theme === 'dark' ? 'sun' : 'moon'} /></button>
</header>
diff --git a/app/web/src/api.ts b/app/web/src/api.ts
index adff40f..8141532 100644
--- a/app/web/src/api.ts
+++ b/app/web/src/api.ts
@@ -4,7 +4,7 @@ import type { MessageMeta } from './types.ts';
type Ok = { ok: true };
const j = async <T>(r: Response): Promise<T> => { const d: unknown = await r.json().catch(() => ({})); if (!r.ok) throw new Error((d as { error?: string }).error || r.statusText); return d as T; };
export const api = {
- agents: () => fetch('/api/agents').then(j<AgentStatus>),
+ agents: (refresh = false) => fetch(refresh ? '/api/agents?refresh=1' : '/api/agents').then(j<AgentStatus>),
projects: () => fetch('/api/projects').then(j<ProjectSummary[]>),
project: (id: string) => fetch(`/api/projects/${id}`).then(j<Snapshot>),
create: (form: FormData) => fetch('/api/projects', { method: 'POST', body: form }).then(j<{ id: string }>),