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.
TypeScript agent-skillscodex-clideskop-appdubbingimage-generationlocalizationskillsttsvideo-editingvideo-generationvideo-transcriptionvideo-translation
merge: integrate master into optimize-functions
wulien-center8d73c13e8d3a
diff --cc apps/desktop/src/main/bootstrap-controller.tsindex cc95655d,11a9966a..79077a3c--- a/apps/desktop/src/main/bootstrap-controller.ts+++ b/apps/desktop/src/main/bootstrap-controller.ts@@@ -35,9 -34,9 +35,10 @@@ export class BootstrapController extendprivate verifiedFingerprint: string | undefined;private automaticRestarts = 0;private stableTimer: NodeJS.Timeout | undefined;+ private healthCheckWork: Promise<void> | undefined;private recoveryWork: Promise<void> | undefined;+ private recoveryController: AbortController | undefined;- private stopped = false;+ private stopping = false;constructor(private readonly input: {daemon: DaemonManager;@@@ -51,7 -50,7 +52,8 @@@stickmanRuntimeRoot: string;defaultProjectRoot: string;development: boolean;+ probeHealth?(connection: DaemonConnection): Promise<boolean>;+ automaticRestartDelays?: readonly number[];}) {super();input.daemon.on('bootstrap', event => {@@@ -81,13 -80,11 +83,14 @@@this.emit('connection', connection === null ? null : this.rendererConnection());});input.daemon.on('exit', event => {- if (event.reason !== 'unexpected' || this.state.phase === 'failed' || this.stopped) return;- if (this.recoveryWork !== undefined || this.runWork !== undefined) return;- this.recoveryWork = this.recoverUnexpectedExit().finally(() => {- this.recoveryWork = undefined;- });+ if (+ event.reason !== 'unexpected'+ || this.stopping+ || this.runWork !== undefined++ || this.recoveryWork !== undefined+ || this.state.phase === 'failed'+ ) return;+ void this.recoverRuntime('exit');});}@@@ -134,25 -131,32 +137,31 @@@}async restartRuntime(): Promise<void> {+ if (this.runWork !== undefined) return this.runWork;+ this.recoveryController?.abort();+ if (this.recoveryWork !== undefined) await this.input.daemon.stop();+ await this.recoveryWork;+ if (this.runWork !== undefined) return this.runWork;- this.stopped = false;+ this.stopping = false;if (this.resolvedEnvironment === undefined) {await this.start();+ if (this.state.phase === 'failed') throw new Error(this.state.error?.message ?? '本地服务启动失败');return;}- const environment = this.resolvedEnvironment;- this.updateState({ phase: 'starting_daemon', error: undefined });- this.runWork = (async () => {- try {- await this.input.daemon.restart(this.daemonStartInput(environment, false, true));- this.automaticRestarts = 0;- this.updateState({ phase: 'starting_runtime', error: undefined });- this.emit('ready');- this.armStableTimer();- } catch (error) {- this.updateState({ phase: 'failed', error: parseBootstrapError(error) });- throw error;- }- })().finally(() => { this.runWork = undefined; });- await this.runWork;+ 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 {@@@ -180,9 -184,11 +189,11 @@@}async stop(): Promise<void> {- this.stopped = true;+ this.stopping = true;+ this.recoveryController?.abort();if (this.stableTimer !== undefined) clearTimeout(this.stableTimer);await this.input.daemon.stop();+ await this.recoveryWork;}private async startInternal(@@@ -295,73 -301,36 +306,79 @@@}}- 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 || (reason !== 'manual' && this.automaticRestarts >= 2)) {- this.updateState({- phase: 'failed',- error: {- code: 'DAEMON_RESTART_EXHAUSTED',- message: '本地运行服务未能自动恢复,请手动重启运行服务。'++ if (reason === 'manual') this.automaticRestarts = 0;+ const delays = this.input.automaticRestartDelays ?? [500, 1_500, 3_000];+ const controller = new AbortController();+ this.recoveryController = controller;+ if (this.stableTimer !== undefined) clearTimeout(this.stableTimer);- while (environment !== undefined && this.automaticRestarts < delays.length && !this.stopped) {- const delay = delays[this.automaticRestarts] ?? 3_000;- this.automaticRestarts += 1;++ let manualAttempted = false;++ while (++ environment !== undefined++ && !this.stopping++ && (reason === 'manual' ? !manualAttempted : this.automaticRestarts < delays.length)++ ) {++ const delay = reason === 'manual' ? 0 : delays[this.automaticRestarts] ?? 3_000;++ if (reason === 'manual') manualAttempted = true;++ else this.automaticRestarts += 1;+ this.updateState({ phase: 'starting_daemon', error: undefined });- this.input.logger.info('Recovering local Runtime', { attempt: this.automaticRestarts, delayMs: delay });- await waitForRecovery(delay, controller.signal);- if (controller.signal.aborted || this.stopped) return;++ this.input.logger.info('Recovering local Runtime', { reason, attempt: this.automaticRestarts, delayMs: delay });++ if (reason !== 'manual') await waitForRecovery(delay, controller.signal);++ if (controller.signal.aborted || this.stopping) return;+ try {++ if (reason !== 'exit') {++ await this.input.daemon.stop();++ if (controller.signal.aborted || this.stopping) return;+ }- });- return;+ await this.input.daemon.start(this.daemonStartInput(environment, false, true));- if (controller.signal.aborted || this.stopped) return;++ if (controller.signal.aborted || this.stopping) {++ await this.input.daemon.stop();++ return;++ }+ this.updateState({ phase: 'starting_runtime', error: undefined });+ this.emit('ready');+ this.armStableTimer();+ return;+ } catch (error) {- if (controller.signal.aborted || this.stopped) return;++ if (controller.signal.aborted || this.stopping) return;+ this.input.logger.error('Local Runtime recovery failed', { message: error instanceof Error ? error.message : String(error) });++ if (reason === 'manual') {++ this.updateState({ phase: 'failed', error: parseBootstrapError(error) });++ throw error;++ }+ }}- 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- });- if (controller.signal.aborted || this.stopped) return;++ if (controller.signal.aborted || this.stopping) return;this.updateState({- phase: 'starting_daemon',- error: undefined+ phase: 'failed',+ error: { code: 'DAEMON_RESTART_EXHAUSTED', message: '本地服务多次恢复失败,请在连接提示或设置 → 诊断中重启本地服务。' }});- try {- 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;- }}private daemonStartInput(@@@ -409,23 -378,18 +426,35 @@@}}+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 waitForRecovery(delay: number, signal: AbortSignal): Promise<void> {+ return new Promise(resolve => {+ const finish = () => {+ clearTimeout(timer);+ signal.removeEventListener('abort', finish);+ resolve();+ };+ const timer = setTimeout(finish, delay);+ signal.addEventListener('abort', finish, { once: true });+ });+ }+function isWorkspaceError(error: unknown): error is Error & { code: string } {diff --cc apps/desktop/src/main/protocol-handler.tsindex 6ead83b7,6c3a1ae1..aa7084e5--- a/apps/desktop/src/main/protocol-handler.ts+++ b/apps/desktop/src/main/protocol-handler.ts@@@ -33,13 -38,26 +39,28 @@@ export async function installProtocolHawebRoot: string;bootstrapRoot: string;getConnection(): DaemonConnection | undefined;+ onTransportFailure?(connection: DaemonConnection): void;logger: DesktopLogger;- }): Promise<void> {+ }): Promise<ProtocolHandlerController> {+ let runtimeSuspended = false;+ const activeRequests = new Set<AbortController>();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, input.onTransportFailure);+ if (runtimeSuspended) {+ return jsonError(503, 'RUNTIME_SHUTTING_DOWN', 'OpenCreator Runtime is stopping');+ }+ const controller = new AbortController();+ activeRequests.add(controller);+ return await proxyRuntimeRequest(+ request,+ url,+ input.getConnection(),+ input.logger,+ AbortSignal.any([request.signal, controller.signal]),- () => activeRequests.delete(controller)++ () => activeRequests.delete(controller),++ input.onTransportFailure+ );}if (url.hostname === 'app') {return await staticResponse(input.webRoot, request, true);@@@ -56,25 -84,17 +87,28 @@@ async function proxyRuntimeRequesturl: URL,connection: DaemonConnection | undefined,logger: DesktopLogger,+ signal: AbortSignal,- onComplete: () => void++ onComplete: () => void,+ onTransportFailure?: (connection: DaemonConnection) => void): Promise<Response> {if (connection === undefined) {+ onComplete();+ 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@@@ -85,20 -105,17 +119,25 @@@headers,body,redirect: 'manual',- signal: request.signal+ signal};if (streamsUpload && body !== undefined) upstreamRequest.duplex = 'half';+ phase = 'fetch';- const upstream = await fetch(target.toString(), upstreamRequest);- return relayRuntimeResponse(upstream, logger, {+ signal.throwIfAborted();+ const upstream = await fetchDesktopRequest(target.toString(), upstreamRequest);- return relayRuntimeResponse(upstream, logger, signal, onComplete);++ return relayRuntimeResponse(upstream, logger, signal, onComplete, {+ method: request.method,+ path: url.pathname,+ daemonPort,+ startedAt,+ connection,+ onTransportFailure+ });} catch (error) {+ onComplete();+ if (signal.aborted) {+ return jsonError(503, 'RUNTIME_REQUEST_ABORTED', 'Runtime request was cancelled');+ }if (error instanceof RuntimeProxyError) {return jsonError(error.status, error.code, error.message);}@@@ -118,14 -130,8 +157,16 @@@function relayRuntimeResponse(upstream: Response,logger: DesktopLogger,+ signal: AbortSignal,- onComplete: () => void++ onComplete: () => void,+ 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 [@@@ -166,16 -175,13 +210,19 @@@}controller.enqueue(result.value);} catch (error) {+ if (released) return;release();- logger.warn('Runtime proxy response stream failed', {- 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);+ if (!signal.aborted) {+ 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 --cc apps/desktop/test/bootstrap-controller.test.tsindex 00000000,3623c728..1d538ec3mode 000000,100644..100644--- a/apps/desktop/test/bootstrap-controller.test.ts+++ b/apps/desktop/test/bootstrap-controller.test.ts@@@ -1,0 -1,111 +1,110 @@@+ import { EventEmitter } from 'node:events';+ import { afterEach, describe, expect, it, vi } from 'vitest';+ import { BootstrapController } from '../src/main/bootstrap-controller.js';+ import type { DaemonManager } from '../src/main/daemon-manager.js';+ import type { DesktopLogger } from '../src/main/logger.js';+ import type { SettingsStore } from '../src/main/settings-store.js';++ vi.mock('../src/main/codex-resolver.js', async importOriginal => ({+ ...await importOriginal<typeof import('../src/main/codex-resolver.js')>(),+ resolveCodexEnvironment: vi.fn(async () => ({+ codexBin: '/test/codex', codexHome: '/test/home', defaultCwd: '/test/project',+ env: {}, source: 'bundled', version: '1.0', commit: null, runtimeRoot: '/test/runtime'+ }))+ }));++ afterEach(() => vi.useRealTimers());++ function fixture() {+ const daemon = new EventEmitter() as EventEmitter & {+ start: ReturnType<typeof vi.fn>;+ restart: ReturnType<typeof vi.fn>;+ stop: ReturnType<typeof vi.fn>;+ };+ daemon.start = vi.fn(async () => undefined);+ daemon.restart = vi.fn(async () => undefined);+ daemon.stop = vi.fn(async () => undefined);+ const controller = new BootstrapController({+ daemon: daemon as unknown as DaemonManager,+ logger: { info: vi.fn(), error: vi.fn() } as unknown as DesktopLogger,+ settings: { read: () => ({}), update: vi.fn() } as unknown as SettingsStore,+ daemonEntryPath: '/test/daemon', appHome: '/test', dataDir: '/test/data',+ codexRuntimeRoot: '/test/codex', creatorRuntimeRoot: '/test/creator', stickmanRuntimeRoot: '/test/stickman',+ defaultProjectRoot: '/test/projects', development: false, automaticRestartDelays: [10, 20, 30]+ });+ controller.on('ready', () => controller.markWorkspaceReady());+ const crash = () => daemon.emit('exit', { reason: 'unexpected', code: 1 });+ return { daemon, controller, crash };+ }++ describe('Desktop Runtime recovery', () => {+ it('bounds automatic recovery, backs off, and resets the budget after manual restart', async () => {+ vi.useFakeTimers();+ const input = fixture();+ await input.controller.start();+ for (const delay of [10, 20, 30]) {+ input.crash();+ await vi.advanceTimersByTimeAsync(delay - 1);+ expect(input.controller.currentState.phase).toBe('starting_daemon');+ await vi.advanceTimersByTimeAsync(1);+ expect(input.controller.currentState.phase).toBe('ready');+ }+ input.crash();+ await vi.advanceTimersByTimeAsync(0);+ expect(input.controller.currentState).toMatchObject({ phase: 'failed', error: { code: 'DAEMON_RESTART_EXHAUSTED' } });+ expect(input.daemon.start).toHaveBeenCalledTimes(4);+ await input.controller.restartRuntime();+ input.crash();+ await vi.advanceTimersByTimeAsync(10);+ expect(input.controller.currentState.phase).toBe('ready');- expect(input.daemon.start).toHaveBeenCalledTimes(5);++ expect(input.daemon.start).toHaveBeenCalledTimes(6);+ expect(input.daemon.start.mock.calls.slice(1).every(call => call[0].requireProbe === false)).toBe(true);+ await input.controller.stop();+ });++ it('retries failed recovery starts and cancels queued recovery on shutdown', async () => {+ vi.useFakeTimers();+ const input = fixture();+ await input.controller.start();+ input.daemon.start.mockRejectedValueOnce(new Error('temporary start failure'));+ input.crash();+ await vi.advanceTimersByTimeAsync(10);+ expect(input.controller.currentState.phase).toBe('starting_daemon');+ await vi.advanceTimersByTimeAsync(20);+ expect(input.controller.currentState.phase).toBe('ready');+ input.crash();+ await input.controller.stop();+ await vi.advanceTimersByTimeAsync(1_000);+ expect(input.daemon.start).toHaveBeenCalledTimes(3);+ });++ it('cancels a pending automatic restart before manually restarting and reports a real failure', async () => {+ vi.useFakeTimers();+ const input = fixture();+ await input.controller.start();+ input.crash();+ await input.controller.restartRuntime();+ await vi.advanceTimersByTimeAsync(100);- expect(input.daemon.start).toHaveBeenCalledTimes(1);- expect(input.daemon.restart).toHaveBeenCalledTimes(1);- input.daemon.restart.mockRejectedValueOnce(new Error('cannot start'));++ expect(input.daemon.start).toHaveBeenCalledTimes(2);++ input.daemon.start.mockRejectedValueOnce(new Error('cannot start'));+ await expect(input.controller.restartRuntime()).rejects.toThrow('cannot start');+ expect(input.controller.currentState.phase).toBe('failed');+ await input.controller.stop();+ });++ it.each(['stop', 'restartRuntime'] as const)('cancels an in-flight recovery start before waiting for %s', async operation => {+ vi.useFakeTimers();+ const input = fixture();+ await input.controller.start();+ let rejectStart: ((error: Error) => void) | undefined;+ input.daemon.start.mockImplementationOnce(() => new Promise((_resolve, reject) => { rejectStart = reject; }));+ input.daemon.stop.mockImplementation(async () => { rejectStart?.(new Error('stopped')); });+ input.crash();+ await vi.advanceTimersByTimeAsync(10);+ expect(rejectStart).toBeDefined();+ await input.controller[operation]();+ expect(input.daemon.stop).toHaveBeenCalled();+ if (operation === 'restartRuntime') expect(input.controller.currentState.phase).toBe('ready');+ await input.controller.stop();+ });+ });diff --cc apps/desktop/test/bootstrap-recovery.test.tsindex 8bb9d90e,00000000..c985c069mode 100644,000000..100644--- a/apps/desktop/test/bootstrap-recovery.test.ts+++ b/apps/desktop/test/bootstrap-recovery.test.ts@@@ -1,116 -1,0 +1,120 @@@+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,++ automaticRestartDelays: [0, 0],+ 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(daemon.stop).not.toHaveBeenCalled();++ expect(daemon.start).toHaveBeenCalledTimes(1);+ 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 });++ await vi.waitFor(() => expect(daemon.start).toHaveBeenCalledTimes(2), { timeout: 2_000 });++ expect(daemon.stop).toHaveBeenCalledTimes(1);+ 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(daemon.stop).toHaveBeenCalledTimes(1);++ expect(daemon.start).toHaveBeenCalledTimes(4);+ expect(controller.currentState.phase).toBe('ready');+ await controller.stop();+ });+});diff --cc apps/desktop/test/protocol-handler.test.tsindex 00000000,efb16c8f..5784ef00mode 000000,100644..100644--- a/apps/desktop/test/protocol-handler.test.ts+++ b/apps/desktop/test/protocol-handler.test.ts@@@ -1,0 -1,206 +1,212 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+ import { fetchDesktopRequest } from '../src/main/desktop-network.js';+ import { installProtocolHandler } from '../src/main/protocol-handler.js';+ import type { DesktopLogger } from '../src/main/logger.js';++ const network = vi.hoisted(() => ({+ fetch: vi.fn<typeof fetch>(),+ handle: vi.fn()+ }));++ vi.mock('electron', () => ({+ net: { fetch: network.fetch },+ protocol: { handle: network.handle }+ }));++ describe('Desktop protocol network lifecycle', () => {+ beforeEach(() => {+ network.fetch.mockReset();+ network.handle.mockReset();+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () => {+ throw new Error('Desktop requests must not use the built-in Undici transport');+ });+ });++ afterEach(() => vi.restoreAllMocks());++ it('uses Chromium fetch for both URL and Request inputs without ambient cookies', async () => {+ network.fetch.mockImplementation(async () => new Response('ok'));+ const request = new Request('https://example.com/status');++ await fetchDesktopRequest(new URL('https://example.com/status'));+ await fetchDesktopRequest(request, { credentials: 'include' });++ expect(network.fetch).toHaveBeenNthCalledWith(1, 'https://example.com/status', {+ credentials: 'omit'+ });+ expect(network.fetch).toHaveBeenNthCalledWith(2, request, {+ credentials: 'omit'+ });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('preserves Runtime authorization, JSON bodies and response headers', async () => {+ network.fetch.mockResolvedValue(new Response('{"ok":true}', {+ status: 201,+ headers: { 'Content-Type': 'application/json', Connection: 'keep-alive' }+ }));+ const fixture = await setup();+ const response = await fixture.handle(new Request(runtimeUrl('/runs'), {+ method: 'POST',+ headers: { Authorization: 'Bearer untrusted', 'Content-Type': 'application/json' },+ body: '{"input":"hello"}'+ }));+ const [target, init] = network.fetch.mock.calls[0]!;++ expect(target).toBe('http://127.0.0.1:60764/runs');+ expect(new Headers(init?.headers).get('authorization')).toBe('Bearer runtime-token');+ expect(new TextDecoder().decode(init?.body as Uint8Array)).toBe('{"input":"hello"}');+ expect(init?.redirect).toBe('manual');+ expect(response.status).toBe(201);+ expect(response.headers.get('connection')).toBeNull();+ expect(await response.json()).toEqual({ ok: true });+ fixture.controller.suspendRuntime();+ expect(init?.signal?.aborted).toBe(false);+ });++ it('keeps Creator source uploads streaming', async () => {+ network.fetch.mockResolvedValue(new Response('{}'));+ const fixture = await setup();+ const request = new Request(runtimeUrl('/creator/jobs/creator_job_test/source-video'), {+ method: 'POST',+ headers: { 'Content-Type': 'application/vnd.opencreator.creator-source' },+ body: new ReadableStream({ start: controller => controller.close() }),+ duplex: 'half'+ } as RequestInit);++ const response = await fixture.handle(request);+ const init = network.fetch.mock.calls[0]![1] as RequestInit & { duplex?: string };++ expect(init.body).toBe(request.body);+ expect(init.duplex).toBe('half');+ await response.text();+ });++ it('aborts pending requests and rejects new requests until Runtime resumes', async () => {+ network.fetch.mockImplementation(async (_url, init) => await new Promise<Response>(+ (_resolve, reject) => init?.signal?.addEventListener('abort', () => {+ reject(init.signal?.reason);+ }, { once: true })+ ));+ const fixture = await setup();+ const pending = fixture.handle(new Request(runtimeUrl('/healthz')));+ await vi.waitFor(() => expect(network.fetch).toHaveBeenCalledTimes(1));+ fixture.controller.suspendRuntime();++ expect((await pending).status).toBe(503);+ const blocked = await fixture.handle(new Request(runtimeUrl('/healthz')));+ expect(blocked.status).toBe(503);+ expect(await blocked.json()).toMatchObject({ error: { code: 'RUNTIME_SHUTTING_DOWN' } });+ expect(network.fetch).toHaveBeenCalledTimes(1);+ expect(fixture.logger.warn).not.toHaveBeenCalled();++ expect(fixture.onTransportFailure).not.toHaveBeenCalled();++ network.fetch.mockImplementation(async () => new Response('ready'));+ fixture.controller.resumeRuntime();+ expect(await (await fixture.handle(new Request(runtimeUrl('/healthz')))).text()).toBe('ready');+ });++ it('also cancels active SSE streams after response headers arrive', async () => {+ network.fetch.mockImplementation(async (_url, init) => new Response(+ new ReadableStream({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('data: ready\n\n'));+ init?.signal?.addEventListener('abort', () => controller.error(init.signal?.reason), {+ once: true+ });+ }+ }),+ { headers: { 'Content-Type': 'text/event-stream' } }+ ));+ const fixture = await setup();+ const response = await fixture.handle(new Request(runtimeUrl('/events')));+ const reader = response.body!.getReader();+ expect(new TextDecoder().decode((await reader.read()).value)).toBe('data: ready\n\n');++ fixture.controller.suspendRuntime();++ await expect(reader.read()).rejects.toMatchObject({ name: 'AbortError' });+ expect(network.fetch.mock.calls[0]![1]?.signal?.aborted).toBe(true);+ expect(fixture.logger.warn).not.toHaveBeenCalled();+ });++ it('forwards renderer cancellation without logging a transport failure', async () => {+ network.fetch.mockImplementation(async (_url, init) => await new Promise<Response>(+ (_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), {+ once: true+ })+ ));+ const fixture = await setup();+ const cancellation = new AbortController();+ const pending = fixture.handle(new Request(runtimeUrl('/healthz'), {+ signal: cancellation.signal+ }));+ await vi.waitFor(() => expect(network.fetch).toHaveBeenCalledTimes(1));+ cancellation.abort();++ expect((await pending).status).toBe(503);+ expect(fixture.logger.warn).not.toHaveBeenCalled();+ });++ it('releases requests when the renderer cancels a response stream', async () => {+ const cancel = vi.fn();+ network.fetch.mockResolvedValue(new Response(new ReadableStream({ cancel })));+ const fixture = await setup();+ const response = await fixture.handle(new Request(runtimeUrl('/events')));++ await response.body!.cancel('window closed');+ fixture.controller.suspendRuntime();++ expect(cancel).toHaveBeenCalledWith('window closed');+ expect(network.fetch.mock.calls[0]![1]?.signal?.aborted).toBe(false);+ expect(fixture.logger.warn).not.toHaveBeenCalled();+ });++ it('still reports genuine transport errors', async () => {+ network.fetch.mockRejectedValue(new Error('connection refused'));+ const fixture = await setup();+ const response = await fixture.handle(new Request(runtimeUrl('/healthz')));++ expect(response.status).toBe(502);+ expect(await response.json()).toMatchObject({ error: { code: 'RUNTIME_PROXY_FAILED' } });- expect(fixture.logger.warn).toHaveBeenCalledWith('Runtime proxy request failed', {++ expect(fixture.logger.warn).toHaveBeenCalledWith('Runtime proxy request failed', expect.objectContaining({+ path: '/.opencreator/runtime/healthz',- message: 'connection refused'- });++ method: 'GET',++ phase: 'fetch',++ errors: [{ name: 'Error' }]++ }));++ expect(fixture.onTransportFailure).toHaveBeenCalledTimes(1);+ });++ it('rejects unsafe Runtime paths before opening a network connection', async () => {+ const fixture = await setup();+ const response = await fixture.handle(new Request(runtimeUrl('/%2f%2fattacker.example')));++ expect(response.status).toBe(400);+ expect(network.fetch).not.toHaveBeenCalled();+ });+ });++ function runtimeUrl(path: string): string {+ return `opencreator-app://app/.opencreator/runtime${path}`;+ }++ async function setup() {++ const onTransportFailure = vi.fn();+ const logger: DesktopLogger = {+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ warnRateLimited: vi.fn(),+ flush: vi.fn(async () => undefined)+ };+ const controller = await installProtocolHandler({+ webRoot: '/unused/web',+ bootstrapRoot: '/unused/bootstrap',+ getConnection: () => ({ address: 'http://127.0.0.1:60764', token: 'runtime-token' }),++ onTransportFailure,+ logger+ });+ const handle = network.handle.mock.calls[0]![1] as (request: Request) => Promise<Response>;- return { controller, handle, logger };++ return { controller, handle, logger, onTransportFailure };+ }diff --cc apps/desktop/test/runtime-proxy-logging.test.tsindex 423dfe14,00000000..f81f5447mode 100644,000000..100644--- a/apps/desktop/test/runtime-proxy-logging.test.ts+++ b/apps/desktop/test/runtime-proxy-logging.test.ts@@@ -1,109 -1,0 +1,111 @@@+import { afterEach, describe, expect, it, vi } from 'vitest';- import { protocol } from 'electron';++import { net, protocol } from 'electron';+import type { DesktopLogger } from '../src/main/logger.js';+import { installProtocolHandler } from '../src/main/protocol-handler.js';++vi.mock('electron', () => ({++ net: { fetch: vi.fn() },+ protocol: {+ handle: vi.fn(),+ registerSchemesAsPrivileged: vi.fn()+ }+}));++afterEach(() => {+ vi.unstubAllGlobals();+ vi.mocked(protocol.handle).mockClear();++ vi.mocked(net.fetch).mockReset();+});++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 })));++ vi.mocked(net.fetch).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 })));++ vi.mocked(net.fetch).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 --cc apps/web/src/app/App.test.tsxindex b7050b64,10285199..a8a79022--- a/apps/web/src/app/App.test.tsx+++ b/apps/web/src/app/App.test.tsx@@@ -7111,68 -7289,6 +7289,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({});++ throw new Error(`Unexpected runtime request: ${url}`);+ };++ 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({@@@ -8301,6 -8417,6 +8479,9 @@@ function handleDefaultCreatorApiRequest): Response | undefined {const method = init?.method ?? 'GET';const parsedUrl = new URL(url);++ if (parsedUrl.pathname === '/creator/components/status' && method === 'GET') {++ return jsonResponse({ platform: 'darwin', arch: 'arm64', components: [] });++ }if (parsedUrl.pathname === '/creator/presets' && method === 'GET') {const locale = parsedUrl.searchParams.get('locale') === 'en-US'? 'en-US'diff --cc apps/web/src/app/AppController.tsxindex 1d96c045,7338824d..47c43e09--- a/apps/web/src/app/AppController.tsx+++ b/apps/web/src/app/AppController.tsx@@@ -4261,10 -4169,12 +4163,13 @@@ export function AppController(props: Ap)|| selectedPendingRunStart !== undefined|| selectedRunsLoading+ || !runtimeWorkspaceReady- || connectionState.status !== 'connected';+ || connectionState.status !== 'connected'+ || agentSetup === 'skipped';const composerDisabledReason = connectionState.status !== 'connected'? t('conversation.connectingRuntime')+ : agentSetup === 'skipped'+ ? l('请先配置 Agent 模型服务', 'Configure the Agent model service first'): projectLoadError !== undefined? t('conversation.checkingTask'): conversationNeedsProject && currentProject === undefined@@@ -4825,16 -4754,7 +4750,16 @@@);return (- <PageIssueRoutingProvider><RuntimeConnectionProvider value={{- <RuntimeRecoveryContext.Provider value={runtimeRecovery}><PageIssueRoutingProvider><div++ <RuntimeRecoveryContext.Provider value={runtimeRecovery}><PageIssueRoutingProvider><RuntimeConnectionProvider value={{+ status: connectionState.status,+ waitingForConfig: connectionConfig === null,- restarting: runtimeRestarting,- restartError: runtimeRestartError,- retry: retryRuntimeConnection,- ...(hostBridge.restartRuntime === undefined++ restarting: runtimeRecovery.phase === 'restarting',++ restartError: runtimeRecovery.phase === 'failed' ? runtimeRecovery.message : undefined,++ retry: () => void runtimeRecovery.retry(),++ ...(runtimeRecovery.restart === undefined+ ? {}- : { restart: () => void restartLocalRuntime() })++ : { restart: () => void runtimeRecovery.restart!() })+ }}><divclassName="app-drop-shell"data-integrated-title-bar={integratedTitleBar?.integratedTitleBar === true ? 'true' : undefined@@@ -4942,48 -4880,53 +4885,53 @@@<strong>松开以添加项目文件夹</strong></div>) : null}- <ProjectManagementDialog- open={projectManagementOpen}- projects={projects}- archivedProjects={archivedProjects}- unassignedThreads={unassignedThreads}- initialProjectId={projectManagementProjectId}- busy={projectMutationBusy}- onClose={() => {- setProjectManagementOpen(false);- setProjectManagementProjectId(undefined);- }}- onUpdate={updateManagedProject}- onArchive={archiveProject}- onRestore={restoreManagedProject}- onReplaceDirectory={- hostBridge.selectProjectDirectory === undefined- ? undefined- : replaceManagedProjectDirectory- }- onAssignThread={assignManagedThread}- onAddProject={- projectService === null- ? undefined- : () => {- setProjectManagementOpen(false);- void createProject();- }- }- onAddProjectDirectory={- hostBridge.selectProjectDirectory === undefined- ? undefined- : async () => {- await addProjectDirectory();- setProjectManagementOpen(true);- }- }- />+ {projectManagementOpen ? (+ <Suspense fallback={<div className="conversation-toast" role="status">{l('正在加载项目管理…', 'Loading project management…', 'Läser in projekthantering…')}</div>}>+ <ProjectManagementDialog+ open={projectManagementOpen}+ projects={projects}+ archivedProjects={archivedProjects}+ unassignedThreads={unassignedThreads}+ initialProjectId={projectManagementProjectId}+ busy={projectMutationBusy}+ onClose={() => {+ setProjectManagementOpen(false);+ setProjectManagementProjectId(undefined);+ }}+ onUpdate={updateManagedProject}+ onArchive={archiveProject}+ onRestore={restoreManagedProject}+ onReplaceDirectory={+ hostBridge.selectProjectDirectory === undefined+ ? undefined+ : replaceManagedProjectDirectory+ }+ onAssignThread={assignManagedThread}+ onAddProject={+ projectService === null+ ? undefined+ : () => {+ setProjectManagementOpen(false);+ void createProject();+ }+ }+ onAddProjectDirectory={+ hostBridge.selectProjectDirectory === undefined+ ? undefined+ : async () => {+ await addProjectDirectory();+ setProjectManagementOpen(true);+ }+ }+ />+ </Suspense>+ ) : null}<AgentDiagnosticsPanelhiddenCreatorIssues={immersiveWorkspace && props.route.view === 'workbench' && props.route.jobId === undefined}+ hiddenBackgroundRuntimeIssues={immersiveWorkspace && props.route.view === 'workbench'}onAskIssue={askAgentAboutIssue}/>- </div></RuntimeConnectionProvider></PageIssueRoutingProvider>- </div></PageIssueRoutingProvider></RuntimeRecoveryContext.Provider>++ </div></RuntimeConnectionProvider></PageIssueRoutingProvider></RuntimeRecoveryContext.Provider>);function createDetailPanel() {diff --cc apps/web/src/features/dashboard/CreatorCollaborationPanel.tsxindex 86591737,6384f90a..ad6636c9--- a/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx+++ b/apps/web/src/features/dashboard/CreatorCollaborationPanel.tsx@@@ -325,8 -331,6 +331,7 @@@ export default function CreatorCollabor);})}- <RuntimeConnectionNotice />+{showAgentWorking ? (<divclassName="creator-collaboration-working"