Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 统一机器人连接恢复与自动模型默认值
Dash9c5771d22f9b
diff --git a/apps/desktop/scripts/fixtures/feishu-connection/fixture.tsx b/apps/desktop/scripts/fixtures/feishu-connection/fixture.tsxnew file mode 100644index 0000000000..f19f88fcb2--- /dev/null+++ b/apps/desktop/scripts/fixtures/feishu-connection/fixture.tsx@@ -0,0 +1,35 @@+import { FeishuBotSection } from '../../../src/renderer/components/settings/FeishuBotSection';+import { mountPage, subscription, forbid } from '../../ui-page/harness';++// Exercise the real hook, host subscriptions and connection card without a live bot.+void mountPage({+ host: (ctx) => ({+ maker: {+ imDefaultSettingsGet: async () => ({+ agentKind: 'codex',+ agents: { codex: { model: 'gpt-example' } },+ }),+ },+ feishuBot: {+ getState: async () => ({+ status: ctx.data.status ?? 'error',+ error: ctx.data.error,+ appId: 'cli_example1234567890',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: 'ou_example1234567890',+ lifecycleAnnouncement: false,+ service: 'feishu',+ }),+ reconnect: () => new Promise(() => {}),+ clear: forbid('feishuBot.clear'),+ onStatusChange: subscription('feishu-status'),+ onRegistrationStatus: subscription('feishu-registration'),+ },+ }),+ render: () => (+ <div className="min-h-screen bg-[var(--surface)] p-4 text-[var(--text-primary)]">+ <FeishuBotSection expanded onToggle={() => {}} />+ </div>+ ),+});diff --git a/apps/desktop/scripts/fixtures/feishu-connection/ui-page.mjs b/apps/desktop/scripts/fixtures/feishu-connection/ui-page.mjsnew file mode 100644index 0000000000..f58ac4b37d--- /dev/null+++ b/apps/desktop/scripts/fixtures/feishu-connection/ui-page.mjs@@ -0,0 +1,120 @@+import assert from 'node:assert/strict';++export default {+ name: 'feishu-connection',+ entry: './fixture.tsx',+ viewport: { width: 660, height: 620 },+ real: 'FeishuBotSection, useFeishuBot, ImChannelSettingsCard, ErrorNotice, Button and translated recovery text',+ notCovered:+ 'Live Feishu network, credential writes and model/notification settings; transport recovery has targeted unit tests',+ stubs: {+ 'src/renderer/components/settings/ImDefaultSettingsSection':+ 'export const ImDefaultSettingsSection = () => null;',+ 'src/renderer/components/settings/FeishuBotNotificationSection':+ 'export const FeishuBotNotificationSection = () => null;',+ },+ cases: {+ default: {+ about: 'Timeout explains recovery and exposes reconnect',+ data: { error: 'Timed out waiting for connection (no onReady).' },+ },+ network: {+ about: 'Network failure has a specific explanation',+ data: { error: 'connect ECONNREFUSED' },+ },+ credentials: {+ about: 'Invalid credentials do not receive network advice',+ data: { error: 'App ID / App Secret 不正确(auth_failed)' },+ },+ unknown: {+ about: 'Unknown cause stays neutral',+ data: { error: 'Unexpected connection failure' },+ },+ conflict: {+ about: 'Device conflict preserves the binding',+ data: { status: 'conflict', error: 'exceed_conn_limit' },+ },+ reconnecting: { about: 'Automatic recovery shows progress', data: { status: 'reconnecting' } },+ connected: {+ about: 'Healthy connection retains a quiet reconnect action',+ data: { status: 'connected' },+ },+ narrow: {+ about: 'Recovery actions wrap at 320px',+ viewport: { width: 320, height: 760 },+ data: { error: 'connect ETIMEDOUT' },+ },+ },+ async ready(page) {+ await page.locator('[data-feishu-connection-card]').waitFor();+ },+ async check(page, ui) {+ const card = page.locator('[data-feishu-connection-card]');+ const reconnect = card.getByRole('button', {+ name: await ui.t('settings.feishuBot.connected.reconnect', {+ service: await ui.t('settings.feishuBot.services.feishu'),+ }),+ exact: true,+ });+ assert.ok(await reconnect.isVisible());+ assert.ok(await reconnect.isEnabled());+ const notes = {+ default: 'timeoutErrorNote',+ narrow: 'timeoutErrorNote',+ network: 'networkErrorNote',+ credentials: 'credentialsErrorNote',+ unknown: 'errorNote',+ conflict: 'conflictNote',+ reconnecting: 'reconnectingNote',+ };+ if (notes[ui.case])+ assert.ok(+ await card+ .getByText(await ui.t(`settings.feishuBot.saved.${notes[ui.case]}`), { exact: true })+ .isVisible(),+ );+ if (ui.data.error) {+ const details = card.getByRole('button', {+ name: await ui.t('chat.errorBanner.networkShowRaw'),+ exact: true,+ });+ assert.equal(await details.getAttribute('aria-expanded'), 'false');+ await details.click();+ assert.equal(await card.locator('pre').innerText(), ui.data.error);+ }+ if (ui.case === 'default') {+ await ui.emit('feishu-status', {+ status: 'connected',+ botAppId: 'cli_example1234567890',+ ownerOpenId: 'ou_example1234567890',+ });+ await card+ .getByText(+ await ui.t('settings.feishuBot.connected.heading', {+ service: await ui.t('settings.feishuBot.services.feishu'),+ }),+ { exact: true },+ )+ .waitFor();+ assert.equal(await card.locator('pre').count(), 0);+ await ui.capture('recovered');+ }+ await reconnect.click();+ assert.ok(await reconnect.isDisabled());+ assert.ok(+ await page+ .getByRole('status', {+ name: await ui.t('settings.feishuBot.statusAria', {+ status: await ui.t('settings.feishuBot.status.connecting'),+ }),+ exact: true,+ })+ .isVisible(),+ );+ assert.ok(+ await card+ .getByText(await ui.t('settings.feishuBot.status.connecting'), { exact: true })+ .isVisible(),+ );+ },+};diff --git a/apps/desktop/scripts/fixtures/im-connection-recovery/fixture.tsx b/apps/desktop/scripts/fixtures/im-connection-recovery/fixture.tsxnew file mode 100644index 0000000000..e4cbf18a54--- /dev/null+++ b/apps/desktop/scripts/fixtures/im-connection-recovery/fixture.tsx@@ -0,0 +1,59 @@+import { DiscordBotSection } from '../../../src/renderer/components/settings/DiscordBotSection';+import { TelegramBotSection } from '../../../src/renderer/components/settings/TelegramBotSection';+import { DingTalkBotSection } from '../../../src/renderer/components/settings/DingTalkBotSection';+import { WecomBotSection } from '../../../src/renderer/components/settings/WecomBotSection';+import { ConfirmDialogProvider } from '../../../src/renderer/components/ui/confirm-dialog-provider';+import { mountPage, subscription } from '../../ui-page/harness';++const sections = {+ discord: DiscordBotSection,+ telegram: TelegramBotSection,+ dingtalk: DingTalkBotSection,+ wecom: WecomBotSection,+};+const pending = () => new Promise(() => {});+const status = { kind: 'error', reason: 'Temporary network failure', code: 'network' };+const ownerUserId = '12345678901234567';++void mountPage({+ host: () => ({+ maker: {+ imDefaultSettingsGet: async () => ({+ agentKind: 'codex',+ agents: { codex: { model: 'gpt-example' } },+ }),+ },+ discordBot: {+ getStatus: async () => ({ status, ownerUserId, lifecycleAnnouncement: false }),+ reconnect: pending,+ onStatusChange: subscription('discord-status'),+ },+ telegramBot: {+ getStatus: async () => ({ status, ownerUserId, botUsername: 'example_bot' }),+ setOnline: pending,+ onStatusChange: subscription('telegram-status'),+ },+ dingtalkBot: {+ getState: async () => ({ status, ownerUserId, appKey: 'example_app', hasSecret: true }),+ reconnect: pending,+ onStatusChange: subscription('dingtalk-status'),+ onOwnerChange: subscription('dingtalk-owner'),+ },+ wecomBot: {+ getStatus: async () => ({ status, ownerUserId, botId: 'example_bot' }),+ reconnect: pending,+ onStatusChange: subscription('wecom-status'),+ },+ wecomGroupNotification: { getState: async () => ({ configured: false, enabled: false }) },+ }),+ render: (ctx) => {+ const Section = sections[ctx.data.channel as keyof typeof sections];+ return (+ <ConfirmDialogProvider>+ <div className="min-h-screen bg-[var(--surface)] p-4 text-[var(--text-primary)]">+ <Section expanded onToggle={() => {}} />+ </div>+ </ConfirmDialogProvider>+ );+ },+});diff --git a/apps/desktop/scripts/fixtures/im-connection-recovery/ui-page.mjs b/apps/desktop/scripts/fixtures/im-connection-recovery/ui-page.mjsnew file mode 100644index 0000000000..abe2764fbe--- /dev/null+++ b/apps/desktop/scripts/fixtures/im-connection-recovery/ui-page.mjs@@ -0,0 +1,63 @@+import assert from 'node:assert/strict';++const channels = ['discord', 'telegram', 'dingtalk', 'wecom'];+export default {+ name: 'im-connection-recovery',+ entry: './fixture.tsx',+ viewport: { width: 660, height: 850 },+ real: 'Four bot settings sections, hooks, ErrorNotice, reconnect buttons and translations',+ notCovered: 'Live IM services, credentials and unrelated model/Telegram behavior settings',+ stubs: {+ 'src/renderer/components/settings/ImDefaultSettingsSection':+ 'export const ImDefaultSettingsSection = () => null;',+ 'src/renderer/components/settings/TelegramBehaviorSettings':+ 'export const TelegramBehaviorSettings = () => null; export const TelegramGroupActivationSettings = () => null; export const TelegramPersonaSettings = () => null;',+ 'src/renderer/components/settings/TelegramRemoteDevices':+ 'export const TelegramRemoteDevices = () => null;',+ },+ cases: Object.fromEntries(+ channels.flatMap((channel) => [+ [+ channel === 'discord' ? 'default' : channel,+ { about: `${channel}: failure retains binding and exposes retry`, data: { channel } },+ ],+ [+ `${channel}-narrow`,+ {+ about: `${channel}: recovery at 320px`,+ data: { channel },+ viewport: { width: 320, height: 850 },+ },+ ],+ ]),+ ),+ async ready(page) {+ await page.getByRole('alert').waitFor();+ },+ async check(page, ui) {+ const channel = ui.data.channel;+ const reconnectKey =+ channel === 'wecom' || channel === 'dingtalk'+ ? `settings.${channel}Bot.reconnect`+ : 'settings.imConnection.reconnect';+ const retry = page.getByRole('button', { name: await ui.t(reconnectKey), exact: true });+ assert.ok(await retry.isEnabled());+ const details = page.getByRole('button', {+ name: await ui.t('chat.errorBanner.networkShowRaw'),+ exact: true,+ });+ assert.equal(await details.getAttribute('aria-expanded'), 'false');+ await details.click();+ assert.equal(await page.locator('pre').innerText(), 'Temporary network failure');+ await retry.click();+ assert.ok(await retry.isDisabled());+ await ui.capture('retrying');+ await ui.emit(`${channel}-status`, {+ status: { kind: 'connected', appId: 'example_bot' },+ ownerUserId: '12345678901234567',+ botId: 'example_bot',+ });+ await page.getByRole('alert').waitFor({ state: 'hidden' });+ await ui.capture('recovered');+ },+};diff --git a/apps/desktop/scripts/fixtures/im-default-model/fixture.tsx b/apps/desktop/scripts/fixtures/im-default-model/fixture.tsxnew file mode 100644index 0000000000..d77b847166--- /dev/null+++ b/apps/desktop/scripts/fixtures/im-default-model/fixture.tsx@@ -0,0 +1,85 @@+import { mountPage, subscription } from '../../ui-page/harness';+import { ImDefaultSettingsSection } from '../../../src/renderer/components/settings/ImDefaultSettingsSection';+import {+ IM_DEFAULT_SETTINGS,+ type ImDefaultSettingsPatch,+} from '../../../src/shared/imDefaultSettings';+import {+ resolveAutomaticImSettings,+ usesAutomaticImModel,+} from '../../../src/shared/imAutomaticModel';+import {+ beginProvidersRefresh,+ commitProvidersSnapshot,+} from '../../../src/renderer/lib/providersSnapshotStore';+import { getDataOwnerGeneration } from '../../../src/renderer/contexts/dataOwnerGeneration';+import { BUNDLED_CATALOG, type ProviderView } from '@cindy/model-providers';++const provider: ProviderView = {+ ...BUNDLED_CATALOG.providers.find((p) => p.id === 'openai')!,+ connected: true,+ agents: ['codex'],+ access: { kind: 'subscription' },+ models: {+ codex: [+ {+ id: 'gpt-6.1-sol',+ name: 'GPT-6.1-Sol',+ contextWindow: 200000,+ group: 'gpt',+ efforts: ['low', 'medium', 'high'],+ defaultEffort: 'high',+ },+ ],+ },+};++void mountPage({+ host: (ctx) => {+ const providers = ctx.case === 'im-unavailable' ? [] : [provider];+ const owner = getDataOwnerGeneration();+ commitProvidersSnapshot(beginProvidersRefresh(), {+ dataOwnerId: owner.dataOwnerId,+ ownerGeneration: owner.generation,+ providers,+ providerOrder: ['openai'],+ });+ let stored = structuredClone(IM_DEFAULT_SETTINGS);+ if (ctx.case === 'im-fixed') stored = resolveAutomaticImSettings(stored, providers)!;+ const state = () => ({+ ...(usesAutomaticImModel(stored)+ ? (resolveAutomaticImSettings(stored, providers) ?? stored)+ : stored),+ automaticModel: usesAutomaticImModel(stored),+ isCustomized: !usesAutomaticImModel(stored),+ customizedKeys: [],+ defaults: IM_DEFAULT_SETTINGS,+ });+ return {+ maker: {+ imDefaultSettingsGet: async () => state(),+ imDefaultSettingsSet: async (patch: ImDefaultSettingsPatch) => {+ stored = { ...stored, ...patch, agents: { ...stored.agents, ...patch.agents } };+ return state();+ },+ imDefaultSettingsReset: async () => {+ stored = structuredClone(IM_DEFAULT_SETTINGS);+ return state();+ },+ listAvailableAgents: async () => ['claude-code', 'codex', 'pi'],+ getCapabilities: async () => ({+ availableModels: provider.models.codex.map((m) => ({ ...m, displayName: m.name })),+ effortLevels: [],+ permissionModes: [{ id: 'auto', displayName: 'Auto' }],+ turnPermissionPolicy: { supported: { supported: true }, unsupportedPermissionModes: [] },+ }),+ onProvidersChanged: subscription('providers'),+ },+ };+ },+ render: () => (+ <main className="min-h-screen bg-[var(--surface)] p-4 text-[var(--text-primary)]">+ <ImDefaultSettingsSection channel="discord" />+ </main>+ ),+});diff --git a/apps/desktop/scripts/fixtures/im-default-model/ui-page.mjs b/apps/desktop/scripts/fixtures/im-default-model/ui-page.mjsnew file mode 100644index 0000000000..2ff9bdb75c--- /dev/null+++ b/apps/desktop/scripts/fixtures/im-default-model/ui-page.mjs@@ -0,0 +1,43 @@+import assert from 'node:assert/strict';++export default {+ name: 'im-default-model',+ entry: './fixture.tsx',+ viewport: { width: 660, height: 520 },+ real: 'IM defaults settings, real model selector, automatic model resolution and restore action',+ notCovered: 'Live credentials and model discovery; host supplies a catalog and settings writes',+ cases: {+ default: { about: 'Automatic selection shows the actual model' },+ 'im-automatic': { about: 'Automatic selection shows the actual model' },+ 'im-fixed': { about: 'Explicit choice can return to automatic without resetting permissions' },+ 'im-unavailable': { about: 'No usable provider is explained without inventing a default' },+ 'im-narrow': { about: 'Automatic selection at 320px', viewport: { width: 320, height: 640 } },+ },+ async ready(page) {+ await page.locator('section').waitFor();+ },+ async check(page, ui) {+ if (ui.case === 'im-fixed') {+ await page+ .getByRole('button', {+ name: await ui.t('settings.imBot.defaults.useAutomatic'),+ exact: true,+ })+ .click();+ }+ assert.ok(+ await page+ .getByText(await ui.t('settings.imBot.defaults.automatic'), { exact: true })+ .isVisible(),+ );+ if (ui.case === 'im-unavailable') {+ assert.ok(+ await page+ .getByText(await ui.t('settings.imBot.defaults.automaticUnavailable'), { exact: true })+ .isVisible(),+ );+ } else {+ assert.ok(await page.getByText('GPT-6.1-Sol', { exact: true }).isVisible());+ }+ },+};diff --git a/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.tsindex d42ba59c11..caed6184b9 100644--- a/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts+++ b/apps/desktop/src/main/__tests__/imDefaultSettingsIpcSecurity.test.ts@@ -5,6 +5,20 @@ import { describe, expect, it } from 'vitest';const source = readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');describe('im default settings IPC security contract', () => {+ // Guard tier: the async catalog projection must not return another owner's settings after switching accounts.+ it('fences the automatic-model projection by the owner generation before returning', () => {+ const start = source.indexOf('async function imDefaultSettingsWire(');+ const end = source.indexOf('\nfunction parseImDefaultSettingsChannel', start);+ const body = source.slice(start, end);+ const capture = body.indexOf('const ownerGeneration = getActiveAppSession().generation;');+ const resolve = body.indexOf('await projectImDefaultSettings(');+ const guard = body.indexOf('getActiveAppSession().generation !== ownerGeneration');+ expect(capture).toBeGreaterThan(0);+ expect(resolve).toBeGreaterThan(capture);+ expect(guard).toBeGreaterThan(resolve);+ expect(body.indexOf('return {')).toBeGreaterThan(guard);+ expect(body).toContain('isAppSessionBoundaryPending()');+ });// 保存/重置会按旧默认批量补写老任务的跟随记录, 并让下一条 IM 消息切换现有任务的// 运行路由 —— sender 校验必须拦在任何回填或写设置之前, 不能让导航到外部页面的// preload frame 改写渠道默认并推动任务切路由(codex review P1, PR #5155)。diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex ff84acb352..8bb1b19676 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -848,7 +848,8 @@ import {resetImDefaultSettingsChannel,writeImDefaultSettingsPatch,} from './im/defaultSettingsStore.js';-import { readImDefaultSettingsFingerprint } from './im/defaultSessionSettings.js';+import { readImDefaultSettingsFingerprint, projectImDefaultSettings } from './im/defaultSessionSettings.js';+import { usesAutomaticImModel } from '../shared/imAutomaticModel.js';import { fingerprintImDefaultSettings } from './im/shared/channelDefaultRoute.js';import { IM_DEFAULT_SETTINGS } from '../shared/imDefaultSettings.js';import { assertOwnerScopeSettledForWrite } from './im/ownerScopedStorage.js';@@ -10480,10 +10481,17 @@ function memorySettingsWire() {};}-function imDefaultSettingsWire(channel?: ImDefaultSettingsChannel) {+async function imDefaultSettingsWire(channel?: ImDefaultSettingsChannel) {+ const ownerGeneration = getActiveAppSession().generation;const state = readImDefaultSettingsState(channel);+ const automaticModel = usesAutomaticImModel(state.value);+ const value = await projectImDefaultSettings(state.value, channel);+ if (isAppSessionBoundaryPending() || getActiveAppSession().generation !== ownerGeneration) {+ throwIpcError('INTERNAL', 'IM settings owner changed; retry loading settings');+ }return {- ...state.value,+ ...value,+ automaticModel,isCustomized: state.isCustomized,customizedKeys: state.customizedKeys,defaults: state.defaults,diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.tsindex ee69f96647..8ad81aaa78 100644--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts@@ -24,6 +24,7 @@ import * as taskImages from '../../cindy-media/taskImageDelivery';import { rewriteTaskImageReferences } from '../../cindy-media/taskImageMarkdown';import type { AgentEvent, Effort, PermissionMode, PermissionModeState } from '@cindy/maker-core';import type { CatalogModel, ProviderView } from '@cindy/model-providers';+import { IM_DEFAULT_SETTINGS } from '../../../shared/imDefaultSettings';const h = vi.hoisted(() => {/** 跨模块调用顺序记录: 'touch:<id>' / 'created:<id>' */@@ -607,6 +608,25 @@ describe('hook task model selection on next send', () => {expect(h.readImDefaultSettings).toHaveBeenCalledWith(undefined);});+ it.each(['telegram', 'slack', 'x'])('resolves automatic %s defaults and follows catalog changes', async (channel) => {+ h.useActualDefaults = true;+ h.readImDefaultSettings.mockReturnValue(IM_DEFAULT_SETTINGS);+ const provider = { ...connectedProvider('openai', [catalogModel('current-recommendation')], 'codex'), access: { kind: 'subscription' as const } };+ h.listProviders.mockResolvedValue([provider]);+ const req = baseReq({ workspaceAlias: 'repo', source: { im: channel, userText: 'hello' } });+ const runner = createMakerHookSessionRunner({ log });+ expect((await runner.run({ ...req, createOnly: true })).status).toBe('ok');+ expect(h.createSessionRow).toHaveBeenCalledWith(expect.objectContaining({ agentKind: 'codex', model: 'current-recommendation' }));+ const creationFingerprint = h.writeDefaultRecord.mock.calls[0][1];+ await runner.run({ ...req, isNew: false });+ const policy = h.followPolicy.mock.calls[0][0];+ expect(policy.fingerprint()).not.toBe(creationFingerprint);+ provider.models.codex = [catalogModel('next-recommendation')];+ const next = await policy.resolveTarget([provider]);+ expect(next).toMatchObject({ agentKind: 'codex', model: 'next-recommendation', providerId: 'openai' });+ expect(next.fingerprint).not.toBe(creationFingerprint);+ });+it.each([false, true])('records new official tasks with their creation defaults (createOnly=%s)', async (createOnly) => {const outcome = await createMakerHookSessionRunner({ log }).run(baseReq({createOnly, source: { im: 'telegram', userText: 'hello' },@@ -616,6 +636,20 @@ describe('hook task model selection on next send', () => {expect(h.acquirePendingAgentSwitch).not.toHaveBeenCalled();});+ it('uses the common automatic policy for a workspace with only an explicit engine', async () => {+ h.useActualDefaults = true;+ h.readImDefaultSettings.mockReturnValue({ ...IM_DEFAULT_SETTINGS, agents: { ...IM_DEFAULT_SETTINGS.agents,+ 'claude-code': { providerId: 'xd', model: 'pinned-claude', effort: 'high' },+ } });+ h.getWorkspacePref.mockReturnValue({ channel: 'telegram', teamId: null, workspace: 'repo',+ agentKind: 'codex', model: null, effort: null, permissionMode: null });+ h.listProviders.mockResolvedValue([{ ...connectedProvider('openai', [catalogModel('automatic-codex')], 'codex'), access: { kind: 'subscription' } }]);+ expect((await createMakerHookSessionRunner({ log }).run(baseReq({ createOnly: true,+ workspaceAlias: 'repo', source: { im: 'telegram', userText: 'hello' },+ }))).status).toBe('ok');+ expect(h.createSessionRow).toHaveBeenCalledWith(expect.objectContaining({ agentKind: 'codex', model: 'automatic-codex' }));+ });+it.each(['telegram', 'slack', 'x'])('preserves %s dispatch defaults until workspace migration completes', async (channel) => {h.useActualDefaults = true;h.isWorkspacePrefsMigrated.mockReturnValue(false);diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.tsindex caf0c6fd05..1b838b4d50 100644--- a/apps/desktop/src/main/hook-control/session-runner.ts+++ b/apps/desktop/src/main/hook-control/session-runner.ts@@ -143,6 +143,7 @@ import {type HookSessionRunner,} from './dispatcher.js';import { resolveHookSessionConfig, type ResolvedHookSessionConfig } from './defaults.js';+import { resolveAutomaticImSettings, resolvedImDefaultFingerprint, usesAutomaticImModel } from '../../shared/imAutomaticModel.js';import { decodeAttachments, sanitizeAttachmentName } from './attachments.js';import {cancelHookInteraction,@@ -257,7 +258,18 @@ async function resolveNewSessionConfig(}const { channel, mergedOverrides, workdirProviderId, workdirRoute, imDefaults } = inputs;- const defaults = imDefaults;+ let defaults = imDefaults;+ const selectedAgent = mergedOverrides.agentKind;+ const selectedDefaultAgent = selectedAgent === 'claude-code' || selectedAgent === 'codex' || selectedAgent === 'pi' ? selectedAgent : imDefaults.agentKind;+ const automatic = usesAutomaticImModel({ ...imDefaults, agentKind: selectedDefaultAgent }) && mergedOverrides.model === null && !workdirRoute?.agentDeviceId;+ if (automatic) {+ const resolved = providers && resolveAutomaticImSettings(imDefaults, providers, {+ agentKind: selectedAgent === 'claude-code' || selectedAgent === 'codex' || selectedAgent === 'pi' ? selectedAgent : undefined,+ providerId: workdirProviderId,+ });+ if (!resolved) throw new Error(`${HOOK_ROUTE_UNAVAILABLE_PREFIX} no available default model${ROUTE_RESELECT_HINT}`);+ defaults = resolved;+ }const requestedAgent = mergedOverrides.agentKind === 'claude-code' || mergedOverrides.agentKind === 'codex' || mergedOverrides.agentKind === 'pi'? mergedOverrides.agentKind : defaults.agentKind;const defaultRoute = defaults.agents[requestedAgent];@@ -288,7 +300,7 @@ async function resolveNewSessionConfig(const resolved = resolveHookSessionConfig({- readDefaults: () => imDefaults,+ readDefaults: () => defaults,// 可执行清单按**启用**口径,不叠加「显示 / 隐藏」偏好:隐藏只是陈列过滤// (选择器不列),被 IM 显式点名或兜底选中仍然合法;停用的模型与供应商已由// visibleModelUnion 内建的准入过滤(model.disabled / suspended)剔除,点名@@ -362,7 +374,8 @@ async function resolveNewSessionConfig(`hook saved route degraded (disabled in settings): model=${resolved.model} providerId=${providerId ?? 'null'} catalog=${providers ? 'ok' : 'outage'}`,);}- return { ...resolved, model: lenient.model, providerId: lenient.providerId, fingerprint };+ return { ...resolved, model: lenient.model, providerId: lenient.providerId,+ fingerprint: automatic ? resolvedImDefaultFingerprint(fingerprint, defaults) : fingerprint };}/**diff --git a/apps/desktop/src/main/hook-control/transport.ts b/apps/desktop/src/main/hook-control/transport.tsindex 1f661af936..aae8d6c373 100644--- a/apps/desktop/src/main/hook-control/transport.ts+++ b/apps/desktop/src/main/hook-control/transport.ts@@ -16,6 +16,7 @@*/import WebSocket from 'ws';+import { ConnectionRetry, connectionBackoffDelayMs } from '@cindy/im/connection-retry';import {makeHello,@@ -66,8 +67,6 @@ export interface HookTransport {dispose(): void;}-const BACKOFF_BASE_MS = 1000;-const BACKOFF_MAX_MS = 30_000;/*** 退避抖动下界:实际延迟取 [BACKOFF_JITTER_MIN_RATIO, 1.0] × 退避值。*@@ -97,10 +96,12 @@ export function computeBackoffDelayMs(maxMs: number,random: () => number,): number {- const capped = Math.min(baseMs * 2 ** attempt, maxMs);- return Math.round(- capped * (BACKOFF_JITTER_MIN_RATIO + random() * (1 - BACKOFF_JITTER_MIN_RATIO)),- );+ return connectionBackoffDelayMs(attempt, {+ baseMs,+ maxMs,+ random,+ jitterMinRatio: BACKOFF_JITTER_MIN_RATIO,+ });}/** 服务端 first-wins:同账号同 deviceId 的后续 hello 被此 close code 拒绝。 */@@ -117,17 +118,18 @@ const IDLE_TIMEOUT_MS = 65_000;export function createHookTransport(opts: HookTransportOpts): HookTransport {const { url, getAuthToken, refreshAuthToken, buildHello, onMessage, onStatus, log } = opts;- const backoffBaseMs = opts.timing?.backoffBaseMs ?? BACKOFF_BASE_MS;- const backoffMaxMs = opts.timing?.backoffMaxMs ?? BACKOFF_MAX_MS;const standbyRetryMs = opts.timing?.standbyRetryMs ?? STANDBY_RETRY_MS;- const random = opts.random ?? Math.random;+ const retry = new ConnectionRetry({+ baseMs: opts.timing?.backoffBaseMs,+ maxMs: opts.timing?.backoffMaxMs,+ jitterMinRatio: BACKOFF_JITTER_MIN_RATIO,+ random: opts.random,+ });let ws: WebSocket | null = null;let stopped = false;let standby = false;- let attempt = 0;let authRefreshAttempted = false;- let retryTimer: ReturnType<typeof setTimeout> | null = null;let pingTimer: ReturnType<typeof setInterval> | null = null;let lastFrameAt = 0;let lastError: string | null = null;@@ -148,10 +150,7 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {}function clearTimers(): void {- if (retryTimer) {- clearTimeout(retryTimer);- retryTimer = null;- }+ retry.reset();if (pingTimer) {clearInterval(pingTimer);pingTimer = null;@@ -159,16 +158,10 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {}function scheduleRetry(delayOverrideMs?: number): void {- if (stopped || retryTimer) return;+ if (stopped) return;// 显式周期(standby 低频探测)不抖动:它表达的是「多久探一次首实例是否退出」,// 是一个产品语义上的固定节奏,不是用来防重连风暴的退避。- const delay =- delayOverrideMs ?? computeBackoffDelayMs(attempt, backoffBaseMs, backoffMaxMs, random);- attempt += 1;- retryTimer = setTimeout(() => {- retryTimer = null;- connect();- }, delay);+ retry.schedule(connect, { fixedDelayMs: delayOverrideMs });}function send(msg: HookMessage): boolean {@@ -298,7 +291,7 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {if (msg.type === 'pong') return;if (msg.type === 'welcome') {standby = false;- attempt = 0;+ retry.reset();authRefreshAttempted = false;lastError = null;log.info(`handshake complete with ${msg.payload.serverName}`);@@ -330,7 +323,9 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {if (code === DUPLICATE_DEVICE_CLOSE_CODE && reasonText === DUPLICATE_DEVICE_CLOSE_REASON) {standby = true;lastError = null;- log.info(`duplicate device connection rejected; entering standby, retrying in ${standbyRetryMs}ms`);+ log.info(+ `duplicate device connection rejected; entering standby, retrying in ${standbyRetryMs}ms`,+ );onStatus('standby', null);scheduleRetry(standbyRetryMs);return;diff --git a/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts b/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.tsindex 02f88b4d19..4ee46f229d 100644--- a/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts+++ b/apps/desktop/src/main/im/__tests__/defaultSessionSettings.test.ts@@ -25,7 +25,8 @@ vi.mock('../defaultSettingsStore', () => ({}));vi.mock('../remoteProviderRoute', () => ({ readImRemoteProviderRoute: mocks.readRemoteRoute }));-import { resolveImSessionDefaults } from '../defaultSessionSettings';+import { projectImDefaultSettings, resolveImSessionDefaults } from '../defaultSessionSettings';+import { IM_DEFAULT_SETTINGS } from '../../../shared/imDefaultSettings';import type { ImOrchestratorConfig } from '../shared/types';const config: ImOrchestratorConfig = {@@ -76,6 +77,7 @@ const providers = [{id: 'xd',name: 'XD',+ auth: { method: 'managed' },source: 'builtin',connected: true,agents: ['claude-code', 'codex'],@@ -91,6 +93,7 @@ const providers = [{id: 'openai',name: 'OpenAI',+ auth: { method: 'managed' },source: 'builtin',connected: true,agents: ['codex'],@@ -113,6 +116,53 @@ const customCodexModel = {};describe('resolveImSessionDefaults', () => {+ // Unit: old fixed IM defaults ignored catalog updates; exercise the real creation resolver.+ it('resolves automatic defaults from the live catalog without persisting a model snapshot', async () => {+ mocks.readImDefaultSettings.mockReturnValue(IM_DEFAULT_SETTINGS);+ const subscription = {+ ...providers[1], access: { kind: 'subscription' },+ models: { codex: [+ { ...openAiCodexModels[0], sortOrder: 20 },+ { ...openAiCodexModels[0], id: 'current-recommendation', sortOrder: 1 },+ ] },+ };+ mocks.listProviders.mockResolvedValue([providers[0], subscription]);+ const first = await resolveImSessionDefaults(config);+ expect(first).toMatchObject({ agentKind: 'codex', model: 'current-recommendation', providerId: 'openai', effort: 'medium' });+ subscription.models.codex[1].id = 'next-recommendation';+ const next = await resolveImSessionDefaults(config);+ expect(next.model).toBe('next-recommendation');+ expect(next.fingerprint).not.toBe(first.fingerprint);+ expect(IM_DEFAULT_SETTINGS.agents.codex.model).toBe('');+ });++ it('does not invent a model when automatic selection has no usable source', async () => {+ mocks.readImDefaultSettings.mockReturnValue(IM_DEFAULT_SETTINGS);+ mocks.listProviders.mockResolvedValue([]);+ await expect(resolveImSessionDefaults(config)).rejects.toThrow('no available chat model');+ mocks.listProviders.mockRejectedValue(new Error('catalog offline'));+ await expect(resolveImSessionDefaults(config)).rejects.toThrow('no available chat model');+ });++ it('projects automatic engine slots for official workspace overrides without changing saved choices', async () => {+ const saved = { ...IM_DEFAULT_SETTINGS, agents: { ...IM_DEFAULT_SETTINGS.agents,+ 'claude-code': { providerId: 'xd', model: 'explicit-old-model', effort: 'high' as const },+ } };+ const view = await projectImDefaultSettings(saved);+ expect(view.agents['claude-code']).toEqual(saved.agents['claude-code']);+ expect(view.agents.codex.model).toBeTruthy();+ expect(view.agents.codex.providerId).toBeTruthy();+ expect(saved.agents.codex.model).toBe('');+ expect(mocks.listProviders).toHaveBeenCalledTimes(1);+ });++ it('filters automatic engines by the channel approval capability', async () => {+ mocks.readImDefaultSettings.mockReturnValue(IM_DEFAULT_SETTINGS);+ mocks.getCapabilities.mockImplementation((agent: string) => ({+ availableModels: [], turnPermissionPolicy: { supported: { supported: agent === 'codex' } },+ }));+ await expect(resolveImSessionDefaults(config, undefined, 'wechat')).resolves.toMatchObject({ agentKind: 'codex' });+ });it.each(['claude-code', 'codex', 'pi'] as const)('resolves a shared %s model only against its own catalog', async (agentKind) => {mocks.readImDefaultSettings.mockReturnValue({ agentKind, permissionMode: 'auto', agents: {[agentKind]: { agentDeviceId: 'share:owner', providerId: 'owner-only', model: 'remote-model', effort: 'high' },@@ -134,7 +184,7 @@ describe('resolveImSessionDefaults', () => {mocks.listProviders.mockResolvedValue(providers);});- it('resolves the system IM default to Claude Opus 4.8 xhigh', async () => {+ it('preserves an explicitly saved older model and effort', async () => {mocks.readImDefaultSettings.mockReturnValue({agentKind: 'claude-code',agents: {@@ -405,8 +455,8 @@ describe('resolveImSessionDefaults', () => {await expect(resolveImSessionDefaults(config)).resolves.toMatchObject({agentKind: 'codex',- model: 'codex/gpt-5.5',- effort: 'high',+ model: 'gpt-5.5',+ effort: 'medium',providerId: null,});});@@ -563,7 +613,7 @@ describe('resolveImSessionDefaults', () => {await expect(resolveImSessionDefaults(config)).resolves.toMatchObject({agentKind: 'codex',- model: 'codex/gpt-5.5', // the image model sorts first but must be skipped+ model: 'gpt-5.5', // the image model must be skipped; use the connected source fallback});});diff --git a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.tsindex a3b247dc53..435ad443b6 100644--- a/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts+++ b/apps/desktop/src/main/im/__tests__/defaultSettingsStore.test.ts@@ -1,17 +1,19 @@import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const scopeMocks = vi.hoisted(() => ({owner: 'cloud-a',+ dir: '',join: null as unknown as (...parts: string[]) => string,claimLegacy: vi.fn(),}));vi.mock('electron', () => ({app: {- getPath: vi.fn(() => '/tmp/xdt-maker-test'),+ getPath: vi.fn(() => scopeMocks.dir),},}));@@ -26,7 +28,7 @@ vi.mock('../../maker-host/logger-adapter.js', () => ({vi.mock('../ownerScopedStorage.js', () => ({ownerScopedImUserDataPath: (...parts: string[]) =>- scopeMocks.join('/tmp/xdt-maker-test', 'owners', scopeMocks.owner, ...parts),+ scopeMocks.join(scopeMocks.dir, 'owners', scopeMocks.owner, ...parts),claimLegacyImPath: scopeMocks.claimLegacy,}));@@ -42,11 +44,22 @@ import {writeImDefaultSettingsPatch,} from '../defaultSettingsStore';-const settingsDir = '/tmp/xdt-maker-test';+const settingsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-im-defaults-'));const settingsFile = () =>path.join(settingsDir, 'owners', scopeMocks.owner, 'im-default-settings.json');describe('im default settings store', () => {+ it('keeps automatic defaults sparse and retains explicit old-model overrides until reset', () => {+ writeImDefaultSettingsPatch({ groupPermissionMode: 'bypassPermissions' }, 'feishu');+ expect(readImDefaultSettings('feishu').agents['claude-code'].model).toBe('');+ expect(JSON.parse(fs.readFileSync(settingsFile(), 'utf-8')).channels.feishu).toEqual({ groupPermissionMode: 'bypassPermissions' });+ const manual = { providerId: 'openai', model: 'old-but-explicit', effort: 'high' as const };+ writeImDefaultSettingsPatch({ agentKind: 'codex', agents: { codex: manual } }, 'feishu');+ expect(readImDefaultSettings('feishu').agents.codex).toEqual(manual);+ writeImDefaultSettingsPatch({ agentKind: IM_DEFAULT_SETTINGS.agentKind, agents: IM_DEFAULT_SETTINGS.agents }, 'feishu');+ expect(readImDefaultSettings('feishu').groupPermissionMode).toBe('bypassPermissions');+ expect(JSON.parse(fs.readFileSync(settingsFile(), 'utf-8')).channels.feishu).toEqual({ groupPermissionMode: 'bypassPermissions' });+ });it('persists the shared location per channel and can switch back to local', () => {const route = { ...IM_DEFAULT_SETTINGS.agents.codex, providerId: 'openai', agentDeviceId: 'share:alice' };writeImDefaultSettingsPatch({ agentKind: 'codex', agents: { codex: route } }, 'feishu');@@ -56,6 +69,7 @@ describe('im default settings store', () => {expect(readImDefaultSettings('feishu').agents.codex.agentDeviceId).toBeUndefined();});beforeEach(() => {+ scopeMocks.dir = settingsDir;scopeMocks.join = path.join;scopeMocks.owner = 'cloud-a';scopeMocks.claimLegacy.mockReset();@@ -194,7 +208,7 @@ describe('im default settings store', () => {// legacy root mirror 是 resolved 满射快照(global 才做 diff),pi 槽为系统默认。pi: {providerId: null,- model: 'claude-sonnet-5',+ model: '',effort: 'high',},});diff --git a/apps/desktop/src/main/im/__tests__/parseDefaultSettingsPatch.test.ts b/apps/desktop/src/main/im/__tests__/parseDefaultSettingsPatch.test.tsindex be1b19b183..ab8e77dbe6 100644--- a/apps/desktop/src/main/im/__tests__/parseDefaultSettingsPatch.test.ts+++ b/apps/desktop/src/main/im/__tests__/parseDefaultSettingsPatch.test.ts@@ -14,6 +14,10 @@ import {import { parseImDefaultSettingsPatch } from '../parseDefaultSettingsPatch.js';describe('parseImDefaultSettingsPatch', () => {+ it('accepts restoring automatic selection but never an empty remote route', () => {+ expect(parseImDefaultSettingsPatch({ agents: IM_DEFAULT_SETTINGS.agents }).agents).toEqual(IM_DEFAULT_SETTINGS.agents);+ expect(() => parseImDefaultSettingsPatch({ agents: { codex: { model: '', agentDeviceId: 'share:alice', providerId: 'openai' } } })).toThrow('remote model required');+ });it('preserves a shared route and clears its location when selecting local', () => {const shared = { providerId: 'openai', model: 'gpt-5.5', effort: 'high', agentDeviceId: 'share:alice' };expect(parseImDefaultSettingsPatch({ agents: { codex: shared } }).agents?.codex).toEqual(shared);diff --git a/apps/desktop/src/main/im/defaultSessionSettings.ts b/apps/desktop/src/main/im/defaultSessionSettings.tsindex a23ceab7e4..b80e028c8d 100644--- a/apps/desktop/src/main/im/defaultSessionSettings.ts+++ b/apps/desktop/src/main/im/defaultSessionSettings.ts@@ -7,6 +7,7 @@*/import type { AgentKind, Effort, PermissionMode } from '@cindy/maker-core';+import { resolveAutomaticImSettings, resolvedImDefaultFingerprint, usesAutomaticImModel } from '../../shared/imAutomaticModel.js';import {chatEligibleSourcesForModel,connectedProvidersForAgent,@@ -28,6 +29,9 @@ import {IM_DEFAULT_SETTINGS,type ImDefaultAgentSettings,type ImDefaultSettingsChannel,+ type ImDefaultSettings,+ type ImDefaultAgentKind,+ isUnconditionalTurnPolicyChannel,} from '../../shared/imDefaultSettings.js';import { createLogger } from '../logger';import { getMaker } from '../maker-host';@@ -39,6 +43,36 @@ import type { ImOrchestratorConfig } from './shared/types';const log = createLogger('im:defaults');+/** Read-only projection; never save the resolved automatic route back as a user preference. */+export async function resolveImAutomaticDefaults<T extends ImDefaultSettings>(+ raw: T,+ channel?: ImDefaultSettingsChannel,+ providerSnapshot?: ProviderView[] | null,+ agentKind?: ImDefaultAgentKind,+): Promise<T | null> {+ const providers = providerSnapshot === undefined ? await listProvidersForDefaults() : providerSnapshot;+ if (!providers) return null;+ return resolveAutomaticImSettings(raw, providers, {+ agentKind,+ allowAgent: channel && isUnconditionalTurnPolicyChannel(channel)+ ? (agent) => getMaker().getCapabilities(agent).turnPermissionPolicy?.supported.supported === true+ : undefined,+ });+}++/** Resolve every automatic slot for settings/official workspace rows, using one catalog snapshot. */+export async function projectImDefaultSettings<T extends ImDefaultSettings>(raw: T, channel?: ImDefaultSettingsChannel): Promise<T> {+ const providers = await listProvidersForDefaults();+ let view = usesAutomaticImModel(raw)+ ? await resolveImAutomaticDefaults(raw, channel, providers) ?? raw : raw;+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {+ if (agent === view.agentKind || raw.agents[agent].model) continue;+ const resolved = await resolveImAutomaticDefaults(raw, channel, providers, agent);+ if (resolved) view = { ...view, agents: { ...view.agents, [agent]: resolved.agents[agent] } };+ }+ return view;+}+export interface ResolvedImSessionDefaults {agentDeviceId?: string | null;agentKind: AgentKind;@@ -72,6 +106,17 @@ export async function resolveImSessionDefaults(channel?: ImDefaultSettingsChannel,): Promise<ResolvedImSessionDefaults> {const raw = readImDefaultSettings(channel);+ if (usesAutomaticImModel(raw)) {+ const resolved = await resolveImAutomaticDefaults(raw, channel, providerSnapshot);+ if (!resolved) throw new Error('im default session has no available chat model; connect or enable a model in settings');+ return {+ agentKind: resolved.agentKind,+ ...resolved.agents[resolved.agentKind],+ permissionMode: raw.permissionMode ?? config.defaultPermissionMode,+ fastMode: false,+ fingerprint: resolvedImDefaultFingerprint(fingerprintImDefaultSettings(raw), resolved),+ };+ }const remote = raw.agents[raw.agentKind];if (remote.agentDeviceId) {const { model } = await readImRemoteProviderRoute({ ...remote, agentDeviceId: remote.agentDeviceId, agentKind: raw.agentKind });@@ -225,12 +270,7 @@ function pickModel(});return { agentKind: systemAgent, modelId: lenient.model };}- log.warn('im default: all model sources exhausted; using hardcoded system default', {- requestedAgent,- channelAgent: config.agentKind,- channelModel: config.defaultModel,- });- return { agentKind: systemAgent, modelId: systemFallbackModel };+ throw new Error('im default session has no available chat model; connect or enable a model in settings');}function hasModel(diff --git a/apps/desktop/src/main/im/parseDefaultSettingsPatch.ts b/apps/desktop/src/main/im/parseDefaultSettingsPatch.tsindex ec72ed06fe..977405be66 100644--- a/apps/desktop/src/main/im/parseDefaultSettingsPatch.ts+++ b/apps/desktop/src/main/im/parseDefaultSettingsPatch.ts@@ -103,7 +103,7 @@ function parseImDefaultAgentSettings(: null;}if ('model' in input) {- if (typeof input.model !== 'string' || !input.model.trim()) {+ if (typeof input.model !== 'string' || (input.model.length > 0 && !input.model.trim())) {throwIpcError('INVALID_PARAMS', 'im default model required (string)');}model = input.model.trim();@@ -115,5 +115,6 @@ function parseImDefaultAgentSettings(effort = input.effort;}if (agentDeviceId && !providerId) throwIpcError('INVALID_PARAMS', 'remote providerId required');+ if (agentDeviceId && !model) throwIpcError('INVALID_PARAMS', 'remote model required');return { providerId, model, effort, ...(agentDeviceId ? { agentDeviceId } : {}) };}diff --git a/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.ts b/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.tsindex 06998ee355..df1daae913 100644--- a/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/channelDefaultRouteSync.test.ts@@ -211,6 +211,21 @@ beforeEach(() => {});describe('syncUnderLock', () => {+ it('rechecks an automatic default after catalog changes without replacing manual task choices', async () => {+ mocks.fingerprint.mockReturnValue('automatic-intent');+ await insertTask('following', OLD, { record: buildImDefaultRouteRecord('resolved-old', OLD) });+ await insertTask('manual', NEW, { record: buildImDefaultRouteRecord('resolved-old', OLD) });+ mocks.resolveDefaults.mockResolvedValue({ ...OLD, fingerprint: 'resolved-old' });+ await sync().syncUnderLock('following');+ expect(mocks.applyRoute).not.toHaveBeenCalled();+ mocks.resolveDefaults.mockResolvedValue({ ...NEW, fingerprint: 'resolved-new' });+ await sync().syncUnderLock('following');+ expect((await rowOf('following')).model).toBe(NEW.model);+ expect(mocks.applyRoute).toHaveBeenCalledTimes(1);+ await sync().syncUnderLock('manual');+ expect(mocks.applyRoute).toHaveBeenCalledTimes(1);+ expect((await rowOf('manual')).model).toBe(NEW.model);+ });it('Auto 被服务端挪到另一家 Cindy 来源、任务已跟过去时,仍算在跟随渠道默认', async () => {const auto = 'auto/group-1';const view = (id: string, source: string, models: string[]) => ({diff --git a/apps/desktop/src/main/im/shared/channelDefaultRouteSync.ts b/apps/desktop/src/main/im/shared/channelDefaultRouteSync.tsindex 0ebaac0922..05ed5a37ec 100644--- a/apps/desktop/src/main/im/shared/channelDefaultRouteSync.ts+++ b/apps/desktop/src/main/im/shared/channelDefaultRouteSync.ts@@ -216,6 +216,9 @@ export function createDefaultRouteFollower(deps: {// 的系统意图, 调用方必须暂缓通用意图应用(PR #5155 review P2)。if (!providers) return 'defer-unknown';const defaults = await deps.resolveTarget(providers);+ // Automatic settings are stable while their catalog-resolved route may change.+ // Skip writes when re-resolution confirms the last adopted route is still current.+ if (defaults.fingerprint === record.fp && !record.pendingRoute) return null;const target: ImDefaultRoute = {agentKind: defaults.agentKind,model: defaults.model,diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.tsindex cac0c1bbe5..2e26136b34 100644--- a/apps/desktop/src/main/im/wechat/WechatIM.ts+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts@@ -1021,6 +1021,9 @@ export class WechatIM extends BaseIM implements RichChannelIM {if (!committed.committed) return;cursor = result.cursor;failures = 0;+ if (this.#state.phase === 'reconnecting') {+ this.#setState({ ...this.#state, phase: 'connected', errorCode: undefined });+ }if (result.messages.length > 0) {this.#setState({...this.#state,diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.tsindex 40b3f6d683..c6bbc243b7 100644--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts@@ -28,6 +28,27 @@ vi.mock('../mediaStaging', async (importOriginal) => {});describe('WechatIM host boundary', () => {+ it('clears reconnecting after an empty successful poll', async () => {+ vi.useFakeTimers();+ const { im, transport, db } = restoredConnection(() => 0);+ const poll = vi.spyOn(transport, 'poll');+ poll.mockRejectedValueOnce(new WechatIlinkError('NETWORK_ERROR', 'offline', true));+ poll.mockResolvedValueOnce({ cursor: 'recovered', messages: [] });+ vi.mocked(db.tx).mockImplementation((async (name: string) =>+ name === 'wechatCommitPollBatch' ? {+ committed: true, insertedTaskIds: [], duplicateTaskIds: [], rejectedTaskIds: [],+ } : null) as DbClient['tx']);+ try {+ await im.init();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(poll).toHaveBeenCalledTimes(3);+ expect(im.getState().phase).toBe('connected');+ expect(im.getState().errorCode).toBeUndefined();+ } finally {+ await im.dispose();+ vi.useRealTimers();+ }+ });// Exercise the durable inbox through the public host lifecycle. Only the// credential-verified owner can request native permissions on a resolved companion route.diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 85fda34bc1..d51c94c757 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -2371,6 +2371,7 @@ contextBridge.exposeInMainWorld('electronAPI', {// ── Discord Bot (Settings → IM Bot tab) ──// 用户本机自建 Discord App + Bot Token;凭证保存在本机 secrets。discordBot: {+ reconnect: () => ipcRenderer.invoke('discordBot:reconnect'),getStatus: (): Promise<{status:| { kind: 'idle' }diff --git a/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx b/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsxindex 34446d03ef..c34c935bd5 100644--- a/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx@@ -1,4 +1,5 @@import { Button } from '@/components/ui/button';+import { ImConnectionError, ImReconnectButton } from './ImConnectionRecovery';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Loader2, Trash2 } from 'lucide-react';@@ -171,9 +172,10 @@ export function DingTalkBotSection({{bot.validationError}</span>) : bot.status.kind === 'error' ? (- <span className="text-[var(--settings-error-text)]" role="alert">- {t('settings.dingtalkBot.errorHint')}- </span>+ <ImConnectionError+ message={t('settings.dingtalkBot.errorHint')}+ details={bot.status.reason}+ />) : (<span className="text-[var(--settings-source-meta)]">{t('settings.dingtalkBot.formHint')}@@ -182,20 +184,15 @@ export function DingTalkBotSection({</div><div className="flex gap-2">{bot.hasSecret && !bot.appSecret.trim() ? (- <Button+ <ImReconnectButtonvariant="cta"size="lg"loading={bot.isSaving}- type="button"- onClick={() => void bot.reconnect()}- disabled={bot.isSaving}+ onReconnect={bot.reconnect}className="flex-1">- {bot.isSaving && (- <Loader2 size={14} className="animate-spin motion-reduce:animate-none" />- )}{t('settings.dingtalkBot.reconnect')}- </Button>+ </ImReconnectButton>) : (<Buttonvariant="cta"diff --git a/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx b/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsxindex 2a4d7a17ed..9cd91c5b62 100644--- a/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx@@ -1,4 +1,5 @@import { Button } from '@/components/ui/button';+import { ImConnectionError, ImSavedConnectionRecovery } from './ImConnectionRecovery';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { Check, ChevronDown, ChevronRight, Eye, EyeOff, Trash2 } from 'lucide-react';@@ -58,6 +59,7 @@ export function DiscordBotSection({isDisconnecting,canConnect,connect,+ reconnect,disconnect,} = useDiscordBot();@@ -154,6 +156,13 @@ export function DiscordBotSection({/>) : (<div className="flex flex-col gap-3">+ {hasSavedCreds && ownerUserId && (+ <ImSavedConnectionRecovery+ loading={isSaving}+ disabled={isDisconnecting}+ onReconnect={reconnect}+ />+ )}<labelclassName="text-12 font-medium text-[var(--settings-section-desc)]"style={{ letterSpacing: '0.12px' }}@@ -219,9 +228,7 @@ export function DiscordBotSection({{validationError}</p>) : status.kind === 'error' ? (- <p className="text-12 text-[var(--settings-error-text)]" role="alert">- {status.reason}- </p>+ <ImConnectionError details={status.reason} />) : (<p className="text-12 text-[var(--settings-source-meta)]">{t('settings.discordBot.formHint')}diff --git a/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx b/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsxindex ed8dc8de00..4a381839c9 100644--- a/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Eye, EyeOff, Trash2, Check, RefreshCw } from 'lucide-react';+import { Eye, EyeOff, Trash2, Check, RefreshCw, Link } from 'lucide-react';import { SegmentedControl } from '@/components/ui/segmented-control';import { cn } from '@/lib/utils';@@ -8,7 +8,7 @@ import { useFeishuBot, type FeishuBotService, type FeishuBotStatus } from '@/hooimport { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Button } from '@/components/ui/button';import { Spinner } from '@/components/ui/spinner';-import { Tip } from '@/components/ui/tooltip';+import { ImConnectionError, ImReconnectButton } from './ImConnectionRecovery';import { savedCredentialsNoteKey, shouldShowSavedCredentialsCard } from './feishuBotPresentation';import { ImChannelSettingsCard, useImChannelSettingsSummary } from './ImChannelSettingsCard';import { ImDefaultSettingsSection } from './ImDefaultSettingsSection';@@ -96,6 +96,7 @@ export function FeishuBotSection({}, [hasLoadedState, hasSavedCreds, preferredService, searchActivation, setService]);const showSavedCredentialsCard = shouldShowSavedCredentialsCard(hasSavedCreds);+ const displayStatus = isReconnecting ? 'testing' : status;const canSave = appId.trim().length > 0 && appSecret.trim().length > 0 && !isSaving;const handleClearClick = useCallback(async () => {@@ -134,28 +135,27 @@ export function FeishuBotSection({'border border-[var(--settings-badge-border)]','text-11 font-medium tracking-[0.12px]',)}- style={{ letterSpacing: '0.12px', color: statusTextColor(status) }}+ style={{ letterSpacing: '0.12px', color: statusTextColor(displayStatus) }}role="status"aria-live="polite"- aria-label={t('settings.feishuBot.statusAria', { status: t(statusKey[status]) })}+ aria-label={t('settings.feishuBot.statusAria', { status: t(statusKey[displayStatus]) })}><spanclassName="h-1.5 w-1.5 rounded-full"- style={{ backgroundColor: statusColor(status) }}+ style={{ backgroundColor: statusColor(displayStatus) }}aria-hidden/>- {t(statusKey[status])}+ {t(statusKey[displayStatus])}</span>}>- <ImDefaultSettingsSection channel="feishu" embedded onSummaryChange={setRouteSummary} />- <div className="h-px w-full bg-[var(--border-default)]" />{showSavedCredentialsCard ? (<SavedCredentialsCardappId={appId}service={service}ownerOpenId={ownerOpenId}- status={status}+ status={displayStatus}+ errorMessage={errorMessage}isClearing={isClearing}isReconnecting={isReconnecting}onReconnect={reconnect}@@ -179,6 +179,8 @@ export function FeishuBotSection({onOpenLauncher={openLauncher}/>)}+ <div className="h-px w-full bg-[var(--border-default)]" />+ <ImDefaultSettingsSection channel="feishu" embedded onSummaryChange={setRouteSummary} />{hasSavedCreds && (<><div className="h-px w-full bg-[var(--border-default)]" />@@ -194,6 +196,7 @@ function SavedCredentialsCard(props: {service: FeishuBotService;ownerOpenId: string | null;status: FeishuBotStatus;+ errorMessage: string | null;isClearing: boolean;isReconnecting: boolean;onReconnect: () => Promise<boolean>;@@ -201,73 +204,78 @@ function SavedCredentialsCard(props: {}) {const { t } = useTranslation();const serviceName = t(`settings.feishuBot.services.${props.service}`);+ const isConnecting =+ props.isReconnecting || props.status === 'testing' || props.status === 'reconnecting';+ const hasError =+ !props.isReconnecting && (props.status === 'error' || props.status === 'conflict');+ const reconnectButton = (+ <ImReconnectButton+ variant={props.status === 'connected' ? 'secondary' : 'primary'}+ size="sm"+ loading={props.isReconnecting}+ onReconnect={props.onReconnect}+ disabled={props.isClearing || props.status === 'testing'}+ aria-label={t('settings.feishuBot.connected.reconnect', { service: serviceName })}+ >+ <RefreshCw size={14} />+ {t('settings.feishuBot.saved.reconnect')}+ </ImReconnectButton>+ );return (<div+ data-feishu-connection-card=""className={cn('mt-1 flex flex-col gap-3 rounded-xl p-5','border border-[var(--settings-theme-card-border)]','bg-[var(--settings-theme-card-bg)]',)}>- <div className="flex items-start gap-3">- <div- className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)]"- style={{- color:- props.status === 'connected'- ? 'var(--settings-badge-connected)'- : 'var(--settings-badge-saved)',- }}- >- <Check size={16} />- </div>- <div className="min-w-0 flex-1">- <div className="flex items-center gap-1.5">- <div className="text-13 font-medium text-[var(--settings-section-title)]">- {t(+ {hasError ? (+ <ImConnectionError+ role="status"+ message={t('settings.feishuBot.saved.errorHeading', { service: serviceName })}+ description={t(savedCredentialsNoteKey(props.status, props.errorMessage))}+ details={props.errorMessage ?? undefined}+ actions={reconnectButton}+ />+ ) : (+ <div className="flex items-start gap-3" role="status">+ <div+ className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-[var(--settings-badge-border)] bg-[var(--settings-badge-bg)]"+ style={{+ color:props.status === 'connected'- ? 'settings.feishuBot.connected.heading'- : 'settings.feishuBot.saved.heading',- { service: serviceName },- )}- </div>- <Tip- text={t('settings.feishuBot.connected.reconnect', { service: serviceName })}- side="top"- delay={200}- >- {/* Keep the trigger hoverable while the inner button is disabled. */}- <span className="inline-flex shrink-0">- <button- type="button"- onClick={() => void props.onReconnect()}- disabled={props.isReconnecting || props.isClearing}- aria-label={t('settings.feishuBot.connected.reconnect', {- service: serviceName,- })}- className={cn(- 'inline-flex h-7 w-7 select-none items-center justify-center rounded-full',- 'text-[var(--settings-section-desc)] transition-colors',- 'hover:bg-[var(--surface-hover)] hover:text-[var(--settings-section-title)]',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',- (props.isReconnecting || props.isClearing) && 'cursor-not-allowed opacity-40',- )}- >- <Spinner- icon={RefreshCw}- size={14}- strokeWidth={2}- spinning={props.isReconnecting}- />- </button>- </span>- </Tip>+ ? 'var(--settings-badge-connected)'+ : 'var(--settings-badge-saved)',+ }}+ >+ {isConnecting ? (+ <Spinner size={16} />+ ) : props.status === 'connected' ? (+ <Check size={16} />+ ) : (+ <Link size={16} />+ )}</div>- <div className="mt-1 text-12 leading-[1.6] text-[var(--settings-section-desc)]">- {t(savedCredentialsNoteKey(props.status))}+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <div className="text-13 font-medium text-[var(--settings-section-title)]">+ {t(+ isConnecting+ ? 'settings.feishuBot.status.connecting'+ : props.status === 'connected'+ ? 'settings.feishuBot.connected.heading'+ : 'settings.feishuBot.saved.heading',+ { service: serviceName },+ )}+ </div>+ </div>+ <div className="mt-1 text-12 leading-[1.6] text-[var(--settings-section-desc)]">+ {t(savedCredentialsNoteKey(props.isReconnecting ? 'testing' : props.status))}+ </div></div></div>- </div>+ )}<div className="grid gap-2 text-12 text-[var(--settings-section-desc)]"><div className="flex justify-between gap-4"><span>{t('settings.feishuBot.connected.serviceLabel')}</span>@@ -288,15 +296,15 @@ function SavedCredentialsCard(props: {</span></div></div>- <div className="flex gap-2 pt-1">+ <div className="flex flex-wrap items-center gap-2 pt-1">+ {!hasError && reconnectButton}<Button- variant="secondary"- size="lg"+ tone="quiet"+ size="sm"loading={props.isClearing}type="button"onClick={props.onClear}- disabled={props.isClearing}- className="flex-1"+ disabled={props.isClearing || props.isReconnecting}><Trash2 size={13} />{t('settings.feishuBot.connected.clear')}diff --git a/apps/desktop/src/renderer/components/settings/ImConnectionRecovery.tsx b/apps/desktop/src/renderer/components/settings/ImConnectionRecovery.tsxnew file mode 100644index 0000000000..aee1d2fecf--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/ImConnectionRecovery.tsx@@ -0,0 +1,64 @@+import type { ComponentProps } from 'react';+import { useTranslation } from 'react-i18next';++import { Button, type ButtonProps } from '@/components/ui/button';+import { ErrorNotice } from '@/components/ui/error-notice';++type ImConnectionErrorProps = Partial<+ Pick<+ ComponentProps<typeof ErrorNotice>,+ 'message' | 'description' | 'details' | 'actions' | 'role'+ >+>;++/** All bot settings use the same quiet error surface and redacted, collapsed details. */+export function ImConnectionError({ message, role = 'alert', ...props }: ImConnectionErrorProps) {+ const { t } = useTranslation();+ return (+ <ErrorNotice+ {...props}+ role={role}+ message={message ?? t('settings.imConnection.failed')}+ className="border-0 bg-transparent p-0"+ />+ );+}++type ImReconnectButtonProps = Omit<ButtonProps, 'onClick'> & {+ onReconnect: () => unknown;+};++/** Credential lookup and channel-specific recovery remain with each hook. */+export function ImReconnectButton({+ onReconnect,+ loading,+ disabled,+ children,+ ...props+}: ImReconnectButtonProps) {+ const { t } = useTranslation();+ return (+ <Button+ variant="secondary"+ type="button"+ {...props}+ loading={loading}+ disabled={disabled || loading}+ onClick={() => void onReconnect()}+ >+ {children ?? t('settings.imConnection.reconnect')}+ </Button>+ );+}++export function ImSavedConnectionRecovery(props: ImReconnectButtonProps) {+ const { t } = useTranslation();+ return (+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-12 text-[var(--settings-section-desc)]">+ {t('settings.imConnection.savedNote')}+ </p>+ <ImReconnectButton {...props} />+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsxindex 8b51832495..0489e7cc21 100644--- a/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx@@ -38,10 +38,8 @@ import {isImDefaultEffort,} from '../../../shared/imDefaultSettings';import { DefaultOverrideControls } from './DefaultOverrideControls';-import {- buildAgentSettingsPatch,- mergeSettingsPatch,-} from './imDefaultSettingsLogic';+import { Button } from '@/components/ui/button';+import { buildAgentSettingsPatch, mergeSettingsPatch } from './imDefaultSettingsLogic';function vendorKeyFor(agentKind: ImDefaultAgentKind): 'cc' | 'codex' | 'pi' {return agentKind === 'claude-code' ? 'cc' : agentKind;@@ -135,9 +133,7 @@ export function ImDefaultSettingsSection({codex: fromProviders.codex.length? fromProviders.codex: (codex.capabilities?.availableModels ?? []),- pi: fromProviders.pi.length- ? fromProviders.pi- : (pi.capabilities?.availableModels ?? []),+ pi: fromProviders.pi.length ? fromProviders.pi : (pi.capabilities?.availableModels ?? []),};}, [providers, cc.capabilities, codex.capabilities, pi.capabilities]);@@ -180,6 +176,8 @@ export function ImDefaultSettingsSection({const persist = useCallback(async (patch: ImDefaultSettingsPatch) => {if (!settings || pending) return false;+ // A displayed automatic route may use a different engine than the stored empty default.+ if (patch.agents && !patch.agentKind) patch = { ...patch, agentKind: settings.agentKind };const previous = settings;setPending(true);setSettings(mergeSettingsPatch(settings, patch));@@ -227,17 +225,14 @@ export function ImDefaultSettingsSection({}const activeSettings = settings.agents[settings.agentKind];+ const automaticModel = settings.automaticModel ?? !activeSettings.model;// 按选中 Agent 的 capabilities 判断:未声明 / 声明了但 supported.supported !== true// 的 Agent(如 Pi)无法在「无条件挂逐条权限确认」的渠道(个人微信)使用。不写死 Pi——// 未来 Pi 补上该 capability、或新增其它不支持的 Agent 时,此处自动跟随 main 侧// 的 capability 真相,不会误警告 / 漏警告。(Telegram / 钉钉仅在群聊挂 policy,// 主人私聊 Pi 可用,设置 UI 不区分群聊/私聊,故不整体警告。)const selectedAgentCaps =- settings.agentKind === 'claude-code'- ? cc- : settings.agentKind === 'codex'- ? codex- : pi;+ settings.agentKind === 'claude-code' ? cc : settings.agentKind === 'codex' ? codex : pi;const selectedAgentCapabilitiesReady =!selectedAgentCaps.loading &&selectedAgentCaps.error === null &&@@ -268,7 +263,9 @@ export function ImDefaultSettingsSection({providerId: string | null = activeSettings.providerId,reconciledEffort?: Effort,) => {- const nextProviderId = agentDeviceId ? providerId : resolveProviderId(settings.agentKind, model, providerId);+ const nextProviderId = agentDeviceId+ ? providerId+ : resolveProviderId(settings.agentKind, model, providerId);const effort = isImDefaultEffort(reconciledEffort)? reconciledEffort: resolveEffort(settings.agentKind, model, activeSettings.effort);@@ -332,6 +329,35 @@ export function ImDefaultSettingsSection({<span className="text-12 font-medium text-[var(--text-secondary)]">{t('settings.imBot.defaults.modelLabel')}</span>+ <div className="flex flex-wrap items-center justify-between gap-2 text-12 text-[var(--text-secondary)]">+ <span>+ {t(+ automaticModel+ ? 'settings.imBot.defaults.automatic'+ : 'settings.imBot.defaults.fixed',+ )}+ </span>+ {!automaticModel && (+ <Button+ size="sm"+ tone="quiet"+ disabled={pending}+ onClick={() =>+ void persist({+ agentKind: IM_DEFAULT_SETTINGS.agentKind,+ agents: IM_DEFAULT_SETTINGS.agents,+ })+ }+ >+ {t('settings.imBot.defaults.useAutomatic')}+ </Button>+ )}+ </div>+ {automaticModel && !activeSettings.model && (+ <p className="text-12 text-[var(--text-secondary)]">+ {t('settings.imBot.defaults.automaticUnavailable')}+ </p>+ )}<ModelSelectorremoteAgent={{ devices: sharedDevices.devices, selectedDeviceId: agentDeviceId }}fastModeConfigurable={false}diff --git a/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx b/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsxindex 2ebbefe052..715f8683b7 100644--- a/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx@@ -1,4 +1,5 @@import { Button } from '@/components/ui/button';+import { ImConnectionError, ImSavedConnectionRecovery } from './ImConnectionRecovery';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import {@@ -263,9 +264,10 @@ export function TelegramBotSection({{validationError}</p>) : status.kind === 'error' ? (- <p className="text-12 text-[var(--settings-error-text)]" role="alert">- {describeTelegramStatusFailure(status, t)}- </p>+ <ImConnectionError+ message={describeTelegramStatusFailure(status, t)}+ details={status.reason}+ />) : (<p className="text-12 text-[var(--settings-source-meta)]">{t('settings.telegramBot.formHint')}@@ -289,6 +291,14 @@ export function TelegramBotSection({)}</div>+ {hasSavedCreds && ownerUserId && (+ <ImSavedConnectionRecovery+ loading={isTogglingOnline}+ disabled={isSaving || isDisconnecting}+ onReconnect={() => setOnline(true)}+ />+ )}+<Buttonvariant="cta"size="lg"@@ -413,9 +423,7 @@ function ConnectedCard(props: {<div className="grid gap-2 text-12 text-[var(--settings-section-desc)]"><div className="flex justify-between gap-4"><span>{t('settings.telegramBot.connected.botLabel')}</span>- <span className="font-medium text-[var(--settings-section-title)]">- {props.botLabel}- </span>+ <span className="font-medium text-[var(--settings-section-title)]">{props.botLabel}</span></div><div className="flex justify-between gap-4"><span>{t('settings.telegramBot.connected.ownerLabel')}</span>diff --git a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsxindex fa52da6682..32fd7b8ac5 100644--- a/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx+++ b/apps/desktop/src/renderer/components/settings/WecomBotSection.tsx@@ -1,4 +1,5 @@import { Button } from '@/components/ui/button';+import { ImConnectionError, ImReconnectButton } from './ImConnectionRecovery';import { useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { Check, Eye, EyeOff, Send, Trash2 } from 'lucide-react';@@ -197,10 +198,12 @@ export function WecomBotSection({{showSecret ? <Eye size={18} /> : <EyeOff size={18} />}</button></div>- {validationError || status.kind === 'error' ? (+ {validationError ? (<p className="text-12 text-[var(--settings-error-text)]" role="alert">- {validationError ?? (status.kind === 'error' ? status.reason : '')}+ {validationError}</p>+ ) : status.kind === 'error' ? (+ <ImConnectionError details={status.reason} />) : (<p className="text-12 text-[var(--settings-source-meta)]">{t('settings.wecomBot.ownerHint')}@@ -208,17 +211,16 @@ export function WecomBotSection({)}<div className="flex flex-col gap-2 sm:flex-row">{botId.trim() && !secret.trim() ? (- <Button+ <ImReconnectButtonvariant="cta"size="lg"loading={isSaving || status.kind === 'connecting'}- type="button"- onClick={() => void reconnect()}+ onReconnect={reconnect}disabled={!canReconnect}className="flex-1">{t('settings.wecomBot.reconnect')}- </Button>+ </ImReconnectButton>) : (<Buttonvariant="cta"@@ -341,10 +343,7 @@ export function WecomBotSection({disabled={wecomGroup.busy || !webhookUrl.trim()}onClick={() => {void wecomGroup- .saveAndTest(- webhookUrl.trim(),- t('settings.notifications.wecomGroupTestMessage'),- )+ .saveAndTest(webhookUrl.trim(), t('settings.notifications.wecomGroupTestMessage')).then(() => {setWebhookUrl('');toast.success(t('settings.notifications.wecomGroupSaveSuccess'));diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsxindex b49f043f9d..df84231b36 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/ImDefaultSettingsSection.test.tsx@@ -14,9 +14,10 @@ const capabilityMockState = vi.hoisted(() => ({} | null,}));-vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));+vi.mock('react-i18next', () => {+ const t = (key: string) => key;+ return { useTranslation: () => ({ t }) };+});vi.mock('@/hooks/useAgentCapabilities', () => {// Pi 未声明 turnPermissionPolicy(警告);Claude Code / Codex 声明且受支持(不警告)。@@ -102,6 +103,19 @@ function defaults(agentKind: ImDefaultSettingsState['agentKind']): ImDefaultSett}describe('ImDefaultSettingsSection Pi channel warning', () => {+ it('restores automatic selection without saving the displayed model or resetting permissions', async () => {+ const automatic = { ...defaults('codex'), automaticModel: true };+ const save = vi.fn(async (_patch: unknown) => automatic);+ window.electronAPI.maker.imDefaultSettingsSet = save;+ render(<ImDefaultSettingsSection channel="feishu" />);+ fireEvent.click(await screen.findByText('settings.imBot.defaults.useAutomatic'));+ await screen.findByText('settings.imBot.defaults.automatic');+ expect(save).toHaveBeenCalledWith({ agentKind: IM_DEFAULT_SETTINGS.agentKind, agents: IM_DEFAULT_SETTINGS.agents }, 'feishu');+ expect(screen.queryByText('settings.imBot.defaults.useAutomatic')).toBeNull();+ fireEvent.click(screen.getByTestId('select-codex'));+ await waitFor(() => expect(save).toHaveBeenCalledTimes(2));+ expect(save.mock.calls[1]?.[0]).toMatchObject({ agentKind: 'codex', agents: { codex: { model: 'gpt-5.5' } } });+ });it('saves a shared model and its location together without local catalog membership', async () => {const save = vi.fn(async () => defaults('codex'));window.electronAPI.maker.imDefaultSettingsSet = save;diff --git a/apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts b/apps/desktop/src/renderer/components/settings/feishuBotPresentation.tsindex 73b030fb70..73646a8540 100644--- a/apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts+++ b/apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts@@ -6,7 +6,7 @@ export function shouldShowSavedCredentialsCard(hasSavedCredentials: boolean): bo}/** Maps the live transport state to an actionable explanation inside the bound card. */-export function savedCredentialsNoteKey(status: FeishuBotStatus): string {+export function savedCredentialsNoteKey(status: FeishuBotStatus, error?: string | null): string {switch (status) {case 'connected':return 'settings.feishuBot.connected.note';@@ -17,6 +17,15 @@ export function savedCredentialsNoteKey(status: FeishuBotStatus): string {case 'conflict':return 'settings.feishuBot.saved.conflictNote';case 'error':+ if (/auth_failed|code: 514|App ID.*App Secret.*不正确/i.test(error ?? '')) {+ return 'settings.feishuBot.saved.credentialsErrorNote';+ }+ if (/timed?\s*out|ETIMEDOUT/i.test(error ?? '')) {+ return 'settings.feishuBot.saved.timeoutErrorNote';+ }+ if (/unable to connect|ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ECONNRESET|网络/i.test(error ?? '')) {+ return 'settings.feishuBot.saved.networkErrorNote';+ }return 'settings.feishuBot.saved.errorNote';case 'idle':return 'settings.feishuBot.saved.idleNote';diff --git a/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.tsindex 9f10a9ba5f..f640ef70d3 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useDiscordBot.test.ts@@ -62,6 +62,7 @@ function installDiscordApi(payload,})),disconnect: vi.fn(async () => ({ status: { kind: 'idle' } as DiscordBotTransportStatus })),+ reconnect: vi.fn(async () => ({ status: { kind: 'connected', appId: 'bot' } as DiscordBotTransportStatus, ownerUserId: '12345678901234567' })),setLifecycleAnnouncement: vi.fn(async (enabled: boolean) => ({ok: true,lifecycleAnnouncement: enabled,@@ -78,6 +79,32 @@ function installDiscordApi(}describe('useDiscordBot', () => {+ it.each(['connecting', 'connected'] as const)('handles reconnect IPC rejection after a %s push', async (kind) => {+ const api = installDiscordApi({ kind: 'error', reason: 'offline' });+ api.reconnect.mockImplementationOnce(async () => {+ const update: DiscordBotTransportStatus = kind === 'connected'+ ? { kind, appId: 'bot' } : { kind };+ api.onStatusChange.mock.calls[0][0]({ status: update });+ throw new Error('IPC interrupted');+ });+ const { result } = renderHook(() => useDiscordBot());+ await waitFor(() => expect(result.current.status.kind).toBe('error'));+ await act(() => result.current.reconnect());+ expect(result.current.status.kind).toBe(kind === 'connected' ? 'connected' : 'error');+ expect(result.current.isSaving).toBe(false);+ });++ it('reconnects with stored credentials without requiring a token draft', async () => {+ const api = installDiscordApi({ kind: 'error', reason: 'network down' });+ const { result } = renderHook(() => useDiscordBot());+ await waitFor(() => expect(result.current.status.kind).toBe('error'));+ await act(() => result.current.reconnect());+ expect(api.reconnect).toHaveBeenCalledOnce();+ expect(api.setConfig).not.toHaveBeenCalled();+ expect(result.current.status.kind).toBe('connected');+ expect(result.current.token).toBe('');+ });+beforeEach(() => {vi.clearAllMocks();delete (window as unknown as { electronAPI?: unknown }).electronAPI;diff --git a/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.tsindex 6b4131ed30..985ae80e70 100644--- a/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts+++ b/apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts@@ -1,6 +1,7 @@// @vitest-environment jsdomimport { act, renderHook, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useFeishuBot, type FeishuBotStatus } from '../useFeishuBot';vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -40,6 +41,7 @@ type RegistrationListener = (payload: {type FeishuState = {status: FeishuBotStatus;+ error?: string;appId: string | null;appSecret: string | null;hasSecret: boolean;@@ -82,16 +84,78 @@ function installFeishuApi() {return { api, statusListeners, registrationListeners };}-let useFeishuBot: typeof import('../useFeishuBot').useFeishuBot;-describe('useFeishuBot', () => {- beforeEach(async () => {- vi.resetModules();+ beforeEach(() => {vi.clearAllMocks();delete (window as unknown as { electronAPI?: unknown }).electronAPI;- ({ useFeishuBot } = await import('../useFeishuBot'));});+ // Unit regression: reconnect previously overwrote newer transport status and+ // only toasted failures. These cases drive the real hook through the IPC API;+ // existing coverage only checks initial hydration and registration races.+ it.each(['error', 'connected'] as const)(+ 'uses the latest %s state and reason after a failed reconnect verdict',+ async (status) => {+ const { api } = installFeishuApi();+ const hook = renderHook(() => useFeishuBot());+ await waitFor(() => expect(hook.result.current.hasLoadedState).toBe(true));+ api.reconnect.mockResolvedValueOnce({ verdict: 'error' });+ api.getState.mockResolvedValueOnce({+ status,+ error: status === 'error' ? 'connect ETIMEDOUT' : undefined,+ appId: 'cli_test',+ appSecret: null,+ hasSecret: true,+ ownerOpenId: null,+ lifecycleAnnouncement: true,+ });+ await act(async () => {+ await hook.result.current.reconnect();+ });+ expect(hook.result.current.status).toBe(status);+ expect(hook.result.current.errorMessage).toBe(+ status === 'error' ? 'connect ETIMEDOUT' : null,+ );+ expect(hook.result.current.hasSavedCreds).toBe(true);+ },+ );++ it.each([false, true])(+ 'keeps a rejected reconnect visible (connecting push: %s)',+ async (pushConnecting) => {+ const { api, statusListeners } = installFeishuApi();+ const hook = renderHook(() => useFeishuBot());+ await waitFor(() => expect(hook.result.current.hasLoadedState).toBe(true));+ api.reconnect.mockImplementationOnce(async () => {+ if (pushConnecting) {+ for (const listener of statusListeners)+ listener({+ status: 'testing',+ botAppId: 'cli_test',+ ownerOpenId: null,+ });+ }+ throw new Error('connection failed');+ });+ await act(async () => {+ await hook.result.current.reconnect();+ });+ expect(hook.result.current.status).toBe('error');+ expect(hook.result.current.errorMessage).toBe('logic.toasts.feishuBotReconnectFailed');+ expect(hook.result.current.isReconnecting).toBe(false);+ act(() => {+ for (const listener of statusListeners)+ listener({+ status: 'connected',+ botAppId: 'cli_test',+ ownerOpenId: null,+ });+ });+ expect(hook.result.current.status).toBe('connected');+ expect(hook.result.current.errorMessage).toBeNull();+ },+ );+it('updates the live owner and module cache when main claims the first sender', async () => {const { api, statusListeners } = installFeishuApi();api.getState.mockResolvedValueOnce({diff --git a/apps/desktop/src/renderer/hooks/useDiscordBot.ts b/apps/desktop/src/renderer/hooks/useDiscordBot.tsindex bcf0103f44..16c949a4e7 100644--- a/apps/desktop/src/renderer/hooks/useDiscordBot.ts+++ b/apps/desktop/src/renderer/hooks/useDiscordBot.ts@@ -28,6 +28,7 @@ export interface UseDiscordBotReturn {isDisconnecting: boolean;canConnect: boolean;connect: () => Promise<boolean>;+ reconnect: () => Promise<void>;disconnect: () => Promise<void>;}@@ -45,6 +46,8 @@ export function useDiscordBot(): UseDiscordBotReturn {const [isSaving, setIsSaving] = useState(false);const [isDisconnecting, setIsDisconnecting] = useState(false);const lifecycleRequestVersionRef = useRef(0);+ const statusVersionRef = useRef(0);+ const latestStatusRef = useRef(status);useEffect(() => {let cancelled = false;@@ -80,6 +83,8 @@ export function useDiscordBot(): UseDiscordBotReturn {useEffect(() => {const unsub = window.electronAPI.discordBot.onStatusChange((update) => {+ statusVersionRef.current += 1;+ latestStatusRef.current = update.status;setStatus(update.status);cachedState = {ownerUserId: cachedState?.ownerUserId ?? '',@@ -170,6 +175,33 @@ export function useDiscordBot(): UseDiscordBotReturn {}}, [isSaving, lifecycleAnnouncement, ownerUserId, t, token]);+ const reconnect = useCallback(async () => {+ if (isSaving || isDisconnecting) return;+ setIsSaving(true);+ setValidationError(null);+ setStatus({ kind: 'connecting' });+ latestStatusRef.current = { kind: 'connecting' };+ const version = statusVersionRef.current;+ try {+ const result = await window.electronAPI.discordBot.reconnect();+ if (version === statusVersionRef.current) {+ setStatus(result.status);+ if (cachedState) cachedState = { ...cachedState, status: result.status };+ }+ } catch (err) {+ log.error('reconnect failed:', err instanceof Error ? err.message : String(err));+ if (version === statusVersionRef.current || latestStatusRef.current.kind === 'connecting') {+ const failed: DiscordBotTransportStatus = {+ kind: 'error', reason: t('logic.toasts.discordBotConnectFailed'),+ };+ setStatus(failed);+ if (cachedState) cachedState = { ...cachedState, status: failed };+ }+ } finally {+ setIsSaving(false);+ }+ }, [isSaving, isDisconnecting, t]);+const disconnect = useCallback(async () => {if (isDisconnecting) return;setIsDisconnecting(true);@@ -213,6 +245,7 @@ export function useDiscordBot(): UseDiscordBotReturn {isDisconnecting,canConnect,connect,+ reconnect,disconnect,};}diff --git a/apps/desktop/src/renderer/hooks/useFeishuBot.ts b/apps/desktop/src/renderer/hooks/useFeishuBot.tsindex b608baa111..23b992c1f8 100644--- a/apps/desktop/src/renderer/hooks/useFeishuBot.ts+++ b/apps/desktop/src/renderer/hooks/useFeishuBot.ts@@ -20,6 +20,7 @@ import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';import { createLogger } from '@/lib/logger';import { setFeishuNotificationsEnabled } from '@/hooks/useFeishuNotificationSettings';+import { mapIpcErrorToI18nKey } from '@/utils/ipcError';const log = createLogger('useFeishuBot');@@ -120,7 +121,7 @@ export function useFeishuBot(): UseFeishuBotReturn {// 否则 device-code 流程在 main 写完凭证后, renderer 这边 appId/secret// 仍然停留在初始空字符串, 导致 ConnectedCard 显示空 + 跳转链接拼成// /app//event 落到飞书 app 列表页。- const reloadState = useCallback(async (): Promise<void> => {+ const reloadState = useCallback(async (): Promise<FeishuBotStatus | undefined> => {const reloadRequestVersion = ++reloadRequestVersionRef.current;const statusPushVersion = statusPushVersionRef.current;try {@@ -158,6 +159,7 @@ export function useFeishuBot(): UseFeishuBotReturn {ownerOpenId: nextOwnerOpenId,lifecycleAnnouncement: state.lifecycleAnnouncement,};+ return nextStatus;} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.error('getState failed:', msg);@@ -345,36 +347,51 @@ export function useFeishuBot(): UseFeishuBotReturn {}, [isClearing, service, t]);const reconnect = useCallback(async () => {- if (isReconnecting) return false;+ if (isReconnecting || isClearing) return false;setIsReconnecting(true);+ const pushVersion = statusPushVersionRef.current;try {const { verdict } = await window.electronAPI.feishuBot.reconnect();- if (verdict === 'connected') {- setStatus('connected');+ // Re-read the live status and its reason; a startup verdict can be stale+ // by the time it reaches the UI (the SDK may already have recovered).+ const refreshedStatus = await reloadState();+ const liveStatus =+ refreshedStatus ??+ (statusPushVersionRef.current !== pushVersion+ ? (latestStatusPushRef.current?.status ?? verdict)+ : verdict);+ if (!refreshedStatus && statusPushVersionRef.current === pushVersion) {+ setStatus(liveStatus);setErrorMessage(null);- if (cachedState) {- cachedState = { ...cachedState, status: 'connected', errorMessage: null };- }+ if (cachedState) cachedState = { ...cachedState, status: liveStatus, errorMessage: null };+ }+ if (liveStatus === 'connected') {toast.success(t('logic.toasts.feishuBotReconnected'));return true;}- if (verdict === 'conflict') {- setStatus('conflict');- toast.error(t('logic.toasts.feishuBotConflict'));- return false;- }- setStatus('error');- toast.error(t('logic.toasts.feishuBotReconnectFailed'));return false;} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.error('reconnect failed:', msg);- toast.error(t('logic.toasts.feishuBotReconnectFailed'));+ // Preserve a newer terminal status, but never leave a failed attempt spinning.+ const pushedStatus = latestStatusPushRef.current?.status;+ if (+ statusPushVersionRef.current === pushVersion ||+ pushedStatus === 'testing' ||+ pushedStatus === 'reconnecting'+ ) {+ const message = t(+ mapIpcErrorToI18nKey(err, { fallback: 'logic.toasts.feishuBotReconnectFailed' }),+ );+ setStatus('error');+ setErrorMessage(message);+ if (cachedState) cachedState = { ...cachedState, status: 'error', errorMessage: message };+ }return false;} finally {setIsReconnecting(false);}- }, [isReconnecting, t]);+ }, [isClearing, isReconnecting, reloadState, t]);const setLifecycleAnnouncement = useCallback((enabled: boolean) => {setLifecycleAnnouncementState(enabled);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 768df0944c..8f9ec50b9b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1480,6 +1480,11 @@}},"settings": {+ "imConnection": {+ "reconnect": "Reconnect",+ "savedNote": "Your saved binding is retained. You can retry the connection.",+ "failed": "Bot connection failed"+ },"title": "Settings","search": {"ariaLabel": "Search settings",@@ -4101,7 +4106,12 @@"connectingNote": "Bot credentials are saved. Establishing the connection now.","reconnectingNote": "Bot credentials are saved. Restoring the connection now.","conflictNote": "Bot credentials are saved, but this App ID is currently in use on another device.",- "errorNote": "Bot credentials are saved, but the connection failed. Select reconnect to try again.",+ "errorNote": "The bot is still bound, but could not connect.",+ "errorHeading": "{{service}} bot connection failed",+ "reconnect": "Reconnect Bot",+ "networkErrorNote": "The IM service is unreachable. Check your network connection.",+ "timeoutErrorNote": "The connection timed out. Reconnect without unbinding the bot.",+ "credentialsErrorNote": "The App ID or App Secret is incorrect. Check the configuration.","idleNote": "Bot credentials are saved, but the bot is not connected. Select reconnect to try again."},"appIdLabel": "App ID",@@ -5756,6 +5766,10 @@"agentUnsupportedOnChannelModeHint": "After switching Agent, send /new; if permission issues persist, send /permission.","permissionModeUnsupportedOnChannelHint": "The current Agent cannot run on this channel in this permission mode, so messages cannot be processed. Send /permission to choose a supported mode.","modelLabel": "Model Configuration",+ "automatic": "Automatic · Uses an available recommended model",+ "fixed": "Model pinned",+ "useAutomatic": "Use automatic selection",+ "automaticUnavailable": "No model is available. Connect or enable a model in model settings.","loading": "Loading new conversation configuration…","loadFailed": "Failed to load new conversation configuration","saveFailed": "Failed to save new conversation configuration",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex e064bcd314..2ae0dbc3f7 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1451,6 +1451,11 @@}},"settings": {+ "imConnection": {+ "reconnect": "再接続",+ "savedNote": "連携情報は保存されています。そのまま再接続できます。",+ "failed": "ボットに接続できませんでした"+ },"title": "設定","search": {"ariaLabel": "設定を検索",@@ -4070,7 +4075,12 @@"connectingNote": "ボットの認証情報は保存されています。接続しています。","reconnectingNote": "ボットの認証情報は保存されています。接続を復旧しています。","conflictNote": "ボットの認証情報は保存されていますが、この App ID は別のデバイスで使用中です。",- "errorNote": "ボットの認証情報は保存されていますが、接続に失敗しました。再接続してもう一度お試しください。",+ "errorNote": "ボットの連携は保持されていますが、接続できませんでした。",+ "errorHeading": "{{service}} ボットの接続に失敗しました",+ "reconnect": "ボットを再接続",+ "networkErrorNote": "IM サービスにアクセスできません。ネットワーク接続を確認してください。",+ "timeoutErrorNote": "接続がタイムアウトしました。連携を解除せずに再接続できます。",+ "credentialsErrorNote": "App ID または App Secret が正しくありません。設定を確認してください。","idleNote": "ボットの認証情報は保存されていますが、現在接続されていません。再接続してください。"},"appIdLabel": "App ID",@@ -5725,6 +5735,10 @@"agentUnsupportedOnChannelModeHint": "Agent を切り替えたら /new を送信し、権限の問題が続く場合は /permission を送信してください。","permissionModeUnsupportedOnChannelHint": "現在の Agent はこの権限モードではこのチャンネルを利用できないため、メッセージを処理できません。/permission を送信して対応する権限モードに変更してください。","modelLabel": "モデル設定",+ "automatic": "自動選択 · 利用可能な推奨モデルを使用",+ "fixed": "モデルを固定中",+ "useAutomatic": "自動選択に戻す",+ "automaticUnavailable": "利用可能なモデルがありません。モデル設定で接続または有効にしてください。","loading": "新規会話設定を読み込み中…","loadFailed": "新規会話設定を読み込めませんでした","saveFailed": "新規会話設定を保存できませんでした",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex d742704578..0754b8ef23 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1451,6 +1451,11 @@}},"settings": {+ "imConnection": {+ "reconnect": "다시 연결",+ "savedNote": "연결 정보가 저장되어 있습니다. 바로 다시 연결할 수 있습니다.",+ "failed": "봇 연결 실패"+ },"title": "설정","search": {"ariaLabel": "설정 검색",@@ -4070,7 +4075,12 @@"connectingNote": "봇 자격 증명이 저장되어 있습니다. 연결하는 중입니다.","reconnectingNote": "봇 자격 증명이 저장되어 있습니다. 연결을 복구하는 중입니다.","conflictNote": "봇 자격 증명이 저장되어 있지만 이 App ID는 다른 기기에서 사용 중입니다.",- "errorNote": "봇 자격 증명이 저장되어 있지만 연결에 실패했습니다. 다시 연결해 보세요.",+ "errorNote": "봇 연동은 유지되지만 연결하지 못했습니다.",+ "errorHeading": "{{service}} 봇 연결 실패",+ "reconnect": "봇 다시 연결",+ "networkErrorNote": "IM 서비스에 접근할 수 없습니다. 네트워크 연결을 확인하세요.",+ "timeoutErrorNote": "연결 시간이 초과되었습니다. 봇 연동을 해제하지 않고 다시 연결할 수 있습니다.",+ "credentialsErrorNote": "App ID 또는 App Secret이 올바르지 않습니다. 설정을 확인하세요.","idleNote": "봇 자격 증명이 저장되어 있지만 현재 연결되지 않았습니다. 다시 연결해 보세요."},"appIdLabel": "App ID",@@ -5725,6 +5735,10 @@"agentUnsupportedOnChannelModeHint": "Agent 전환 후 /new를 보내세요. 권한 문제가 계속되면 /permission을 보내세요.","permissionModeUnsupportedOnChannelHint": "현재 Agent는 이 권한 모드로 이 채널에서 실행할 수 없어 메시지를 처리할 수 없습니다. /permission을 보내 지원되는 권한 모드로 변경하세요.","modelLabel": "모델 설정",+ "automatic": "자동 선택 · 사용 가능한 추천 모델 사용",+ "fixed": "모델 고정됨",+ "useAutomatic": "자동 선택으로 복원",+ "automaticUnavailable": "사용 가능한 모델이 없습니다. 모델 설정에서 연결하거나 활성화하세요.","loading": "새 대화 설정을 불러오는 중…","loadFailed": "새 대화 설정을 불러오지 못했습니다","saveFailed": "새 대화 설정 저장에 실패했습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex e594f1fffe..622a67eaee 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1451,6 +1451,11 @@}},"settings": {+ "imConnection": {+ "reconnect": "重新连接",+ "savedNote": "绑定信息已保留,可直接重试连接。",+ "failed": "机器人连接失败"+ },"title": "设置","search": {"ariaLabel": "搜索设置",@@ -4070,7 +4075,12 @@"connectingNote": "已保存机器人凭证,正在建立连接。","reconnectingNote": "已保存机器人凭证,正在恢复连接。","conflictNote": "已保存机器人凭证,但该 App ID 当前被其他设备占用。",- "errorNote": "已保存机器人凭证,但当前连接失败。请点击重新连接重试。",+ "errorNote": "机器人绑定已保留,当前未能连接。",+ "errorHeading": "{{service}} 机器人连接失败",+ "reconnect": "重新连接",+ "networkErrorNote": "暂时无法访问 IM 服务,请检查网络连接。",+ "timeoutErrorNote": "连接超时,可重新连接。无需解绑机器人。",+ "credentialsErrorNote": "App ID 或 App Secret 不正确,请核对配置。","idleNote": "已保存机器人凭证,当前尚未连接。请点击重新连接。"},"appIdLabel": "App ID",@@ -5725,6 +5735,10 @@"agentUnsupportedOnChannelModeHint": "切换 Agent 后发送 /new;仍有权限问题则发送 /permission","permissionModeUnsupportedOnChannelHint": "当前 Agent 不支持以此权限模式在该渠道运行,消息将无法处理。请发送 /permission 调整权限模式。","modelLabel": "模型配置",+ "automatic": "自动选择 · 使用当前可用的推荐模型",+ "fixed": "已固定模型",+ "useAutomatic": "恢复自动选择",+ "automaticUnavailable": "暂无可用模型,请先在模型设置中连接或启用模型。","loading": "正在读取新对话配置…","loadFailed": "读取新对话配置失败","saveFailed": "保存新对话配置失败",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 7d46206f6e..2dfcc7c173 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1451,6 +1451,11 @@}},"settings": {+ "imConnection": {+ "reconnect": "重新連線",+ "savedNote": "繫結資訊已保留,可直接重試連線。",+ "failed": "機器人連線失敗"+ },"title": "設定","search": {"ariaLabel": "搜尋設定",@@ -4070,7 +4075,12 @@"connectingNote": "已儲存機器人憑證,正在建立連線。","reconnectingNote": "已儲存機器人憑證,正在恢復連線。","conflictNote": "已儲存機器人憑證,但該 App ID 當前被其他裝置佔用。",- "errorNote": "已儲存機器人憑證,但當前連線失敗。請點選重新連線重試。",+ "errorNote": "已保留機器人繫結,目前無法連線。",+ "errorHeading": "{{service}} 機器人連線失敗",+ "reconnect": "重新連線",+ "networkErrorNote": "暫時無法存取 IM 服務,請檢查網路連線。",+ "timeoutErrorNote": "連線逾時,可重新連線。無須解綁機器人。",+ "credentialsErrorNote": "App ID 或 App Secret 不正確,請核對設定。","idleNote": "已儲存機器人憑證,當前尚未連線。請點選重新連線。"},"appIdLabel": "App ID",@@ -5725,6 +5735,10 @@"agentUnsupportedOnChannelModeHint": "切換 Agent 後傳送 /new;仍有權限問題則傳送 /permission","permissionModeUnsupportedOnChannelHint": "目前 Agent 不支援以此權限模式在該渠道執行,訊息將無法處理。請傳送 /permission 調整權限模式。","modelLabel": "模型配置",+ "automatic": "自動選擇 · 使用目前可用的推薦模型",+ "fixed": "已固定模型",+ "useAutomatic": "恢復自動選擇",+ "automaticUnavailable": "暫無可用模型,請先在模型設定中連接或啟用模型。","loading": "正在讀取新對話配置…","loadFailed": "讀取新對話配置失敗","saveFailed": "儲存新對話配置失敗",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 83236a3fd3..caa09ef109 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2302,6 +2302,7 @@ interface ElectronAPI {// ── Discord Bot (Settings → IM Bot tab) ──discordBot: {+ reconnect: () => Promise<{ status: DiscordBotTransportStatus; ownerUserId: string | null }>;getStatus: () => Promise<{status: DiscordBotTransportStatus;ownerUserId: string | null;diff --git a/apps/desktop/src/shared/imAutomaticModel.ts b/apps/desktop/src/shared/imAutomaticModel.tsnew file mode 100644index 0000000000..f4c6555621--- /dev/null+++ b/apps/desktop/src/shared/imAutomaticModel.ts@@ -0,0 +1,93 @@+import {+ getModel,+ clampEffortToSupported,+ defaultEffortForCapabilities,+ type ProviderView,+} from '@cindy/model-providers';+import { resolveNewMakerDefaultTuple } from './newMakerDefaultTuple.js';+import { resolveNewTaskDefaultRoute } from './draftModelCalibration.js';+import {+ isImDefaultEffort,+ type ImDefaultAgentKind,+ type ImDefaultSettings,+} from './imDefaultSettings.js';++export function usesAutomaticImModel(settings: ImDefaultSettings): boolean {+ return !settings.agents[settings.agentKind].model.trim();+}++/** Shared by personal bots, official hooks and settings. No draft/last-used preference is read. */+export function resolveAutomaticImSettings<T extends ImDefaultSettings>(+ settings: T,+ providers: readonly ProviderView[],+ options: {+ agentKind?: ImDefaultAgentKind;+ providerId?: string | null;+ allowAgent?: (agent: ImDefaultAgentKind) => boolean;+ } = {},+): T | null {+ const agents = (['claude-code', 'codex', 'pi'] as const).filter(+ (agent) =>+ (!options.agentKind || options.agentKind === agent) && (options.allowAgent?.(agent) ?? true),+ );+ const scoped = options.providerId+ ? providers.filter((p) => p.id === options.providerId)+ : providers;+ const tuple = resolveNewMakerDefaultTuple({+ providers: scoped,+ providersLoading: false,+ availableAgentsLoaded: true,+ availableAgents: new Set(agents.map((agent) => (agent === 'claude-code' ? 'cc' : agent))),+ });+ let route = tuple+ ? {+ agentKind: tuple.vendor === 'cc' ? ('claude-code' as const) : tuple.vendor,+ model: tuple.model,+ providerId: tuple.providerId,+ }+ : null;+ // Custom providers and catalogs without a factory recommendation use the same fallback as new tasks.+ if (!route) {+ for (const agentKind of agents) {+ const candidate = resolveNewTaskDefaultRoute({ providers: scoped, agent: agentKind });+ if (candidate) {+ route = { agentKind, ...candidate };+ break;+ }+ }+ }+ if (!route) return null;+ const provider = scoped.find((p) => p.id === route.providerId)!;+ const model = getModel(provider, route.model, route.agentKind);+ const effort = model?.efforts.length+ ? (clampEffortToSupported(model.defaultEffort, model.efforts) ??+ defaultEffortForCapabilities(model.efforts))+ : null;+ return {+ ...settings,+ agentKind: route.agentKind,+ agents: {+ ...settings.agents,+ [route.agentKind]: {+ model: route.model,+ providerId: route.providerId,+ effort: isImDefaultEffort(effort) ? effort : 'high',+ },+ },+ };+}++/** Automatic defaults depend on the catalog too. A raw settings fingerprint must trigger re-resolution. */+export function resolvedImDefaultFingerprint(+ rawFingerprint: string,+ resolved: ImDefaultSettings,+): string {+ const selected = resolved.agents[resolved.agentKind];+ return JSON.stringify([+ rawFingerprint,+ resolved.agentKind,+ selected.model,+ selected.providerId,+ selected.effort,+ ]);+}diff --git a/apps/desktop/src/shared/imDefaultSettings.ts b/apps/desktop/src/shared/imDefaultSettings.tsindex d09ae7bdd5..32e5b3f08c 100644--- a/apps/desktop/src/shared/imDefaultSettings.ts+++ b/apps/desktop/src/shared/imDefaultSettings.ts@@ -15,6 +15,7 @@ export interface ImDefaultAgentSettings {/** Agent 所在电脑;share:<id> 表示分享供应商,缺省为本机。 */agentDeviceId?: string | null;providerId: string | null;+ /** Empty means automatic selection from the current catalog, never a wire model ID. */model: string;effort: ImDefaultEffort;}@@ -47,6 +48,8 @@ export type ImDefaultSettingsPatch = Omit<Partial<ImDefaultSettings>, 'agents'>};export interface ImDefaultSettingsState extends ImDefaultSettings {+ /** Read-only projection flag. The model shown is resolved; persisted automatic models remain empty. */+ automaticModel?: boolean;isCustomized: boolean;customizedKeys: string[];defaults: ImDefaultSettings;@@ -59,18 +62,18 @@ export const IM_DEFAULT_SETTINGS: ImDefaultSettings = {agents: {'claude-code': {providerId: null,- model: 'claude-opus-4-8',- effort: 'xhigh',+ model: '',+ effort: 'high',},codex: {providerId: null,- model: 'codex/gpt-5.5',+ model: '',effort: 'high',},- // Pi 走网关中档模型作为 IM 新会话默认值,可在各渠道设置中覆盖。+ // Empty defaults follow the common new-task policy; explicit selections stay fixed.pi: {providerId: null,- model: 'claude-sonnet-5',+ model: '',effort: 'high',},},@@ -127,13 +130,9 @@ export const WECHAT_UNSUPPORTED_PERMISSION_MODES: readonly ImDefaultPermissionMo* (event.speaker 存在)时挂载,主人私聊不挂 → Pi 在私聊可用,设置 UI 不区分* 群聊/私聊,不能整体警告。新增渠道时先确认其 policy 挂载是否无条件。*/-export const UNCONDITIONAL_TURN_POLICY_CHANNELS: readonly ImDefaultSettingsChannel[] = [- 'wechat',-];+export const UNCONDITIONAL_TURN_POLICY_CHANNELS: readonly ImDefaultSettingsChannel[] = ['wechat'];-export function isUnconditionalTurnPolicyChannel(- channel: ImDefaultSettingsChannel,-): boolean {+export function isUnconditionalTurnPolicyChannel(channel: ImDefaultSettingsChannel): boolean {return UNCONDITIONAL_TURN_POLICY_CHANNELS.includes(channel);}diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.mdindex c237cad4fd..727b58168e 100644--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@ -38,7 +38,7 @@| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx, apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 || `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 || `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginActions, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginDevicePicker, PluginManagementLayout, PluginProjectMenu, RemotePluginConfiguration, RemotePluginPage, RemotePluginReadOnlyDetail, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 28 | 0 | 48 |-| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalAgentSection.settings-search.ts, apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 137 | 95 | 552 |+| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AddSpeechModelsDialog.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImConnectionRecovery.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalAgentSection.settings-search.ts, apps/desktop/src/renderer/components/settings/LocalAgentSection.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderAccountUsageModule.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SpeechModelChoices.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 137 | 95 | 551 || `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarTabWindowLayout.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/NewTag.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/TabDragController.tsx, apps/desktop/src/renderer/features/right-sidebar/TabGroupPanel.tsx, apps/desktop/src/renderer/features/right-sidebar/botMenuOwnerContext.ts, apps/desktop/src/renderer/features/right-sidebar/globalTabs.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.test.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mailPreview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openPluginTaskTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSideChatTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/lib/tabHosting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/useTabCreationMenu.ts, apps/desktop/src/renderer/features/right-sidebar/moveTab.ts, apps/desktop/src/renderer/features/right-sidebar/pluginPlacement.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailCardBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailConversationView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailParticipant.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/MailPreview.test.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/mail-preview/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-task/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/plugin-view/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/SideChatTabBody.test.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/SideChatTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/side-chat/state.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/terminalFont.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/useTerminalFontSettings.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/tabGroupHost.tsx, apps/desktop/src/renderer/features/right-sidebar/tabGroupPanes.ts, apps/desktop/src/renderer/features/right-sidebar/tabGroups.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 147 | 46 | 199 || `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginDevicePicker, PluginManagementLayout, RemoteSkillsPage, SkillCategoryFilterBar, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/skillhub-home.css | 39 | 0 | 45 || `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 42 | 0 | 35 |diff --git a/docs/dev-rules/im-turn-flow.md b/docs/dev-rules/im-turn-flow.mdindex c3092e4cba..7d17c1878e 100644--- a/docs/dev-rules/im-turn-flow.md+++ b/docs/dev-rules/im-turn-flow.md@@ -12,6 +12,26 @@ Telegram / Slack / X)是同一件事的两套实现:把渠道里的一条消[`../product-rules/telegram-bot-parity.md`](../product-rules/telegram-bot-parity.md);台账里标「有意不同」的项以策略参数表达,合并时不抹平。+连接恢复由渠道 transport 持有,不重放任务或发送内容。Telegram、Discord 的启动网络失败与+钉钉的连接失败使用可取消的指数退避(约 1 秒起、30 秒封顶,带抖动);Telegram 429 尊重+服务端完整等待时间。飞书保留 SDK 重连,仅在 SDK 耗尽重试或启动抛错后补重试;就绪日志须+与 SDK 真实连接状态一致。微信、企业微信保留已有重试循环。恢复成功立即更新状态,+不等待下一条消息;凭据失效保留明确错误,冲突沿用各渠道原策略。主动下线、解绑、换账号或退出+必须取消重试,旧连接结果不得复活。设置页的手动重连复用保存的凭据,不要求重新输入或解绑。++退避计算、默认间隔、抖动和可取消定时器统一放在 `@cindy/im/connection-retry`:飞书、+Telegram、Discord、钉钉和官方 hook 共用调度器,Telegram 长轮询复用同一退避策略。+官方 hook 的冲突等待间隔和抖动范围通过参数保留;鉴权、冲突及 SDK 回调仍由渠道适配层处理。+设置页共用 `ImConnectionRecovery.tsx` 的错误提示、重连按钮和已保存凭据恢复行,避免各渠道+重复维护文案、加载状态和错误详情展示。++机器人未单独选择模型时,空的模型配置表示自动选择意图。个人渠道、官方 hook 与设置页均经+`shared/imAutomaticModel.ts` 复用普通新任务的默认组合与目录回退规则,不读取输入框的最近选择。+解析结果包含来源、引擎、模型和思考强度,只用于执行和展示,不写回 override。自动模式的+跟随记录同时记下解析结果,下一条消息重新解析目录;结果未变不改任务,任务手动选择仍优先。+无可用来源时明确失败,不把空字符串或历史写死型号交给执行器。已有显式配置保留原值;恢复+自动选择只清模型路由覆盖,保留权限档。+## 1. 入口账本每一行是一轮任务的一个步骤。「现状」列写真正干活的函数;「目标」列写合并后的归属:diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex c3011dbfdd..073127ea37 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -174,6 +174,11 @@ App 完成未读与提醒统一由 `renderer/hooks/useSessionRunningStatus.ts``acquirePendingAgentSwitchForImSend` 的切换流程;官方 hook 先应用选择,再读取任务meta 和绑定观察器,发送完成即释放锁。跟随切换与手动选择共用发送锁;跟随切换保持任务的权限档与 Fast。回归见 `hook-control/__tests__/session-runner.test.ts`。桌面 IM 默认配置与目录偏好统一使用标准模型选择器,一次保存 Harness、来源、模型和思考强度;不额外展示独立 Harness 控件,不展示无法保存的 Fast。两侧的配置归属与权限规则保持各自既有契约。+2026-10-26:官方与个人机器人未单独选模时共用 `shared/imAutomaticModel.ts`,复用普通新任务+的出厂默认组合与可用目录回退,不跟随输入框的最近选择。设置页显示「自动选择」和当前解析+出的实际模型;手动固定的旧模型继续保留。目录更新后,仍跟随默认的任务在下一条消息重算,+手动改过的任务不受影响。「恢复自动选择」不重置权限。两侧独立的配置归属、目录覆盖与权限+策略保持不变;自动模式没有可用来源时明确失败,不再回落到写死的旧型号。两侧的成功提示、帮助与命令菜单都必须按这个真实结果称为「新任务」,不得沿用旧的「新对话/清掉上下文」说法。官方 bot 通过 `session-new-v1` 双向能力协商执行立即创建,滚动升级时旧 Desktop 才退回旧的diff --git a/packages/lizi-im/package.json b/packages/lizi-im/package.jsonindex 8e8a51fdc1..cb7b960e2b 100644--- a/packages/lizi-im/package.json+++ b/packages/lizi-im/package.json@@ -7,7 +7,8 @@"main": "./src/index.ts","types": "./src/index.ts","exports": {- ".": "./src/index.ts"+ ".": "./src/index.ts",+ "./connection-retry": "./src/connectionRetry.ts"},"scripts": {"build": "tsc --noEmit",diff --git a/packages/lizi-im/src/connectionRetry.ts b/packages/lizi-im/src/connectionRetry.tsnew file mode 100644index 0000000000..b55351177f--- /dev/null+++ b/packages/lizi-im/src/connectionRetry.ts@@ -0,0 +1,66 @@+export interface ConnectionBackoffOptions {+ baseMs?: number;+ maxMs?: number;+ /** Downward jitter keeps maxMs a true cap. Use 1 for deterministic polling. */+ jitterMinRatio?: number;+ random?: () => number;+}++export function connectionBackoffDelayMs(+ attempt: number,+ {+ baseMs = 1_000,+ maxMs = 30_000,+ jitterMinRatio = 0.8,+ random = Math.random,+ }: ConnectionBackoffOptions = {},+): number {+ const capped = Math.min(maxMs, baseMs * 2 ** attempt);+ return Math.round(capped * (jitterMinRatio + random() * (1 - jitterMinRatio)));+}++/** Shared delay policy for timer-driven connections and abortable poll loops. */+export class ConnectionBackoff {+ private attempt = 0;++ constructor(private readonly options: ConnectionBackoffOptions = {}) {}++ nextDelay(minimumDelayMs = 0): number {+ return Math.max(minimumDelayMs, connectionBackoffDelayMs(this.attempt++, this.options));+ }++ reset(): void {+ this.attempt = 0;+ }+}++/** One cancellable retry per connection; SDK-owned retries stay in their SDK. */+export class ConnectionRetry {+ private timer: ReturnType<typeof setTimeout> | null = null;+ private readonly backoff: ConnectionBackoff;++ constructor(options: ConnectionBackoffOptions = {}) {+ this.backoff = new ConnectionBackoff(options);+ }++ schedule(+ retry: () => void,+ options: { minimumDelayMs?: number; fixedDelayMs?: number } = {},+ ): void {+ if (this.timer) return;+ const backoffDelay = this.backoff.nextDelay(options.minimumDelayMs);+ // Conflict standby uses an exact interval, independent of jitter.+ const delay = options.fixedDelayMs ?? backoffDelay;+ this.timer = setTimeout(() => {+ this.timer = null;+ retry();+ }, delay);+ this.timer.unref?.();+ }++ reset(): void {+ if (this.timer) clearTimeout(this.timer);+ this.timer = null;+ this.backoff.reset();+ }+}diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.tsindex 085fb80862..29067741d2 100644--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts@@ -85,6 +85,103 @@ function validCredentialFetcher() {);}+describe('DingTalk connection recovery', () => {+ it('backs off repeated failures and cancels retries when credentials are cleared', async () => {+ vi.useFakeTimers();+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);+ const { host } = makeHost();+ const fetcher = vi.fn<typeof fetch>().mockRejectedValue(new Error('offline'));+ const im = new DingTalkIM(host, { fetcher });+ try {+ await im.init();+ await vi.advanceTimersByTimeAsync(800);+ expect(fetcher).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1_599);+ expect(fetcher).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1);+ expect(fetcher).toHaveBeenCalledTimes(3);+ await im.clearCredentials();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(fetcher).toHaveBeenCalledTimes(3);+ expect(im.getStatus().kind).toBe('idle');+ } finally {+ await im.dispose();+ random.mockRestore();+ vi.useRealTimers();+ }+ });++ it('recovers a dropped stream without enabling the SDK retry loop', async () => {+ vi.useFakeTimers();+ const { host } = makeHost();+ const clients: FakeClient[] = [];+ const im = new DingTalkIM(host, {+ fetcher: validCredentialFetcher(),+ clientFactory: () => { const client = new FakeClient(); clients.push(client); return client; },+ });+ const received = vi.fn();+ im.onMessage(received);+ try {+ await im.init();+ expect(clients[0].config.autoReconnect).toBe(false);+ clients[0].emit(directMessage());+ await vi.advanceTimersByTimeAsync(0);+ expect(received).toHaveBeenCalledOnce();+ clients[0].connected = false;+ await vi.advanceTimersByTimeAsync(3_000);+ expect(clients).toHaveLength(2);+ expect(im.getStatus().kind).toBe('connected');+ clients[1].emit(directMessage());+ clients[0].emit(directMessage({ msgId: 'stale-client' }));+ await vi.advanceTimersByTimeAsync(0);+ expect(received).toHaveBeenCalledOnce();+ clients[1].emit(directMessage({ msgId: 'new-message' }));+ await vi.advanceTimersByTimeAsync(0);+ expect(received).toHaveBeenCalledTimes(2);+ await im.dispose();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(clients).toHaveLength(2);+ } finally { await im.dispose(); vi.useRealTimers(); }+ });++ it('does not open a socket when disposed during credential validation', async () => {+ const { host } = makeHost();+ let resolve!: (response: Response) => void;+ const fetcher = vi.fn<typeof fetch>(() => new Promise((done) => { resolve = done; }));+ const clientFactory = vi.fn(() => new FakeClient());+ const im = new DingTalkIM(host, { fetcher, clientFactory });+ const starting = im.init();+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce());+ await im.dispose();+ resolve(new Response(JSON.stringify({ accessToken: 'token', expireIn: 7200 })));+ await starting;+ expect(clientFactory).not.toHaveBeenCalled();+ expect(im.getStatus().kind).toBe('idle');+ });++ it.each(['recover', 'dispose', 'auth'])('handles startup failure: %s', async (outcome) => {+ vi.useFakeTimers();+ const { host } = makeHost();+ const fetcher = validCredentialFetcher();+ if (outcome === 'auth') {+ fetcher.mockResolvedValueOnce(new Response('{}', { status: 401 }));+ } else {+ fetcher.mockRejectedValueOnce(new Error('network down'));+ }+ const im = new DingTalkIM(host, { fetcher, clientFactory: () => new FakeClient() });+ try {+ await im.init();+ if (outcome === 'dispose') await im.dispose();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(fetcher).toHaveBeenCalledTimes(outcome === 'recover' ? 2 : 1);+ if (outcome === 'recover') expect(im.getStatus().kind).toBe('connected');+ } finally {+ await im.dispose();+ vi.useRealTimers();+ }+ });+});+function outboundImageFetcher() {return vi.fn<typeof fetch>(async (input) => {const url = String(input);diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.tsindex ddf4aa5c46..a10412d970 100644--- a/packages/lizi-im/src/dingtalk/index.ts+++ b/packages/lizi-im/src/dingtalk/index.ts@@ -8,6 +8,7 @@ import {} from "dingtalk-stream";import { BaseIM } from "../BaseIM.js";+import { ConnectionRetry } from "../connectionRetry.js";import type { ChannelIM, ImFinalOutput } from "../channelIM.js";import type {IMCardActionEvent,@@ -114,6 +115,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {private ownerUserId = "";private connectionVersion = 0;private statusTimer: ReturnType<typeof setInterval> | null = null;+ private readonly connectionRetry = new ConnectionRetry();constructor(host: IMHost,@@ -132,15 +134,13 @@ export class DingTalkIM extends BaseIM implements ChannelIM {}try {await this.connect(credentials);- } catch (error) {- this.setStatus({- kind: "error",- reason: safeConnectionError(error),- });+ } catch {+ // connect publishes the failure and schedules recovery for saved credentials.}}async dispose(): Promise<void> {+ this.connectionRetry.reset();this.connectionVersion += 1;this.stopStatusMonitor();this.client?.disconnect();@@ -224,15 +224,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {return this.runInAccountScope(async () => {const credentials = this.readCredentials();if (!credentials) throw new Error("DINGTALK_CREDENTIALS_MISSING");- try {- await this.connect(credentials);- } catch (error) {- this.setStatus({- kind: "error",- reason: safeConnectionError(error),- });- throw error;- }+ await this.connect(credentials);return this.getPublicState();});});@@ -452,6 +444,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {const previous = this.readCredentials();const previousOwner = this.host.secrets.read(this.key(OWNER_USER_ID_SECRET));+ const version = this.connectionVersion + 1;try {await this.connect(credentials);if (!this.writeCredentials(credentials)) {@@ -463,6 +456,7 @@ export class DingTalkIM extends BaseIM implements ChannelIM {}return this.getPublicState();} catch (error) {+ if (version !== this.connectionVersion) throw error;this.restoreSecret(this.key(APP_KEY_SECRET), previous?.appKey ?? null);this.restoreSecret(this.key(APP_SECRET_SECRET), previous?.appSecret ?? null);this.restoreSecret(this.key(OWNER_USER_ID_SECRET), previousOwner);@@ -493,9 +487,35 @@ export class DingTalkIM extends BaseIM implements ChannelIM {this.setStatus({ kind: "idle" });}- private async connect(credentials: Credentials): Promise<void> {- await this.stopConnection();- const version = this.connectionVersion;+ private async connect(credentials: Credentials, retrying = false): Promise<void> {+ const version = this.connectionVersion + (retrying ? 0 : 1);+ await this.stopConnection(!retrying);+ if (version !== this.connectionVersion) throw new Error("DINGTALK_CONNECTION_REPLACED");+ try {+ await this.openConnection(credentials, version);+ if (version !== this.connectionVersion) throw new Error("DINGTALK_CONNECTION_REPLACED");+ this.connectionRetry.reset();+ } catch (error) {+ if (version !== this.connectionVersion) throw error;+ const reason = safeConnectionError(error);+ this.setStatus({ kind: "error", reason });+ const saved = this.readCredentials();+ if (reason !== "DINGTALK_AUTH_FAILED" && saved?.appKey === credentials.appKey+ && saved?.appSecret === credentials.appSecret) {+ this.scheduleReconnect(credentials, version);+ }+ throw error;+ }+ }++ private scheduleReconnect(credentials: Credentials, version: number): void {+ this.connectionRetry.schedule(() => {+ if (version !== this.connectionVersion) return;+ void this.connect(credentials, true).catch(() => undefined);+ });+ }++ private async openConnection(credentials: Credentials, version: number): Promise<void> {this.setStatus({ kind: "connecting" });const api = new DingTalkApiClient(credentials.appKey,@@ -512,13 +532,23 @@ export class DingTalkIM extends BaseIM implements ChannelIM {: "DINGTALK_NETWORK_FAILED",);}+ if (version !== this.connectionVersion) {+ api.close();+ return;+ }const client = (this.options.clientFactory ?? defaultClientFactory)(credentials,);+ this.client = client;+ const closeAttempt = () => {+ if (this.client === client) this.client = null;+ client.disconnect();+ api.close();+ };client.config.autoReconnect = false;client.registerCallbackListener(TOPIC_ROBOT, (message) => {this.ackDownstream(client, message);- if (version !== this.connectionVersion) return;+ if (version !== this.connectionVersion || this.client !== client) return;const accountToken = this.host.accountScope?.capture();if (this.host.accountScope && accountToken === null) return;void this.acceptDownstream(message, version, accountToken);@@ -526,43 +556,43 @@ export class DingTalkIM extends BaseIM implements ChannelIM {try {await client.connect();} catch {- client.disconnect();- api.close();+ closeAttempt();throw createConnectionError("DINGTALK_STREAM_CONNECTION_FAILED");}if (version !== this.connectionVersion) {- client.disconnect();- api.close();+ closeAttempt();throw new Error("DINGTALK_CONNECTION_REPLACED");}if (!client.connected) {- client.disconnect();- api.close();+ closeAttempt();throw createConnectionError("DINGTALK_STREAM_CONNECTION_FAILED");}- client.config.autoReconnect = true;+ // Own retries here: the SDK retries every second with uncancellable timers.this.client = client;this.appKey = credentials.appKey;this.api = api;this.setStatus({ kind: "connected", appId: credentials.appKey });- this.startStatusMonitor(version);+ this.startStatusMonitor(version, credentials);}- private async stopConnection(): Promise<void> {- this.connectionVersion += 1;+ private async stopConnection(resetRetry = true): Promise<void> {+ if (resetRetry) this.connectionRetry.reset();+ if (resetRetry) this.connectionVersion += 1;this.stopStatusMonitor();const client = this.client;this.client = null;this.api?.close();this.api = null;client?.disconnect();- this.targetByUserId.clear();- this.laneQueues.clear();- this.seenMessageIds.clear();- this.rejectPendingReplies("DINGTALK_CONNECTION_REPLACED");+ if (resetRetry) {+ this.targetByUserId.clear();+ this.laneQueues.clear();+ this.seenMessageIds.clear();+ this.rejectPendingReplies("DINGTALK_CONNECTION_REPLACED");+ }}- private startStatusMonitor(version: number): void {+ private startStatusMonitor(version: number, credentials: Credentials): void {this.stopStatusMonitor();this.statusTimer = setInterval(() => {if (version !== this.connectionVersion || !this.client) return;@@ -570,8 +600,9 @@ export class DingTalkIM extends BaseIM implements ChannelIM {if (this.status.kind !== "connected") {this.setStatus({ kind: "connected", appId: this.appKey });}- } else if (this.status.kind === "connected") {- this.setStatus({ kind: "connecting" });+ } else {+ if (this.status.kind === "connected") this.setStatus({ kind: "connecting" });+ this.scheduleReconnect(credentials, version);}}, STATUS_POLL_MS);}diff --git a/packages/lizi-im/src/discord/__tests__/discordIM.test.ts b/packages/lizi-im/src/discord/__tests__/discordIM.test.tsindex 3dbbd6872d..1f012b78f1 100644--- a/packages/lizi-im/src/discord/__tests__/discordIM.test.ts+++ b/packages/lizi-im/src/discord/__tests__/discordIM.test.ts@@ -61,6 +61,46 @@ function fakeGateway(): { factory: (ev: DiscordGatewayEvents) => DiscordGateway;}describe('DiscordIM teammate instance', () => {+ it('manual reconnect uses the saved token and cancels the pending automatic retry', async () => {+ vi.useFakeTimers();+ const { host, secrets, handlers } = makeHost();+ secrets.set('discord-bot-token', 'saved-token');+ const gateway = fakeGateway();+ gateway.connect.mockRejectedValueOnce(new Error('offline'));+ const im = new DiscordIM(host, { gatewayFactory: gateway.factory });+ im.registerIpc();+ try {+ await im.init();+ await handlers.get('discordBot:reconnect')!();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(gateway.connect).toHaveBeenCalledTimes(2);+ expect(gateway.connect).toHaveBeenLastCalledWith('saved-token');+ expect(secrets.get('discord-bot-token')).toBe('saved-token');+ expect(im.getStatus().kind).toBe('connected');+ } finally { await im.dispose(); vi.useRealTimers(); }+ });++ it.each(['recover', 'dispose', 'invalid-token'])('handles startup failure: %s', async (outcome) => {+ vi.useFakeTimers();+ const { host, secrets } = makeHost();+ secrets.set('discord-bot-token', 'saved-token');+ const gateway = fakeGateway();+ gateway.connect.mockRejectedValueOnce(Object.assign(new Error('network down'), {+ code: outcome === 'invalid-token' ? 'TokenInvalid' : 'ECONNRESET',+ }));+ const im = new DiscordIM(host, { gatewayFactory: gateway.factory });+ try {+ await im.init();+ if (outcome === 'dispose') await im.dispose();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(gateway.connect).toHaveBeenCalledTimes(outcome === 'recover' ? 2 : 1);+ if (outcome === 'recover') expect(im.getStatus().kind).toBe('connected');+ } finally {+ await im.dispose();+ vi.useRealTimers();+ }+ });+it('reads and writes credentials under its prefix, skips settings IPC and broadcasts', async () => {const { host, secrets, handlers, broadcasts } = makeHost();const gateway = fakeGateway();diff --git a/packages/lizi-im/src/discord/index.ts b/packages/lizi-im/src/discord/index.tsindex 34a3a501b6..bafb28a4d4 100644--- a/packages/lizi-im/src/discord/index.ts+++ b/packages/lizi-im/src/discord/index.ts@@ -2,6 +2,7 @@ import fs from 'node:fs';import path from 'node:path';import { BaseIM } from '../BaseIM.js';+import { ConnectionRetry } from '../connectionRetry.js';import { processingReaction } from '../processingReactions.js';import type { ChannelIM } from '../channelIM.js';import type {@@ -106,6 +107,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {private lifecycleAnnouncementEnabled = true;private lifecycleNoticeVersion = 0;private disposing = false;+ private readonly connectionRetry = new ConnectionRetry();constructor(host: IMHost, private readonly opts: DiscordIMOptions = {}) {super('discord', host);@@ -141,16 +143,12 @@ export class DiscordIM extends BaseIM implements ChannelIM {this.ownerUserId && this.host.secrets.read(this.key(RUNTIME_ACTIVE_SECRET_KEY)),);- try {- await this.gateway.connect(token);- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- this.log.warn(`discord gateway connect failed: ${msg}`);- }+ await this.reconnectPreviousGateway(token);}async dispose(): Promise<void> {this.disposing = true;+ this.connectionRetry.reset();const noticeDeadline = Date.now() + RUNTIME_NOTICE_SHUTDOWN_BUDGET_MS;await this.waitForRuntimeOnlineNotice(noticeDeadline);this.configVersion += 1;@@ -213,6 +211,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {const nextOwnerUserId = ownerUserId || this.ownerUserId;if (token) {+ this.connectionRetry.reset();this.configVersion += 1;const wasConnectedBeforeReconnect = this.status.kind === 'connected';await this.gateway.destroy();@@ -250,8 +249,21 @@ export class DiscordIM extends BaseIM implements ChannelIM {return configResult();}+ /** Reconnect using stored credentials without changing the binding. */+ async reconnect(): Promise<DiscordConfigState> {+ this.connectionRetry.reset();+ const version = ++this.configVersion;+ await this.gateway.destroy();+ if (this.disposing || version !== this.configVersion) return this.getConfigState();+ const token = this.host.secrets.read(this.key(TOKEN_SECRET_KEY));+ if (token) await this.reconnectPreviousGateway(token);+ else this.setStatus({ kind: 'idle' });+ return this.getConfigState();+ }+/** 通知主人、断开并清掉本实例的全部凭证。 */async disconnect(): Promise<{ status: IMStatus }> {+ this.connectionRetry.reset();this.configVersion += 1;const disconnectedNoticeConfigVersion = this.configVersion;const disconnectedOwnerUserId = this.ownerUserId;@@ -279,6 +291,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {if (this.opts.ipc === false) return;this.host.ipc.handle('discordBot:set-config', (payload) => this.setConfig(payload));+ this.host.ipc.handle('discordBot:reconnect', () => this.reconnect());// Renderer IPC can run after handler registration but before init(). Read the// persisted preference here instead of exposing the constructor default.@@ -551,12 +564,21 @@ export class DiscordIM extends BaseIM implements ChannelIM {private async reconnectPreviousGateway(previousToken: string | null): Promise<void> {const token = previousToken?.trim() ?? '';if (!token) return;-+ const version = this.configVersion;try {await this.gateway.connect(token);+ if (version === this.configVersion) this.connectionRetry.reset();} catch (err) {+ if (this.disposing || version !== this.configVersion) return;const msg = err instanceof Error ? err.message : String(err);this.log.warn(`discord gateway reconnect to previous config failed: ${msg}`);+ this.setStatus(mapDiscordLoginErrorToStatus(err));+ const code = typeof err === 'object' && err !== null && 'code' in err ? err.code : undefined;+ if (['TokenInvalid', 'DisallowedIntents', 'InvalidIntents', 4004, 4010, 4011, 4012, 4013, 4014].includes(code as string | number)) return;+ this.connectionRetry.schedule(() => {+ if (this.disposing || version !== this.configVersion) return;+ void this.reconnectPreviousGateway(token);+ });}}diff --git a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.tsindex 71171043e2..cc527f6202 100644--- a/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/ipcAccountScope.test.ts@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({getCurrentStatus: vi.fn<() => 'idle' | 'testing' | 'connected' | 'reconnecting' | 'conflict' | 'error'>(() => 'idle'),+ getCurrentError: vi.fn<() => string | undefined>(() => undefined),readCredentials: vi.fn(() =>null as {@@ -28,6 +29,7 @@ const mocks = vi.hoisted(() => ({vi.mock('../wsClient.js', () => ({QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS: 4500,getCurrentStatus: mocks.getCurrentStatus,+ getCurrentError: mocks.getCurrentError,setLifecycleAnnouncement: vi.fn(),clearOrphanRetriesForCredentialClear: vi.fn(),stop: mocks.stop,@@ -133,6 +135,7 @@ beforeEach(() => {operationGate = null;vi.clearAllMocks();mocks.getCurrentStatus.mockReturnValue('idle');+ mocks.getCurrentError.mockReturnValue(undefined);mocks.readCredentials.mockReturnValue(null);mocks.stop.mockResolvedValue(undefined);mocks.start.mockResolvedValue('connected');@@ -144,6 +147,17 @@ afterEach(() => {vi.useRealTimers();});+// Unit regression: opening settings after a failure must retain its cause.+// Existing tests cover account boundaries, not the get-state error snapshot.+it('returns the connection failure reason when settings opens after the status event', async () => {+ mocks.getCurrentStatus.mockReturnValue('error');+ mocks.getCurrentError.mockReturnValue('connect ETIMEDOUT');+ await expect(Promise.resolve(handlers.get('feishuBot:get-state')?.())).resolves.toMatchObject({+ status: 'error',+ error: 'connect ETIMEDOUT',+ });+});+describe('Feishu IPC account scope', () => {it('starts app registration with the selected verification service', async () => {mocks.requestRegistration.mockResolvedValue({diff --git a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.tsindex 3cafa5055c..67d7ad4ca9 100644--- a/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/wsClientConflict.test.ts@@ -16,6 +16,8 @@ interface MockSdkOptions {};onReady?: () => void;onError?: (error: Error) => void;+ onReconnecting?: () => void;+ onReconnected?: () => void;}type EventHandler = (data: unknown) => Promise<unknown> | unknown;@@ -24,6 +26,7 @@ const mocks = {options: [] as MockSdkOptions[],start: vi.fn(async () => undefined),close: vi.fn(),+ connectionStatus: vi.fn(() => ({ state: 'connected' })),bindClient: vi.fn(),unbindClient: vi.fn(),getBoundClient: vi.fn(() => null),@@ -48,6 +51,7 @@ vi.doMock('@larksuiteoapi/node-sdk', () => ({WSClient: class {readonly start = mocks.start;readonly close = mocks.close;+ readonly getConnectionStatus = mocks.connectionStatus;constructor(options: MockSdkOptions) {mocks.options.push(options);@@ -111,6 +115,7 @@ beforeEach(async () => {mocks.options.length = 0;mocks.eventHandlers = {};vi.clearAllMocks();+ mocks.connectionStatus.mockReturnValue({ state: 'connected' });mocks.firstAllowed.mockReturnValue(null);mocks.readOwnerOpenId.mockReturnValue(null);});@@ -132,6 +137,110 @@ afterAll(() => {});describe('Feishu WebSocket conflict handling', () => {+ it('does not treat an SDK ready log as recovery while its socket is retrying', async () => {+ vi.useFakeTimers();+ try {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ mocks.connectionStatus.mockReturnValue({ state: 'reconnecting' });+ latestClient().logger.info('[ws]', 'ws client ready');+ expect(wsClient.getCurrentStatus()).not.toBe('connected');+ await vi.advanceTimersByTimeAsync(8_000);+ await expect(connecting).resolves.toBe('error');+ } finally {+ await wsClient.stop({ announceOffline: false });+ vi.useRealTimers();+ }+ });++ it('retries a rejected SDK start without an unhandled rejection', async () => {+ vi.useFakeTimers();+ mocks.start.mockRejectedValueOnce(new Error('network down'));+ try {+ await expect(wsClient.start(credentials, { announceLifecycle: false })).resolves.toBe('error');+ await vi.advanceTimersByTimeAsync(1_000);+ expect(mocks.start).toHaveBeenCalledTimes(2);+ latestClient().options.onReady?.();+ expect(wsClient.getCurrentStatus()).toBe('connected');+ } finally {+ await wsClient.stop({ announceOffline: false });+ vi.useRealTimers();+ }+ });++ it.each(['recover', 'stop', 'auth'])('handles exhausted SDK retries: %s', async (outcome) => {+ vi.useFakeTimers();+ try {+ const connecting = wsClient.start(credentials, { announceLifecycle: false });+ const client = latestClient();+ client.options.onError?.(new Error(outcome === 'auth'+ ? 'pullConnectConfig failed: code=514, msg=invalid credentials'+ : 'WebSocket reconnect exhausted after 3 attempts'));+ await connecting;+ if (outcome === 'stop') await wsClient.stop({ announceOffline: false });+ await vi.advanceTimersByTimeAsync(2_000);+ expect(mocks.start).toHaveBeenCalledTimes(outcome === 'recover' ? 2 : 1);+ if (outcome === 'recover') {+ client.options.onReady?.();+ expect(wsClient.getCurrentStatus()).toBe('connected');+ }+ } finally {+ await wsClient.stop({ announceOffline: false });+ vi.useRealTimers();+ }+ });++ // Regression: the one-shot startup verdict used to pin the visible status to error.+ // Unit tier: drive real start() with SDK callbacks and fake time; existing cases+ // cover conflicts, but not a successful connection after the startup deadline.+ it.each(['onReady', 'onReconnected'] as const)(+ 'recovers after startup timeout via %s and ignores callbacks after stop',+ async (callback) => {+ vi.useFakeTimers();+ const onStatus = vi.fn();+ feishuEvents.on('status', onStatus);+ try {+ const connecting = wsClient.start(credentials, {+ announceLifecycle: false,+ });+ const sdkClient = latestClient();+ await vi.advanceTimersByTimeAsync(8000);+ await expect(connecting).resolves.toBe('error');+ expect(wsClient.getCurrentStatus()).toBe('error');+ expect(wsClient.getCurrentError()).toContain('Timed out');++ sdkClient.options.onReconnecting?.();+ expect(wsClient.getCurrentStatus()).toBe('reconnecting');+ sdkClient.options[callback]?.();+ expect(wsClient.getCurrentStatus()).toBe('connected');+ expect(wsClient.getCurrentError()).toBeUndefined();+ expect(onStatus).toHaveBeenLastCalledWith(+ expect.objectContaining({+ status: 'connected',+ error: undefined,+ }),+ );++ await wsClient.stop({ announceOffline: false });+ sdkClient.options[callback]?.();+ expect(wsClient.getCurrentStatus()).toBe('idle');+ } finally {+ feishuEvents.off('status', onStatus);+ vi.useRealTimers();+ }+ },+ );++ it('does not overwrite a ready callback with an earlier failed startup verdict', async () => {+ const connecting = wsClient.start(credentials, {+ announceLifecycle: false,+ });+ const sdkClient = latestClient();+ sdkClient.options.onError?.(new Error('connect ETIMEDOUT'));+ sdkClient.options.onReady?.();+ await expect(connecting).resolves.toBe('connected');+ expect(wsClient.getCurrentStatus()).toBe('connected');+ });+it('maps exceed_conn_limit during initial connection to conflict and closes the socket', async () => {const onConflict = vi.fn();feishuEvents.on('conflict', onConflict);diff --git a/packages/lizi-im/src/feishu/ipc.ts b/packages/lizi-im/src/feishu/ipc.tsindex 1ab493ccab..2b563ea0b0 100644--- a/packages/lizi-im/src/feishu/ipc.ts+++ b/packages/lizi-im/src/feishu/ipc.ts@@ -188,6 +188,7 @@ export function getPublicState(): FeishuPublicState {// across get-state ↔ init). storage.readOwnerOpenId is the source of truth.return {status: wsClient.getCurrentStatus(),+ error: wsClient.getCurrentError(),appId: creds?.appId ?? null,appSecret: creds?.appSecret ?? null,hasSecret: creds != null,diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.tsindex 79dfa22f1d..06d75dbe56 100644--- a/packages/lizi-im/src/feishu/wsClient.ts+++ b/packages/lizi-im/src/feishu/wsClient.ts@@ -44,6 +44,7 @@*/import * as Lark from '@larksuiteoapi/node-sdk';+import { ConnectionRetry } from '../connectionRetry.js';import { ConflictDetector } from './conflictDetector.js';import { feishuEvents } from './events.js';@@ -74,6 +75,9 @@ function createWsState() {pendingStartAccount: null as Pick<BotCredentials, 'appId' | 'service'> | null,topicLeaseDiscardThroughGeneration: 0,currentStatus: 'idle' as FeishuConnectionStatus,+ currentError: undefined as string | undefined,+ connectionRetry: new ConnectionRetry(),+ retryStart: null as (() => void) | null,acceptingInbound: false,lifecycleGeneration: 0,conflictTransitionGeneration: null as number | null,@@ -107,7 +111,6 @@ function shouldAbandonTopicLease();}-/*** 入站消息去重 —— 飞书事件是「至少送达一次」: 服务端等不到我们的 ACK 就会把* 同一条消息**原样再推一遍**(同一个 message_id)。没有这道闸, 重推会被当成一条@@ -176,10 +179,10 @@ export const QUIT_OFFLINE_ANNOUNCE_TIMEOUT_MS = 4500;// existing reconnect flow instead of dropping inbound messages indefinitely.const FEISHU_WS_PING_TIMEOUT_SECONDS = 30;-function emitRendererStatus(error?: string): void {+function emitRendererStatus(): void {feishuEvents.emit('status', {status: S().currentStatus,- error,+ error: S().currentError,botAppId: S().currentBotAppId,ownerOpenId: ownerGuard.firstAllowed() ?? storage.readOwnerOpenId(),});@@ -187,7 +190,8 @@ function emitRendererStatus(error?: string): void {function setStatus(status: FeishuConnectionStatus, error?: string): void {S().currentStatus = status;- emitRendererStatus(error);+ S().currentError = error;+ emitRendererStatus();// Also broadcast public IMStatus to host orchestrator subscribersfeishuEvents.emit('imStatus', toImStatus(status, error));}@@ -204,6 +208,10 @@ export function getCurrentStatus(): FeishuConnectionStatus {return S().currentStatus;}+export function getCurrentError(): string | undefined {+ return S().currentError;+}+export function getCurrentBotAppId(): string | null {return S().currentBotAppId;}@@ -252,7 +260,9 @@ function isConflictSignal(message: string): boolean {}function isActiveConnection(generation: number, appId: string): boolean {- return S().acceptingInbound && S().lifecycleGeneration === generation && S().currentBotAppId === appId;+ return (+ S().acceptingInbound && S().lifecycleGeneration === generation && S().currentBotAppId === appId+ );}async function transitionToConflict(generation: number, appId: string): Promise<void> {@@ -277,8 +287,12 @@ function handleReadySignal(): void {if (!isActiveConnection(generation, appId)) return;activeDetector.markReady();- if (activeDetector.getVerdict()?.kind === 'connected' && S().currentStatus !== 'connected') {+ // The startup verdict is final, but the SDK can recover after its deadline.+ // Only a connection conflict (or the generation guard above) forbids recovery.+ if (activeDetector.getVerdict()?.kind !== 'conflict' && S().currentStatus !== 'connected') {+ S().connectionRetry.reset();setStatus('connected');+ void fetchBotOpenId();}}@@ -289,7 +303,10 @@ function handleReconnectingSignal(): void {if (!isActiveConnection(generation, appId)) return;activeDetector.markReconnecting();- if (activeDetector.getVerdict()?.kind !== 'conflict' && S().currentStatus === 'connected') {+ if (+ activeDetector.getVerdict()?.kind !== 'conflict' &&+ (S().currentStatus === 'connected' || S().currentStatus === 'error')+ ) {setStatus('reconnecting');}}@@ -299,11 +316,7 @@ function handleReconnectedSignal(generation: number,appId: string,): void {- if (!isActiveConnection(generation, appId)) return;- activeDetector.markReconnected();- if (activeDetector.getVerdict()?.kind === 'connected' && S().currentStatus !== 'connected') {- setStatus('connected');- }+ handleReadySignal(activeDetector, generation, appId);}function handleErrorSignal(@@ -320,6 +333,13 @@ function handleErrorSignal(return;}activeDetector.markError(error);+ setStatus('error', error.message);+ // The SDK owns ordinary reconnects. Only restart when that loop has stopped.+ if (/WebSocket reconnect exhausted/i.test(error.message) && S().retryStart) {+ S().connectionRetry.schedule(S().retryStart!);+ } else {+ S().connectionRetry.reset();+ }}// ── SDK logger interceptor ────────────────────────────────────────────────────@@ -346,6 +366,9 @@ function makeCapturingLogger(log.debug('[feishu/sdk-info]', msg);if (!isActiveConnection(generation, appId)) return;if (msg.includes('ws client ready')) {+ // Some SDK versions log "ready" after merely scheduling their retry loop.+ const state = S().client?.getConnectionStatus?.().state;+ if (state && state !== 'connected') return;handleReadySignal(activeDetector, generation, appId);} else if (msg.includes('reconnect success')) {handleReconnectedSignal(activeDetector, generation, appId);@@ -474,14 +497,28 @@ export async function start('card.action.trigger_v1': (data: unknown) => runInScope(scope, () => handleCardAction(data)),});- try {- void client.start({ eventDispatcher });- } catch (err) {+ const onStartFailure = bound((err: unknown) => {+ if (!isActiveConnection(startedGeneration, creds.appId)) return;const msg = err instanceof Error ? err.message : String(err);log.error(`[feishu/wsClient] start threw: ${msg}`);setStatus('error', msg);startDetector.markError(err instanceof Error ? err : new Error(msg));- }+ if (S().retryStart) S().connectionRetry.schedule(S().retryStart!);+ });+ const startSdk = bound(() => {+ if (!isActiveConnection(startedGeneration, creds.appId)) return;+ try {+ void Promise.resolve(client.start({ eventDispatcher })).catch(onStartFailure);+ } catch (err) {+ onStartFailure(err);+ }+ });+ S().retryStart = bound(() => {+ if (!isActiveConnection(startedGeneration, creds.appId)) return;+ setStatus('reconnecting');+ startSdk();+ });+ startSdk();const verdict = await startDetector.waitForVerdict();if (S().detector === startDetector) S().detector = null;@@ -494,10 +531,13 @@ export async function start(return 'error';}- switch (verdict.kind) {+ // A ready callback may have arrived after the initial error settled but before+ // this continuation ran. Do not repaint that recovered connection as failed.+ const currentVerdict =+ S().currentStatus === 'connected' ? { kind: 'connected' as const } : verdict;+ switch (currentVerdict.kind) {case 'connected':if (S().currentStatus !== 'connected') setStatus('connected');- void fetchBotOpenId();// 恢复本 bot 在 stop() 时被挂起的排队重试(同账号重连) — 事件已被// ACK, 不恢复的话孤儿提示/撤回链随断连永久消失。if (opts.announceLifecycle !== false) {@@ -510,7 +550,7 @@ export async function start(await transitionToConflict(startedGeneration, creds.appId);return 'conflict';case 'error':- setStatus('error', verdict.message);+ setStatus('error', currentVerdict.message);return 'error';}}@@ -554,6 +594,8 @@ export async function stop(opts: StopOptions = {}): Promise<void> {}async function stopCurrentClient(opts: StopOptions): Promise<void> {+ S().connectionRetry.reset();+ S().retryStart = null;const log = getLog();const stoppedGeneration = S().lifecycleGeneration;if (opts.discardPendingTopicLeases) {diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.tsindex ae4488cb1f..68c0926b91 100644--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts@@ -235,6 +235,44 @@ async function connect(): Promise<void> {}describe('TelegramIM', () => {+ it.each(['startup', 'poll'])('honors the full rate-limit wait during %s', async (phase) => {+ vi.useFakeTimers();+ ctx.host.secrets.write('telegram-bot-token', '999:saved-token');+ const method = phase === 'startup' ? 'getMe' : 'getUpdates';+ const rateLimit = new TelegramApiError(method, 429, 'Too Many Requests', 90);+ if (phase === 'startup') api.failNextCall(method, rateLimit);+ try {+ await im.init();+ if (phase === 'poll') api.failNextGetUpdates(rateLimit);+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(89_999);+ expect(api.calls.filter((call) => call.method === method)).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(api.calls.filter((call) => call.method === method)).toHaveLength(2);+ } finally {+ await im.dispose();+ vi.useRealTimers();+ }+ });++ it.each(['recover', 'offline', 'dispose', 'invalid-token'])('handles startup failure: %s', async (outcome) => {+ vi.useFakeTimers();+ ctx.host.secrets.write('telegram-bot-token', '999:saved-token');+ api.failNextCall('getMe', outcome === 'invalid-token'+ ? new TelegramApiError('getMe', 401, 'invalid token') : new Error('network down'));+ try {+ await im.init();+ if (outcome === 'offline') await im.goOffline();+ if (outcome === 'dispose') await im.dispose();+ await vi.advanceTimersByTimeAsync(2_000);+ expect(api.calls.filter((call) => call.method === 'getMe')).toHaveLength(outcome === 'recover' ? 2 : 1);+ if (outcome === 'recover') expect(im.getStatus().kind).toBe('connected');+ } finally {+ await im.dispose();+ vi.useRealTimers();+ }+ });+it('无 token 时 init 保持 idle, 不发任何请求', async () => {await im.init();expect(im.getStatus()).toEqual({ kind: 'idle' });diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.tsindex 2d191586b9..1953fa7310 100644--- a/packages/lizi-im/src/telegram/index.ts+++ b/packages/lizi-im/src/telegram/index.ts@@ -23,6 +23,7 @@ import fs from 'node:fs';import path from 'node:path';import { BaseIM } from '../BaseIM.js';+import { ConnectionBackoff, ConnectionRetry } from '../connectionRetry.js';import type { ChannelIM } from '../channelIM.js';import type {IMAttachment,@@ -116,8 +117,6 @@ const GROUP_MEDIA_POOL_TTL_MS = 24 * 60 * 60 * 1_000;* 用户早已不在等, 逐条回答只会刷屏并派出过期任务。*/const STALE_MESSAGE_MS = 60 * 60 * 1_000;-const POLL_RETRY_BASE_MS = 1_000;-const POLL_RETRY_MAX_MS = 30_000;/** 409 = 另一个进程在对同一 token 轮询 — 低频探测等它退出。 */const POLL_CONFLICT_RETRY_MS = 30_000;const MAX_OUTBOUND_FILE_BYTES = 50 * 1024 * 1024;@@ -395,6 +394,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {*/private lifetimeAbort = new AbortController();private pollLoop: Promise<void> | null = null;+ private readonly connectionRetry = new ConnectionRetry();private disposing = false;/** sendRichMessage 方法不可用(404)后的永久 latch(本实例生命周期内)。 */private richSendDisabled = false;@@ -684,7 +684,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });return configResult();}- const connected = await this.connect(token);+ const connected = await this.connect(token, false);if (!connected) {const failedStatus = this.status;const restored = await this.rollbackConfigOrFailClosed(@@ -1295,7 +1295,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {// ── connect / polling ──────────────────────────────────────────────────────- private async connect(token: string): Promise<boolean> {+ private async connect(token: string, autoRetry = true): Promise<boolean> {const api = (this.opts.apiFactory ?? createTelegramApiClient)(token);// getMe 是网络请求, 这段窗口里另一台设备可能远程下线、用户可能本地下线或// 登出。这些路径都只递增 configVersion + 停当前 poll —— 尚未创建 poll 的@@ -1310,6 +1310,15 @@ export class TelegramIM extends BaseIM implements ChannelIM {} catch (err) {if (this.configVersion !== generation || this.disposing) return false;this.setStatus(mapConnectErrorToStatus(err));+ const retryable = !(err instanceof TelegramApiError)+ || err.errorCode === 429 || err.errorCode >= 500;+ if (autoRetry && retryable) {+ this.connectionRetry.schedule(() => {+ if (this.configVersion !== generation || this.disposing) return;+ if (this.offlineFlagState() !== 'absent') return;+ void this.connect(token);+ }, { minimumDelayMs: err instanceof TelegramApiError ? (err.retryAfterSec ?? 0) * 1_000 : 0 });+ }return false;}// 世代变了(被下线/登出/换 token)或已 dispose → 本次连接结果作废。offline@@ -1329,6 +1338,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {this.log.info('connect result discarded: offline flag is set or unreadable after getMe');return false;}+ this.connectionRetry.reset();this.api = api;this.botId = me.id;this.botUsername = me.username ?? '';@@ -1395,7 +1405,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {): Promise<void> {let offset = this.readPersistedOffset();this.lastSeenOffset = offset;- let retryDelay = POLL_RETRY_BASE_MS;+ const backoff = new ConnectionBackoff({ jitterMinRatio: 1 });while (!abort.signal.aborted && this.configVersion === generation) {try {const updates = await api.call<TgUpdate[]>(@@ -1407,7 +1417,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {},abort.signal,);- retryDelay = POLL_RETRY_BASE_MS;+ backoff.reset();if (this.status.kind !== 'connected') {this.setStatus({ kind: 'connected', appId: String(this.botId) });}@@ -1436,13 +1446,14 @@ export class TelegramIM extends BaseIM implements ChannelIM {}// 网络抖动/超时: connecting + 指数退避重试。if (this.status.kind === 'connected') this.setStatus({ kind: 'connecting' });- await sleep(retryDelay, abort.signal);- retryDelay = Math.min(retryDelay * 2, POLL_RETRY_MAX_MS);+ await sleep(backoff.nextDelay(err instanceof TelegramApiError+ ? (err.retryAfterSec ?? 0) * 1_000 : 0), abort.signal);}}}private async stopPolling(): Promise<void> {+ this.connectionRetry.reset();this.clearPendingAlbums();this.pollAbort?.abort();this.pollAbort = null;diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.tsindex 9bdb58f61b..5a241a11f1 100644--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts@@ -619,6 +619,18 @@ describe("WecomIM routing and ownership", () => {expect(im.getStatus()).toEqual({ kind: "connecting" });});+ it("clears an old authentication failure after recovery", async () => {+ const { host } = createHost();+ const client = new FakeClient();+ const im = new WecomIM(host, { clientFactory: () => client as never });+ await im.init();+ client.emit("error", new Error("Authentication failed: old failure"));+ client.emit("authenticated");+ client.emit("error", new Error("network unavailable"));+ expect(im.getStatus()).toEqual({ kind: "error", reason: "network unavailable" });+ await im.dispose();+ });+it.each([{channel: "wecomBot:set-config",diff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.tsindex 04631b2c71..de5ad038c2 100644--- a/packages/lizi-im/src/wecom/index.ts+++ b/packages/lizi-im/src/wecom/index.ts@@ -524,6 +524,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {client.on("authenticated", () => {if (!this.isCurrent(client, generation)) return;serverConflict = false;+ this.lastAuthFailureReason = "";this.setStatus({ kind: "connected", appId: botId });});client.on("reconnecting", () => {diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex 681b50f3d4..1cb40e013d 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -894,9 +894,6 @@"apps/desktop/src/renderer/hooks/__tests__/useDingTalkBot.test.ts": {"resetModules": 1},- "apps/desktop/src/renderer/hooks/__tests__/useFeishuBot.test.ts": {- "resetModules": 1- },"apps/desktop/src/renderer/hooks/__tests__/useModelPricing.test.ts": {"resetModules": 1},