Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

feat(runtime): recover disconnected runtimes and preserve workspace state

wulien-center495400e9cb85
diff --git a/apps/desktop/src/main/bootstrap-controller.ts b/apps/desktop/src/main/bootstrap-controller.ts
index 643eb88f..cc95655d 100644
--- a/apps/desktop/src/main/bootstrap-controller.ts
+++ b/apps/desktop/src/main/bootstrap-controller.ts
@@ -3,7 +3,8 @@ import { EventEmitter } from 'node:events';
import { resolve } from 'node:path';
import type {
DesktopBootstrapState,
- DesktopConnectionConfig
+ DesktopConnectionConfig,
+ DaemonConnection
} from '../shared/types.js';
import {
CodexResolutionError,
@@ -34,6 +35,9 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
private verifiedFingerprint: string | undefined;
private automaticRestarts = 0;
private stableTimer: NodeJS.Timeout | undefined;
+ private healthCheckWork: Promise<void> | undefined;
+ private recoveryWork: Promise<void> | undefined;
+ private stopping = false;
constructor(private readonly input: {
daemon: DaemonManager;
@@ -47,6 +51,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
stickmanRuntimeRoot: string;
defaultProjectRoot: string;
development: boolean;
+ probeHealth?(connection: DaemonConnection): Promise<boolean>;
}) {
super();
input.daemon.on('bootstrap', event => {
@@ -76,8 +81,13 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
this.emit('connection', connection === null ? null : this.rendererConnection());
});
input.daemon.on('exit', event => {
- if (event.reason !== 'unexpected' || this.state.phase === 'failed') return;
- void this.recoverUnexpectedExit();
+ if (
+ event.reason !== 'unexpected'
+ || this.stopping
+ || this.runWork !== undefined
+ || this.state.phase === 'failed'
+ ) return;
+ void this.recoverRuntime('exit');
});
}
@@ -96,6 +106,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
loginShellTask?: LoginShellEnvironmentTask
): Promise<void> {
if (this.runWork !== undefined) return this.runWork;
+ this.stopping = false;
this.runWork = this.startInternal(selectedCodexBin, loginShellTask).finally(() => {
this.runWork = undefined;
});
@@ -123,17 +134,25 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
}
async restartRuntime(): Promise<void> {
+ this.stopping = false;
if (this.resolvedEnvironment === undefined) {
await this.start();
return;
}
- await this.input.daemon.restart(this.daemonStartInput(
- this.resolvedEnvironment,
- false,
- true
- ));
- this.updateState({ phase: 'starting_runtime', error: undefined });
- this.emit('ready');
+ await this.recoverRuntime('manual');
+ }
+
+ reportProxyFailure(connection: DaemonConnection): void {
+ if (
+ this.stopping
+ || this.state.phase !== 'ready'
+ || this.input.daemon.currentConnection !== connection
+ || this.healthCheckWork !== undefined
+ || this.recoveryWork !== undefined
+ ) return;
+ this.healthCheckWork = this.checkRuntimeHealth(connection).finally(() => {
+ this.healthCheckWork = undefined;
+ });
}
markWorkspaceReady(): void {
@@ -161,6 +180,7 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
}
async stop(): Promise<void> {
+ this.stopping = true;
if (this.stableTimer !== undefined) clearTimeout(this.stableTimer);
await this.input.daemon.stop();
}
@@ -275,33 +295,72 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
}
}
- private async recoverUnexpectedExit(): Promise<void> {
+ private async checkRuntimeHealth(connection: DaemonConnection): Promise<void> {
+ const probe = this.input.probeHealth ?? probeDaemonHealth;
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ if (this.stopping || this.input.daemon.currentConnection !== connection) return;
+ const healthy = await probe(connection).catch(() => false);
+ if (healthy) {
+ this.input.logger.info('Runtime proxy failure health probe succeeded', { attempt: attempt + 1 });
+ return;
+ }
+ if (attempt === 0) await new Promise(resolve => setTimeout(resolve, 750));
+ }
+ if (this.stopping || this.input.daemon.currentConnection !== connection) return;
+ this.input.logger.warn('Runtime health probes failed', { pid: this.input.daemon.pid });
+ await this.recoverRuntime('health');
+ }
+
+ private recoverRuntime(reason: 'exit' | 'health' | 'manual'): Promise<void> {
+ if (this.recoveryWork !== undefined) return this.recoveryWork;
+ this.recoveryWork = this.recoverRuntimeInternal(reason).finally(() => {
+ this.recoveryWork = undefined;
+ });
+ return this.recoveryWork;
+ }
+
+ private async recoverRuntimeInternal(reason: 'exit' | 'health' | 'manual'): Promise<void> {
+ if (this.stopping) return;
const environment = this.resolvedEnvironment;
- if (environment === undefined || this.automaticRestarts >= 1) {
+ if (environment === undefined || (reason !== 'manual' && this.automaticRestarts >= 2)) {
this.updateState({
phase: 'failed',
error: {
code: 'DAEMON_RESTART_EXHAUSTED',
- message: '本地运行服务连续退出,请导出诊断后重新检测'
+ message: '本地运行服务未能自动恢复,请手动重启运行服务。'
}
});
return;
}
- this.automaticRestarts += 1;
+ if (reason === 'manual') this.automaticRestarts = 0;
+ else this.automaticRestarts += 1;
+ this.input.logger.warn('Runtime recovery started', {
+ reason,
+ attempt: this.automaticRestarts,
+ pid: this.input.daemon.pid
+ });
this.updateState({
phase: 'starting_daemon',
error: undefined
});
try {
- await this.input.daemon.start(this.daemonStartInput(environment, false, true));
+ const input = this.daemonStartInput(environment, false, true);
+ if (reason === 'exit') await this.input.daemon.start(input);
+ else await this.input.daemon.restart(input);
this.updateState({ phase: 'starting_runtime' });
this.emit('ready');
this.armStableTimer();
+ this.input.logger.info('Runtime recovery completed', { reason, pid: this.input.daemon.pid });
} catch (error) {
+ this.input.logger.error('Runtime recovery failed', {
+ reason,
+ message: error instanceof Error ? error.message : String(error)
+ });
this.updateState({
phase: 'failed',
error: parseBootstrapError(error)
});
+ if (reason === 'manual') throw error;
}
}
@@ -350,6 +409,23 @@ export class BootstrapController extends EventEmitter<BootstrapControllerEvents>
}
}
+async function probeDaemonHealth(connection: DaemonConnection): Promise<boolean> {
+ try {
+ const response = await fetch(`${connection.address}/healthz`, {
+ signal: AbortSignal.timeout(1_500),
+ cache: 'no-store'
+ });
+ if (!response.ok) return false;
+ const payload: unknown = await response.json();
+ return typeof payload === 'object'
+ && payload !== null
+ && 'ok' in payload
+ && payload.ok === true;
+ } catch {
+ return false;
+ }
+}
+
function isWorkspaceError(
error: unknown
): error is Error & { code: string } {
diff --git a/apps/desktop/src/main/daemon-manager.ts b/apps/desktop/src/main/daemon-manager.ts
index 424e682a..a75747ef 100644
--- a/apps/desktop/src/main/daemon-manager.ts
+++ b/apps/desktop/src/main/daemon-manager.ts
@@ -280,7 +280,12 @@ export class DaemonManager extends EventEmitter<DaemonManagerEvents> {
}
}
await this.terminateKnownCodexProcesses(true);
- await settlesWithin(exited, 1_000);
+ if (!await settlesWithin(exited, 1_000)) {
+ throw new DaemonStartError(
+ 'DAEMON_STOP_FAILED',
+ '旧的本地运行服务未确认退出,已取消启动替代进程'
+ );
+ }
}
private async terminateKnownCodexProcesses(force: boolean): Promise<void> {
diff --git a/apps/desktop/src/main/main.ts b/apps/desktop/src/main/main.ts
index 92dd7294..02268dde 100644
--- a/apps/desktop/src/main/main.ts
+++ b/apps/desktop/src/main/main.ts
@@ -228,6 +228,7 @@ async function launchDesktop(): Promise<void> {
webRoot,
bootstrapRoot,
getConnection: () => daemon.currentConnection,
+ onTransportFailure: connection => bootstrap?.reportProxyFailure(connection),
logger
});
registerIpcHandlers({
@@ -257,7 +258,8 @@ async function launchDesktop(): Promise<void> {
windowManager?.send(desktopIpc.connectionChanged, connection);
});
bootstrap.on('ready', () => {
- void loadWorkspace();
+ if (workspaceLoaded) bootstrap?.markWorkspaceReady();
+ else void loadWorkspace();
});
bootstrapSurfaceReady = windowManager.loadBootstrap();
@@ -397,8 +399,14 @@ function registerIpcHandlers(input: {
return result.filePaths[0] ?? null;
});
handle(desktopIpc.restartRuntime, input.development, async () => {
- await input.bootstrap.restartRuntime();
- return ok();
+ try {
+ await input.bootstrap.restartRuntime();
+ return input.bootstrap.currentState.phase === 'ready'
+ ? ok()
+ : failed(input.bootstrap.currentState.error?.message ?? '本地运行服务重启失败');
+ } catch (error) {
+ return failed(error instanceof Error ? error.message : String(error));
+ }
});
handle(desktopIpc.reloadWorkspace, input.development, async () => {
await input.reloadWorkspace();
diff --git a/apps/desktop/src/main/protocol-handler.ts b/apps/desktop/src/main/protocol-handler.ts
index d8c1783c..6ead83b7 100644
--- a/apps/desktop/src/main/protocol-handler.ts
+++ b/apps/desktop/src/main/protocol-handler.ts
@@ -9,7 +9,8 @@ import {
createRuntimeProxyTarget,
isStreamingRuntimeUploadRequest,
isRuntimeRequestUrl,
- readBoundedRequestBody
+ readBoundedRequestBody,
+ runtimeProxyErrorDetails
} from './runtime-proxy.js';
export function registerPrivilegedSchemes(): void {
@@ -32,12 +33,13 @@ export async function installProtocolHandler(input: {
webRoot: string;
bootstrapRoot: string;
getConnection(): DaemonConnection | undefined;
+ onTransportFailure?(connection: DaemonConnection): void;
logger: DesktopLogger;
}): Promise<void> {
await protocol.handle('opencreator-app', async request => {
const url = new URL(request.url);
if (isRuntimeRequestUrl(url)) {
- return await proxyRuntimeRequest(request, url, input.getConnection(), input.logger);
+ return await proxyRuntimeRequest(request, url, input.getConnection(), input.logger, input.onTransportFailure);
}
if (url.hostname === 'app') {
return await staticResponse(input.webRoot, request, true);
@@ -53,15 +55,26 @@ async function proxyRuntimeRequest(
request: Request,
url: URL,
connection: DaemonConnection | undefined,
- logger: DesktopLogger
+ logger: DesktopLogger,
+ onTransportFailure?: (connection: DaemonConnection) => void
): Promise<Response> {
if (connection === undefined) {
+ logger.warnRateLimited('runtime-proxy-unavailable', 'Runtime proxy connection unavailable', {
+ method: request.method,
+ path: url.pathname
+ }, 5_000);
return jsonError(503, 'RUNTIME_UNAVAILABLE', 'OpenCreator Runtime is not ready');
}
+ const startedAt = performance.now();
+ let phase = 'target';
+ let daemonPort: string | undefined;
try {
const target = createRuntimeProxyTarget(url, connection.address);
+ daemonPort = target.port;
+ phase = 'headers';
const headers = createRuntimeProxyHeaders(request.headers, connection.token);
const streamsUpload = isStreamingRuntimeUploadRequest(target, request);
+ phase = 'body';
const body = request.method === 'GET' || request.method === 'HEAD'
? undefined
: streamsUpload
@@ -75,23 +88,44 @@ async function proxyRuntimeRequest(
signal: request.signal
};
if (streamsUpload && body !== undefined) upstreamRequest.duplex = 'half';
+ phase = 'fetch';
const upstream = await fetch(target.toString(), upstreamRequest);
- return relayRuntimeResponse(upstream, logger);
+ return relayRuntimeResponse(upstream, logger, {
+ method: request.method,
+ path: url.pathname,
+ daemonPort,
+ startedAt,
+ connection,
+ onTransportFailure
+ });
} catch (error) {
if (error instanceof RuntimeProxyError) {
return jsonError(error.status, error.code, error.message);
}
logger.warn('Runtime proxy request failed', {
+ method: request.method,
path: url.pathname,
- message: error instanceof Error ? error.message : String(error)
+ phase,
+ durationMs: Math.round(performance.now() - startedAt),
+ daemonPort,
+ errors: runtimeProxyErrorDetails(error)
});
+ if (phase === 'fetch' && !request.signal.aborted) onTransportFailure?.(connection);
return jsonError(502, 'RUNTIME_PROXY_FAILED', 'Runtime request failed');
}
}
function relayRuntimeResponse(
upstream: Response,
- logger: DesktopLogger
+ logger: DesktopLogger,
+ context: {
+ method: string;
+ path: string;
+ daemonPort: string;
+ startedAt: number;
+ connection: DaemonConnection;
+ onTransportFailure?: (connection: DaemonConnection) => void;
+ }
): Response {
const headers = new Headers(upstream.headers);
for (const name of [
@@ -134,8 +168,14 @@ function relayRuntimeResponse(
} catch (error) {
release();
logger.warn('Runtime proxy response stream failed', {
- message: error instanceof Error ? error.message : String(error)
+ method: context.method,
+ path: context.path,
+ phase: 'response-stream',
+ durationMs: Math.round(performance.now() - context.startedAt),
+ daemonPort: context.daemonPort,
+ errors: runtimeProxyErrorDetails(error)
});
+ context.onTransportFailure?.(context.connection);
controller.error(error);
}
},
diff --git a/apps/desktop/src/main/runtime-proxy.ts b/apps/desktop/src/main/runtime-proxy.ts
index 71e1201d..893fb55b 100644
--- a/apps/desktop/src/main/runtime-proxy.ts
+++ b/apps/desktop/src/main/runtime-proxy.ts
@@ -6,6 +6,59 @@ const CREATOR_SOURCE_UPLOAD_PATH =
export const MAX_RUNTIME_REQUEST_BODY_BYTES = 10 * 1024 * 1024;
+export type RuntimeProxyErrorDetail = {
+ name?: string;
+ code?: string;
+ errno?: number;
+ syscall?: string;
+};
+
+export function runtimeProxyErrorDetails(error: unknown): RuntimeProxyErrorDetail[] {
+ const details: RuntimeProxyErrorDetail[] = [];
+ const pending: Array<{ value: unknown; depth: number }> = [{ value: error, depth: 0 }];
+ const seen = new Set<object>();
+
+ while (pending.length > 0 && details.length < 8) {
+ const { value, depth } = pending.shift()!;
+ if (typeof value !== 'object' || value === null || seen.has(value)) continue;
+ seen.add(value);
+ try {
+ const entry = value as Record<string, unknown>;
+ const name = entry.name;
+ const code = entry.code;
+ const errno = entry.errno;
+ const syscall = entry.syscall;
+ const detail: RuntimeProxyErrorDetail = {};
+ if (typeof name === 'string' && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name)) {
+ detail.name = name;
+ }
+ if (typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code)) {
+ detail.code = code;
+ }
+ if (typeof errno === 'number' && Number.isSafeInteger(errno)) {
+ detail.errno = errno;
+ }
+ if (typeof syscall === 'string' && /^[a-z][a-z0-9_]{0,31}$/.test(syscall)) {
+ detail.syscall = syscall;
+ }
+ details.push(detail);
+
+ if (depth >= 3) continue;
+ pending.push({ value: entry.cause, depth: depth + 1 });
+ const errors = entry.errors;
+ if (Array.isArray(errors)) {
+ for (let index = 0; index < Math.min(errors.length, 8); index += 1) {
+ pending.push({ value: errors[index], depth: depth + 1 });
+ }
+ }
+ } catch {
+ // Diagnostic extraction must not replace the original proxy failure.
+ }
+ }
+
+ return details;
+}
+
export class RuntimeProxyError extends Error {
constructor(
readonly status: number,
diff --git a/apps/desktop/test/bootstrap-recovery.test.ts b/apps/desktop/test/bootstrap-recovery.test.ts
new file mode 100644
index 00000000..8bb9d90e
--- /dev/null
+++ b/apps/desktop/test/bootstrap-recovery.test.ts
@@ -0,0 +1,116 @@
+import { EventEmitter } from 'node:events';
+import { describe, expect, it, vi } from 'vitest';
+import { BootstrapController } from '../src/main/bootstrap-controller.js';
+import type { DaemonManager, DaemonStartInput } from '../src/main/daemon-manager.js';
+import type { DesktopLogger } from '../src/main/logger.js';
+import type { SettingsStore } from '../src/main/settings-store.js';
+import type { DaemonConnection } from '../src/shared/types.js';
+
+vi.mock('../src/main/codex-resolver.js', async importOriginal => ({
+ ...await importOriginal<typeof import('../src/main/codex-resolver.js')>(),
+ resolveCodexEnvironment: vi.fn(async () => ({
+ codexBin: 'codex',
+ codexHome: 'codex-home',
+ defaultCwd: '.',
+ env: {},
+ source: 'bundled',
+ version: 'test',
+ commit: null,
+ runtimeRoot: null
+ }))
+}));
+
+class FakeDaemon extends EventEmitter {
+ connection: DaemonConnection | undefined;
+ get currentConnection() { return this.connection; }
+ get pid() { return 1234; }
+ start = vi.fn(async (_input: DaemonStartInput) => {
+ this.connection = { address: 'http://127.0.0.1:60764', token: 'test' };
+ this.emit('connection', this.connection);
+ return this.connection;
+ });
+ stop = vi.fn(async () => {
+ this.connection = undefined;
+ this.emit('connection', null);
+ });
+ restart = vi.fn(async (input: DaemonStartInput) => {
+ await this.stop();
+ return await this.start(input);
+ });
+}
+
+function setup(probeHealth: (connection: DaemonConnection) => Promise<boolean>) {
+ const daemon = new FakeDaemon();
+ const logger: DesktopLogger = {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ warnRateLimited: vi.fn(),
+ flush: vi.fn(async () => undefined)
+ };
+ const controller = new BootstrapController({
+ daemon: daemon as unknown as DaemonManager,
+ settings: { read: () => ({ codexRuntimeMode: 'bundled' }) } as SettingsStore,
+ logger,
+ daemonEntryPath: 'daemon.js',
+ appHome: '.',
+ dataDir: '.',
+ codexRuntimeRoot: '.',
+ creatorRuntimeRoot: '.',
+ stickmanRuntimeRoot: '.',
+ defaultProjectRoot: '.',
+ development: true,
+ probeHealth
+ });
+ controller.on('ready', () => controller.markWorkspaceReady());
+ return { controller, daemon, logger };
+}
+
+describe('Desktop Runtime recovery', () => {
+ it('keeps a healthy daemon running after a transient proxy failure', async () => {
+ const probeHealth = vi.fn(async () => true);
+ const { controller, daemon } = setup(probeHealth);
+ await controller.start();
+
+ controller.reportProxyFailure(daemon.currentConnection!);
+ await vi.waitFor(() => expect(probeHealth).toHaveBeenCalledTimes(1));
+ expect(daemon.restart).not.toHaveBeenCalled();
+ expect(controller.currentState.phase).toBe('ready');
+ await controller.stop();
+ });
+
+ it('restarts once after two failed probes despite concurrent request failures', async () => {
+ const probeHealth = vi.fn(async () => false);
+ const { controller, daemon } = setup(probeHealth);
+ await controller.start();
+
+ const connection = daemon.currentConnection!;
+ controller.reportProxyFailure(connection);
+ controller.reportProxyFailure(connection);
+ await vi.waitFor(() => expect(daemon.restart).toHaveBeenCalledTimes(1), { timeout: 2_000 });
+ expect(probeHealth).toHaveBeenCalledTimes(2);
+ expect(controller.currentState.phase).toBe('ready');
+ await controller.stop();
+ });
+
+ it('bounds automatic restarts and still permits manual recovery', async () => {
+ const { controller, daemon } = setup(vi.fn(async () => false));
+ await controller.start();
+
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ daemon.connection = undefined;
+ daemon.emit('connection', null);
+ daemon.emit('exit', { code: 1, reason: 'unexpected' });
+ await vi.waitFor(() => expect(controller.currentState.phase).toBe(
+ attempt < 2 ? 'ready' : 'failed'
+ ));
+ }
+ expect(daemon.start).toHaveBeenCalledTimes(3);
+ expect(controller.currentState.error?.code).toBe('DAEMON_RESTART_EXHAUSTED');
+
+ await controller.restartRuntime();
+ expect(daemon.restart).toHaveBeenCalledTimes(1);
+ expect(controller.currentState.phase).toBe('ready');
+ await controller.stop();
+ });
+});
diff --git a/apps/desktop/test/runtime-proxy-logging.test.ts b/apps/desktop/test/runtime-proxy-logging.test.ts
new file mode 100644
index 00000000..423dfe14
--- /dev/null
+++ b/apps/desktop/test/runtime-proxy-logging.test.ts
@@ -0,0 +1,109 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { protocol } from 'electron';
+import type { DesktopLogger } from '../src/main/logger.js';
+import { installProtocolHandler } from '../src/main/protocol-handler.js';
+
+vi.mock('electron', () => ({
+ protocol: {
+ handle: vi.fn(),
+ registerSchemesAsPrivileged: vi.fn()
+ }
+}));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.mocked(protocol.handle).mockClear();
+});
+
+describe('Desktop Runtime proxy logging', () => {
+ it('rate-limits logs while the daemon connection is unavailable', async () => {
+ const logger = fakeLogger();
+ await installProtocolHandler({
+ webRoot: '',
+ bootstrapRoot: '',
+ getConnection: () => undefined,
+ logger
+ });
+
+ const handler = vi.mocked(protocol.handle).mock.calls[0]![1];
+ const response = await handler(new Request(
+ 'opencreator-app://app/.opencreator/runtime/tasks?token=private-value'
+ ));
+
+ expect(response.status).toBe(503);
+ expect(logger.warnRateLimited).toHaveBeenCalledWith(
+ 'runtime-proxy-unavailable',
+ 'Runtime proxy connection unavailable',
+ { method: 'GET', path: '/.opencreator/runtime/tasks' },
+ 5_000
+ );
+ });
+
+ it('logs the transport error chain without exposing query strings or messages', async () => {
+ const cause = Object.assign(new Error('private-value'), {
+ code: 'ECONNREFUSED',
+ errno: -4078,
+ syscall: 'connect'
+ });
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('fetch failed', { cause })));
+ const logger = fakeLogger();
+ const onTransportFailure = vi.fn();
+ await installProtocolHandler({
+ webRoot: '',
+ bootstrapRoot: '',
+ getConnection: () => ({ address: 'http://127.0.0.1:60764', token: 'private-value' }),
+ onTransportFailure,
+ logger
+ });
+
+ const handler = vi.mocked(protocol.handle).mock.calls[0]![1];
+ const response = await handler(new Request(
+ 'opencreator-app://app/.opencreator/runtime/healthz?token=private-value'
+ ));
+
+ expect(response.status).toBe(502);
+ expect(await response.json()).toEqual({
+ error: { code: 'RUNTIME_PROXY_FAILED', message: 'Runtime request failed' }
+ });
+ expect(logger.warn).toHaveBeenCalledWith('Runtime proxy request failed', {
+ method: 'GET',
+ path: '/.opencreator/runtime/healthz',
+ phase: 'fetch',
+ durationMs: expect.any(Number),
+ daemonPort: '60764',
+ errors: [
+ { name: 'TypeError' },
+ { name: 'Error', code: 'ECONNREFUSED', errno: -4078, syscall: 'connect' }
+ ]
+ });
+ expect(JSON.stringify(vi.mocked(logger.warn).mock.calls)).not.toContain('private-value');
+ expect(onTransportFailure).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not restart for an upstream application error', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('error', { status: 500 })));
+ const onTransportFailure = vi.fn();
+ await installProtocolHandler({
+ webRoot: '',
+ bootstrapRoot: '',
+ getConnection: () => ({ address: 'http://127.0.0.1:60764', token: 'test' }),
+ onTransportFailure,
+ logger: fakeLogger()
+ });
+
+ const handler = vi.mocked(protocol.handle).mock.calls[0]![1];
+ const response = await handler(new Request('opencreator-app://app/.opencreator/runtime/tasks'));
+ expect(response.status).toBe(500);
+ expect(onTransportFailure).not.toHaveBeenCalled();
+ });
+});
+
+function fakeLogger(): DesktopLogger {
+ return {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ warnRateLimited: vi.fn(),
+ flush: vi.fn(async () => undefined)
+ };
+}
diff --git a/apps/desktop/test/runtime-proxy.test.ts b/apps/desktop/test/runtime-proxy.test.ts
index cab72a54..565e718d 100644
--- a/apps/desktop/test/runtime-proxy.test.ts
+++ b/apps/desktop/test/runtime-proxy.test.ts
@@ -4,10 +4,58 @@ import {
createRuntimeProxyTarget,
isStreamingRuntimeUploadRequest,
isRuntimeRequestUrl,
- readBoundedRequestBody
+ readBoundedRequestBody,
+ runtimeProxyErrorDetails
} from '../src/main/runtime-proxy.js';
describe('Desktop Runtime proxy', () => {
+ it('records nested connection error codes without logging messages or secrets', () => {
+ const cause = Object.assign(new Error('https://example.com?token=private-value'), {
+ code: 'ECONNREFUSED',
+ errno: -4078,
+ syscall: 'connect',
+ address: 'private-value'
+ });
+ const error = new TypeError('fetch failed', { cause });
+
+ expect(runtimeProxyErrorDetails(error)).toEqual([
+ { name: 'TypeError' },
+ { name: 'Error', code: 'ECONNREFUSED', errno: -4078, syscall: 'connect' }
+ ]);
+ expect(JSON.stringify(runtimeProxyErrorDetails(error))).not.toContain('private-value');
+ });
+
+ it('bounds aggregate errors and cyclic causes', () => {
+ const root = new AggregateError([
+ Object.assign(new Error('secret'), { code: 'ETIMEDOUT' }),
+ Object.assign(new Error('secret'), { code: 'ECONNRESET' })
+ ], 'secret');
+ Object.assign(root, { cause: root });
+
+ expect(runtimeProxyErrorDetails(root)).toEqual([
+ { name: 'AggregateError' },
+ { name: 'Error', code: 'ETIMEDOUT' },
+ { name: 'Error', code: 'ECONNRESET' }
+ ]);
+ });
+
+ it('rejects untrusted free-text fields in error metadata', () => {
+ expect(runtimeProxyErrorDetails({
+ name: 'Error https://example.com?key=secret',
+ code: 'ECONNREFUSED?token=secret',
+ syscall: 'connect secret',
+ errno: 'secret',
+ cause: new Error('secret')
+ })).toEqual([{}, { name: 'Error' }]);
+ });
+
+ it('does not throw when inspecting a hostile error getter', () => {
+ const error = Object.defineProperty(new Error('secret'), 'code', {
+ get() { throw new Error('secret'); }
+ });
+ expect(() => runtimeProxyErrorDetails(error)).not.toThrow();
+ });
+
it('matches only the exact runtime route prefix', () => {
expect(isRuntimeRequestUrl(new URL('opencreator-app://app/.opencreator/runtime'))).toBe(true);
expect(isRuntimeRequestUrl(new URL('opencreator-app://app/.opencreator/runtime/healthz'))).toBe(true);
diff --git a/apps/web/src/app/App.test.tsx b/apps/web/src/app/App.test.tsx
index 4c183a74..b7050b64 100644
--- a/apps/web/src/app/App.test.tsx
+++ b/apps/web/src/app/App.test.tsx
@@ -7111,6 +7111,68 @@ describe('App', () => {
expect(request.prompt).not.toContain('model catalog unavailable');
});
+ it('keeps the current conversation and draft while reconnecting without a page reload', async () => {
+ const hostBridge = createHostBridge();
+ hostBridge.kind = 'desktop';
+ let available = true;
+ let notifyConnection: ((config: { baseUrl: string; token: string } | null) => void) | undefined;
+ const config = { baseUrl: 'http://127.0.0.1:60764', token: 'runtime-token' };
+ hostBridge.readConnectionConfig = async () => available ? config : null;
+ hostBridge.subscribeConnectionConfig = listener => {
+ notifyConnection = listener;
+ return () => { notifyConnection = undefined; };
+ };
+ hostBridge.restartRuntime = vi.fn(async () => ({ ok: true as const }));
+ let failedHealthChecks = 0;
+ const runtimeFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const projectResponse = handleDefaultProjectApiRequest(url, init);
+ if (projectResponse !== undefined) return projectResponse;
+ if (url.endsWith('/healthz')) {
+ if (!available) {
+ failedHealthChecks += 1;
+ return jsonResponse({ error: { code: 'RUNTIME_UNAVAILABLE', message: 'offline' } }, { status: 503 });
+ }
+ return jsonResponse({ ok: true });
+ }
+ if (url.endsWith('/codex/status')) return jsonResponse(createCodexStatusResponse());
+ if (url.endsWith('/schedules')) return jsonResponse({ schedules: [] });
+ if (url.endsWith('/tasks?status=all&limit=50')) return jsonResponse({ tasks: [], hasMore: false });
+ if (url.endsWith('/threads?status=active&limit=50')) {
+ return jsonResponse({ threads: [createThreadResponse({ id: 'thread_kept', title: '保留的会话' })] });
+ }
+ if (url.endsWith('/threads/thread_kept/history?limit=50')) {
+ return jsonResponse({ threadId: 'thread_kept', codexThreadId: null, items: [] });
+ }
+ if (url.endsWith('/threads/thread_kept/runs?limit=50')) return jsonResponse({ runs: [] });
+ if (url.endsWith('/threads/thread_kept')) {
+ return jsonResponse({ thread: createThreadResponse({ id: 'thread_kept', title: '保留的会话' }) });
+ }
+ return jsonResponse({});
+ };
+
+ render(<App fileService={createFileService()} hostBridge={hostBridge} runtimeFetch={runtimeFetch} />);
+ await screen.findByRole('status', { name: '本地运行内核正常' });
+ const conversation = await screen.findByRole('button', { name: /保留的会话/ });
+ fireEvent.click(conversation);
+ const composer = await screen.findByRole('textbox', { name: '输入任务' });
+ fireEvent.change(composer, { target: { value: '恢复后继续这段草稿' } });
+
+ available = false;
+ act(() => notifyConnection?.(null));
+ expect(screen.getByRole('button', { name: /保留的会话/ })).toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: '输入任务' })).toHaveValue('恢复后继续这段草稿');
+ expect(screen.getByRole('button', { name: '重启本地服务' })).toBeInTheDocument();
+ await waitFor(() => expect(failedHealthChecks).toBeGreaterThan(0));
+
+ available = true;
+ await waitFor(() => expect(screen.getByRole('status', { name: '本地运行内核正常' })).toBeInTheDocument(), {
+ timeout: 4_000
+ });
+ expect(screen.getByRole('textbox', { name: '输入任务' })).toHaveValue('恢复后继续这段草稿');
+ expect(screen.getByRole('button', { name: /保留的会话/ })).toBeInTheDocument();
+ });
+
it('restores the recent model config for a new conversation', async () => {
const user = userEvent.setup();
writeRecentModelConfig({
diff --git a/apps/web/src/app/AppController.tsx b/apps/web/src/app/AppController.tsx
index dfd6f2b5..1d96c045 100644
--- a/apps/web/src/app/AppController.tsx
+++ b/apps/web/src/app/AppController.tsx
@@ -33,6 +33,7 @@ import type {
import { FolderInput } from 'lucide-react';
import { lazy, Suspense, useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { AppLayout } from '../components/layout/AppLayout.js';
+import { RuntimeConnectionNotice, RuntimeConnectionProvider } from './runtime-connection-context.js';
import { DesktopWindowControls } from '../components/layout/DesktopWindowControls.js';
import { beginPaneResize } from '../components/layout/pane-resize-2026-07-29.js';
import { Timeline, type TimelineHandle } from '../components/timeline/Timeline.js';
@@ -348,6 +349,8 @@ export function AppController(props: AppControllerProps) {
status: 'disconnected',
message: '正在等待本地服务'
});
+ const [runtimeRestarting, setRuntimeRestarting] = useState(false);
+ const [runtimeRestartError, setRuntimeRestartError] = useState<string>();
const [runDiagnosticsById, setRunDiagnosticsById] = useState<Record<string, RunDiagnosticsResponse | undefined>>({});
const [runAttachmentsById, setRunAttachmentsById] = useState<Record<string, AttachmentResponse[] | undefined>>({});
const [runContextById, setRunContextById] = useState<Record<string, RunContextResponse | undefined>>({});
@@ -1086,7 +1089,6 @@ export function AppController(props: AppControllerProps) {
taskBaselineReadyRef.current = false;
if (connectionState.status !== 'connected' || taskService === null) {
- setRuntimeTasks([]);
return () => {
canceled = true;
};
@@ -1162,8 +1164,7 @@ export function AppController(props: AppControllerProps) {
useEffect(() => {
if (connectionState.status === 'connected') return;
- stopAllRunEventSubscriptions(false);
- dispatchRunRegistry({ type: 'reset' });
+ stopAllRunEventSubscriptions();
setRunsLoadingThreadId(undefined);
setRunsLoadedThreadId(undefined);
}, [connectionState.status]);
@@ -1224,9 +1225,11 @@ export function AppController(props: AppControllerProps) {
const unsubscribe = hostBridge.subscribeConnectionConfig?.(config => {
if (canceled) return;
connectionConfigVersionRef.current += 1;
- setConnectionConfig(config);
if (config === null) {
+ setConnectionConfig(current => current === null ? null : { ...current });
setConnectionState({ status: 'disconnected', message: '正在恢复本地服务连接' });
+ } else {
+ setConnectionConfig(config);
}
});
@@ -1236,6 +1239,18 @@ export function AppController(props: AppControllerProps) {
};
}, [hostBridge]);
+ useEffect(() => {
+ if (connectionConfig !== null) return;
+ let canceled = false;
+ const timer = window.setInterval(() => {
+ readHostRuntimeConfig(connectionConfigVersionRef.current, () => canceled);
+ }, 2_000);
+ return () => {
+ canceled = true;
+ window.clearInterval(timer);
+ };
+ }, [connectionConfig, hostBridge]);
+
useEffect(() => {
let canceled = false;
@@ -1258,6 +1273,7 @@ export function AppController(props: AppControllerProps) {
useEffect(() => {
let canceled = false;
+ let timer: number | undefined;
if (connectionService === null) {
setConnectionState({ status: 'disconnected', message: '正在等待本地服务' });
@@ -1266,19 +1282,24 @@ export function AppController(props: AppControllerProps) {
};
}
- connectionService
- .check()
- .then(nextState => {
- if (canceled) return;
- setConnectionState(nextState);
- })
- .catch(() => {
- if (canceled) return;
- setConnectionState({ status: 'disconnected', message: '本地服务连接失败' });
- });
+ const check = async () => {
+ let nextState: ConnectionState;
+ try {
+ nextState = await connectionService.check();
+ } catch {
+ nextState = { status: 'disconnected', message: '本地服务连接失败' };
+ }
+ if (canceled) return;
+ setConnectionState(nextState);
+ if (nextState.status !== 'invalid_token') {
+ timer = window.setTimeout(check, nextState.status === 'connected' ? 5_000 : 2_000);
+ }
+ };
+ void check();
return () => {
canceled = true;
+ if (timer !== undefined) window.clearTimeout(timer);
};
}, [connectionService]);
@@ -1322,11 +1343,6 @@ export function AppController(props: AppControllerProps) {
|| threadService === null
) {
setRuntimeWorkspaceReady(false);
- if (connectionState.status !== 'connected') {
- setProjects([]);
- setArchivedProjects([]);
- setRuntimeThreads([]);
- }
return () => {
canceled = true;
};
@@ -1336,6 +1352,7 @@ export function AppController(props: AppControllerProps) {
const activeProjectService = projectService;
const activeThreadService = threadService;
async function loadRuntimeWorkspace() {
+ let loaded = false;
try {
const legacyProjects = parseLegacyLocalStorageProjects(
readJsonFromStorage<unknown>(PROJECTS_STORAGE_KEY)
@@ -1388,6 +1405,7 @@ export function AppController(props: AppControllerProps) {
if (canceled) return;
setRuntimeThreads(response.threads);
setThreadLoadError(undefined);
+ loaded = true;
const restoredThreadId = restoredThreadIdRef.current;
restoredThreadIdRef.current = undefined;
@@ -1414,14 +1432,10 @@ export function AppController(props: AppControllerProps) {
}
} catch {
if (canceled) return;
- setProjects([]);
- setArchivedProjects([]);
- setRuntimeThreads([]);
- dispatch({ type: 'set_current_project', projectId: undefined });
setProjectLoadError('无法迁移或加载项目,请稍后重试');
setThreadLoadError(undefined);
} finally {
- if (!canceled) setRuntimeWorkspaceReady(true);
+ if (!canceled) setRuntimeWorkspaceReady(loaded);
}
}
@@ -1435,8 +1449,6 @@ export function AppController(props: AppControllerProps) {
useEffect(() => {
let canceled = false;
if (connectionState.status !== 'connected' || creatorService === null) {
- setCreatorPresets([]);
- setCreatorPresetsError(undefined);
setCreatorPresetsLoading(false);
return () => {
canceled = true;
@@ -1476,10 +1488,6 @@ export function AppController(props: AppControllerProps) {
useEffect(() => {
let canceled = false;
if (connectionState.status !== 'connected' || creatorService === null) {
- if (connectionState.status !== 'connected') {
- setCreatorJobs([]);
- setCreatorJobsError(undefined);
- }
setCreatorJobsLoading(false);
return () => {
canceled = true;
@@ -1515,7 +1523,6 @@ export function AppController(props: AppControllerProps) {
let canceled = false;
if (connectionState.status !== 'connected' || scheduleService === null) {
- if (connectionState.status !== 'connected') setRuntimeSchedules([]);
return () => {
canceled = true;
};
@@ -1526,9 +1533,7 @@ export function AppController(props: AppControllerProps) {
.then(response => {
if (!canceled) setRuntimeSchedules(response.schedules);
})
- .catch(() => {
- if (!canceled) setRuntimeSchedules([]);
- });
+ .catch(() => undefined);
return () => {
canceled = true;
@@ -1844,7 +1849,9 @@ export function AppController(props: AppControllerProps) {
setThreadHistoryLoadError(undefined);
setHistoryLoadingThreadId(selectedThreadId);
setHistoryLoadedThreadId(undefined);
- showTimelineForThread(selectedThreadId, [], false);
+ if (timelineThreadIdRef.current !== selectedThreadId) {
+ showTimelineForThread(selectedThreadId, [], false);
+ }
return;
}
@@ -2303,21 +2310,42 @@ export function AppController(props: AppControllerProps) {
hostBridge
.readConnectionConfig()
.then(config => {
- if (!isCanceled() && connectionConfigVersionRef.current === loadVersion) setConnectionConfig(config);
+ if (!isCanceled() && connectionConfigVersionRef.current === loadVersion) {
+ setConnectionConfig(current => config ?? current);
+ }
})
.catch(() => {
- if (!isCanceled() && connectionConfigVersionRef.current === loadVersion) setConnectionConfig(null);
+ // Keep the last valid service while the host connection is unavailable.
});
}
function retryRuntimeConnection() {
+ setRuntimeRestartError(undefined);
connectionConfigVersionRef.current += 1;
const loadVersion = connectionConfigVersionRef.current;
- setConnectionConfig(null);
+ setConnectionConfig(current => current === null ? null : { ...current });
setConnectionState({ status: 'disconnected', message: '正在等待本地服务' });
readHostRuntimeConfig(loadVersion, () => false);
}
+ async function restartLocalRuntime() {
+ if (hostBridge.restartRuntime === undefined || runtimeRestarting) return;
+ setRuntimeRestarting(true);
+ setRuntimeRestartError(undefined);
+ try {
+ const result = await hostBridge.restartRuntime();
+ if (!result.ok) {
+ setRuntimeRestartError(result.message);
+ return;
+ }
+ retryRuntimeConnection();
+ } catch (error) {
+ setRuntimeRestartError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setRuntimeRestarting(false);
+ }
+ }
+
function handleColorModeChange(mode: ColorMode) {
setColorMode(mode);
applyColorMode(mode);
@@ -4233,6 +4261,7 @@ export function AppController(props: AppControllerProps) {
)
|| selectedPendingRunStart !== undefined
|| selectedRunsLoading
+ || !runtimeWorkspaceReady
|| connectionState.status !== 'connected';
const composerDisabledReason = connectionState.status !== 'connected'
? t('conversation.connectingRuntime')
@@ -4493,6 +4522,7 @@ export function AppController(props: AppControllerProps) {
</div>
) : (
<div className="composer-wrap" onWheel={handleComposerWheel}>
+ <RuntimeConnectionNotice />
{showConversationEmptyState ? (
<ConversationEmptyState />
) : null}
@@ -4795,7 +4825,16 @@ export function AppController(props: AppControllerProps) {
);
return (
- <PageIssueRoutingProvider><div
+ <PageIssueRoutingProvider><RuntimeConnectionProvider value={{
+ status: connectionState.status,
+ waitingForConfig: connectionConfig === null,
+ restarting: runtimeRestarting,
+ restartError: runtimeRestartError,
+ retry: retryRuntimeConnection,
+ ...(hostBridge.restartRuntime === undefined
+ ? {}
+ : { restart: () => void restartLocalRuntime() })
+ }}><div
className="app-drop-shell"
data-integrated-title-bar={
integratedTitleBar?.integratedTitleBar === true ? 'true' : undefined
@@ -4944,7 +4983,7 @@ export function AppController(props: AppControllerProps) {
hiddenCreatorIssues={immersiveWorkspace && props.route.view === 'workbench' && props.route.jobId === undefined}
onAskIssue={askAgentAboutIssue}
/>
- </div></PageIssueRoutingProvider>
+ </div></RuntimeConnectionProvider></PageIssueRoutingProvider>
);
function createDetailPanel() {
diff --git a/apps/web/src/app/runtime-connection-context.test.tsx b/apps/web/src/app/runtime-connection-context.test.tsx
new file mode 100644
index 00000000..3dec70cb
--- /dev/null
+++ b/apps/web/src/app/runtime-connection-context.test.tsx
@@ -0,0 +1,49 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import { LanguageProvider } from '../i18n/LanguageProvider.js';
+import {
+ RuntimeConnectionNotice,
+ RuntimeConnectionProvider,
+ type RuntimeConnectionNoticeState
+} from './runtime-connection-context.js';
+
+function renderNotice(value: RuntimeConnectionNoticeState) {
+ render(
+ <LanguageProvider initialPreference="zh-CN">
+ <RuntimeConnectionProvider value={value}>
+ <RuntimeConnectionNotice />
+ </RuntimeConnectionProvider>
+ </LanguageProvider>
+ );
+}
+
+describe('Runtime connection notice', () => {
+ it('shows only the available browser retry action', () => {
+ const retry = vi.fn();
+ renderNotice({
+ status: 'disconnected',
+ waitingForConfig: false,
+ restarting: false,
+ retry
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: '重试连接' }));
+ expect(retry).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole('button', { name: '重启本地服务' })).not.toBeInTheDocument();
+ });
+
+ it('shows the native restart action when Desktop provides it', () => {
+ const restart = vi.fn();
+ renderNotice({
+ status: 'disconnected',
+ waitingForConfig: true,
+ restarting: false,
+ retry: vi.fn(),
+ restart
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: '重启本地服务' }));
+ expect(restart).toHaveBeenCalledTimes(1);
+ expect(screen.getByText(/当前内容会保留/)).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/app/runtime-connection-context.tsx b/apps/web/src/app/runtime-connection-context.tsx
new file mode 100644
index 00000000..4dedbb20
--- /dev/null
+++ b/apps/web/src/app/runtime-connection-context.tsx
@@ -0,0 +1,60 @@
+import { createContext, useContext, type ReactNode } from 'react';
+import { RefreshCw, RotateCcw, ServerOff } from 'lucide-react';
+import { useLocalizedCopy } from '../i18n/useLocalizedCopy.js';
+
+export type RuntimeConnectionNoticeState = {
+ status: 'connected' | 'disconnected' | 'invalid_token';
+ waitingForConfig: boolean;
+ restarting: boolean;
+ restartError?: string;
+ retry(): void;
+ restart?(): void;
+};
+
+const RuntimeConnectionContext = createContext<RuntimeConnectionNoticeState | null>(null);
+
+export function RuntimeConnectionProvider(props: {
+ value: RuntimeConnectionNoticeState;
+ children: ReactNode;
+}) {
+ return (
+ <RuntimeConnectionContext.Provider value={props.value}>
+ {props.children}
+ </RuntimeConnectionContext.Provider>
+ );
+}
+
+export function RuntimeConnectionNotice() {
+ const state = useContext(RuntimeConnectionContext);
+ const l = useLocalizedCopy();
+ if (state === null || state.status === 'connected') return null;
+
+ return (
+ <div className="runtime-connection-notice" role="status" aria-live="polite">
+ <ServerOff size={16} aria-hidden="true" />
+ <span>{state.status === 'invalid_token'
+ ? l('本地服务授权失效,请检查连接配置。', 'Local Runtime authorization failed. Check the connection settings.')
+ : state.waitingForConfig
+ ? l('正在恢复本地运行服务连接。当前内容会保留。', 'Reconnecting to the local Runtime. Your current work is preserved.')
+ : l('本地运行服务连接中断,正在重试。当前内容会保留。', 'Local Runtime connection lost. Retrying without discarding your work.')}</span>
+ <button type="button" onClick={state.retry} title={l('重试连接', 'Retry connection')}>
+ <RefreshCw size={14} aria-hidden="true" />
+ {l('重试连接', 'Retry connection')}
+ </button>
+ {state.restart === undefined ? null : (
+ <button
+ type="button"
+ onClick={state.restart}
+ disabled={state.restarting}
+ title={l('重启本地服务', 'Restart local Runtime')}
+ >
+ <RotateCcw size={14} aria-hidden="true" />
+ {state.restarting
+ ? l('正在重启', 'Restarting')
+ : l('重启本地服务', 'Restart local Runtime')}
+ </button>
+ )}
+ {state.restartError === undefined ? null : <span role="alert">{state.restartError}</span>}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx b/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx
index 67efe0f9..86591737 100644
--- a/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx
+++ b/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx
@@ -23,6 +23,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import OpenCreatorMark from '../../components/brand/OpenCreatorMark.js';
import { MarkdownRenderer } from '../../components/markdown/MarkdownRenderer.js';
import { useLocalizedCopy } from '../../i18n/useLocalizedCopy.js';
+import { RuntimeConnectionNotice } from '../../app/runtime-connection-context.js';
import { issueConversationText } from '../issues/issue-catalog.js';
import ToolAgentComposer, { type ToolAgentPermission } from './ToolAgentComposer.js';
import {
@@ -263,10 +264,13 @@ export default function CreatorCollaborationPanel(props: {
) : null}
{session === null ? (
- <div className="creator-collaboration-unavailable" role="alert">
- <ServerOff size={16} aria-hidden="true" />
- <p>{l('Creator Runtime 未连接,Agent 不会生成替代回复。', 'Creator Runtime is disconnected. The Agent will not generate substitute responses.')}</p>
- </div>
+ <>
+ <div className="creator-collaboration-unavailable" role="alert">
+ <ServerOff size={16} aria-hidden="true" />
+ <p>{l('Creator Runtime 未连接,Agent 不会生成替代回复。', 'Creator Runtime is disconnected. The Agent will not generate substitute responses.')}</p>
+ </div>
+ <RuntimeConnectionNotice />
+ </>
) : (
<>
<div
@@ -321,6 +325,8 @@ export default function CreatorCollaborationPanel(props: {
);
})}
+ <RuntimeConnectionNotice />
+
{showAgentWorking ? (
<div
className="creator-collaboration-working"
diff --git a/apps/web/src/runtime/client.ts b/apps/web/src/runtime/client.ts
index 52b7af4c..d2066be0 100644
--- a/apps/web/src/runtime/client.ts
+++ b/apps/web/src/runtime/client.ts
@@ -25,8 +25,8 @@ export class RuntimeClient {
this.fetchImpl = input.fetchImpl ?? fetch;
}
- async get<T = unknown>(path: string): Promise<T> {
- return this.request<T>(path, { method: 'GET' });
+ async get<T = unknown>(path: string, options: RuntimeRequestOptions = {}): Promise<T> {
+ return this.request<T>(path, { method: 'GET', signal: options.signal });
}
async rawGet(path: string, options: RuntimeRequestOptions = {}): Promise<Response> {
@@ -58,7 +58,7 @@ export class RuntimeClient {
return this.request<T>(path, { method: 'DELETE' });
}
- async request<T>(path: string, input: { method: string; body?: unknown }): Promise<T> {
+ async request<T>(path: string, input: { method: string; body?: unknown; signal?: AbortSignal }): Promise<T> {
const response = await this.rawRequest(path, input);
const payload = await readSuccessfulJson(response, path);
return payload as T;
diff --git a/apps/web/src/services/connection-service.ts b/apps/web/src/services/connection-service.ts
index f5059daf..62887120 100644
--- a/apps/web/src/services/connection-service.ts
+++ b/apps/web/src/services/connection-service.ts
@@ -23,8 +23,11 @@ export function createConnectionService(client: ClientLike) {
return {
async check(): Promise<ConnectionState> {
try {
- await client.get('/healthz');
- const codexStatus = await client.get<CodexStatusResponse>('/codex/status');
+ await client.get('/healthz', { signal: AbortSignal.timeout(2_000) });
+ const codexStatus = await client.get<CodexStatusResponse>(
+ '/codex/status',
+ { signal: AbortSignal.timeout(2_000) }
+ );
return { status: 'connected', codexStatus };
} catch (error) {
const message = errorMessage(error);
diff --git a/apps/web/src/styles/app.css b/apps/web/src/styles/app.css
index ffab871c..60679eb8 100644
--- a/apps/web/src/styles/app.css
+++ b/apps/web/src/styles/app.css
@@ -3222,6 +3222,43 @@ html.is-pane-resizing * {
background: transparent;
}
+.runtime-connection-notice {
+ width: min(var(--conversation-content-max), 100%);
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px 10px;
+ margin: 0 auto 10px;
+ padding: 8px 0;
+ border-top: 1px solid var(--border-hairline);
+ color: var(--muted);
+ font-size: 13px;
+ line-height: 1.4;
+}
+
+.runtime-connection-notice > span:first-of-type {
+ flex: 1 1 180px;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.runtime-connection-notice button {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ border: 0;
+ padding: 2px 0;
+ background: transparent;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+}
+
+.runtime-connection-notice button:disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+
.conversation-page.is-empty .composer-wrap {
min-height: 0;
align-self: stretch;