fix: harden host language switching

This commit is contained in:
xmanrui 2026-08-24 03:55:55 +08:00
parent 3741dd8fd9
commit d4b8666495
23 changed files with 189 additions and 90 deletions

View file

@ -1,10 +1,9 @@
import { TextHarnessBridge, createTextBridgeStatus } from '../shared/text-harness-bridge.mjs';
import { t } from '../shared/i18n.mjs';
export const DISCORD_DESCRIPTOR = Object.freeze({
key: 'discord',
label: 'Discord',
connectionLabel: t(' Gateway 长连接'),
connectionLabel: ' Gateway 长连接',
});
export class DiscordHarnessBridge extends TextHarnessBridge {

View file

@ -50,4 +50,3 @@ export default {
'钉钉 Stream 消息连接运行正常': 'The DingTalk Stream message connection is running normally',
'钉钉消息连接当前离线': 'The DingTalk message connection is currently offline',
};

View file

@ -6,4 +6,3 @@ export default {
'Discord机器人': 'Discord Bot',
' Gateway 长连接': ' Gateway long-lived connection',
};

View file

@ -21,4 +21,3 @@ export default {
'Harness Session 已创建。': 'Harness Session created.',
'正在使用 {tool}…': 'Using {tool}…',
};

View file

@ -9,12 +9,6 @@ export default {
结果文件: 'Result file',
'结果文件「{name}」已生成,但 QQ 今日文件上传额度已用完,请稍后重试。':
'The result file "{name}" was generated, but QQ\'s daily file upload quota is used up. Please try again later.',
@ -58,4 +52,3 @@ export default {
'QQ 已授权,但无法安全保存接入配置。':
'QQ authorization succeeded, but the connection configuration could not be saved safely.',
};

View file

@ -64,6 +64,20 @@ export default {
'/help 显示本帮助': '/help Show this help',
'{label}机器人与 DeepSeek Harness 连接正常。':
'The {label} bot is connected to DeepSeek Harness and working normally.',
'{label}机器人凭据缺失,请移除后重新接入。':
'{label} bot credentials are missing. Remove the bot and connect it again.',
'{label}连接未就绪,插件会自动重试。':
'The {label} connection is not ready yet. The plugin will retry automatically.',
'{label}机器人已接入,消息连接暂未就绪。':
'The {label} bot is connected, but its message connection is not ready yet.',
'{label}连接仍未就绪,请稍后重试。':
'The {label} connection is still not ready. Please try again later.',
'{label}机器人尚未连接': 'The {label} bot is not connected yet',
'{name}({id})': '{name} ({id})',
'{label}{connectionLabel}运行正常': 'The {label}{connectionLabel} is running normally',
'{label}连接未就绪,插件会自动重试':
'The {label} connection is not ready. The plugin will retry automatically',
'{label}连接当前离线': 'The {label} connection is currently offline',
'已开启新会话。请发送你的问题。': 'A new session has started. Please send your question.',
'正在使用{name}…': 'Using {name}…',
'已停止。': 'Stopped.',
@ -75,4 +89,3 @@ export default {
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。':
'A pending question left over in this Session was detected. It has been safely cancelled, and your latest message is being processed.',
};

View file

@ -213,4 +213,3 @@ export default {
'已提交补充指令,Agent 会在下一步读取。':
'Additional instruction submitted; the Agent will read it at the next step.',
};

View file

@ -97,4 +97,3 @@ export default {
// agent-preset.mjs
'Agent Preset 无效。': 'Invalid Agent Preset.',
};

View file

@ -25,4 +25,3 @@ export default {
'Slack App Token 无法创建 Socket Mode 连接,请确认已启用 Socket Mode 和 connections:write。':
'The Slack App Token could not create a Socket Mode connection. Make sure Socket Mode and connections:write are enabled.',
};

View file

@ -19,4 +19,3 @@ export default {
'Telegram机器人': 'Telegram Bot',
' Bot API 长轮询': ' Bot API long polling',
};

View file

@ -36,4 +36,3 @@ export default {
'企业微信连接未就绪,插件会自动重试': 'The Enterprise WeChat connection is not ready. The plugin will retry automatically',
'企业微信连接当前离线': 'The Enterprise WeChat connection is currently offline',
};

View file

@ -78,4 +78,3 @@ export default {
'微信服务拒绝了文件消息。': 'The WeChat service rejected the file message.',
'微信账号连接启动失败。': 'Failed to start the WeChat account connection.',
};

View file

@ -15,4 +15,3 @@ export default {
'WhatsApp账号': 'WhatsApp account',
' Web 关联设备': ' Web linked device',
};

View file

@ -14,7 +14,7 @@ let language = 'zh';
// (including undefined and unrecognized values) selects Chinese.
export function setImHostLanguage(lang) {
const normalized = typeof lang === 'string' ? lang.trim().toLowerCase() : '';
language = normalized === 'english' || normalized.startsWith('en') ? 'en' : 'zh';
language = normalized === 'english' || /^en(?:[-_].*)?$/u.test(normalized) ? 'en' : 'zh';
}
export function getImHostLanguage() {

View file

@ -1,4 +1,5 @@
import { connectionTestMessage } from './connection-test.mjs';
import { t } from './i18n.mjs';
function cleanString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
@ -70,7 +71,9 @@ export class TokenBotController {
if (!token) {
this.#errors.set(config.botId, safeError(
'missing-token',
`${this.#descriptor.label}机器人凭据缺失,请移除后重新接入。`,
t('{label}机器人凭据缺失,请移除后重新接入。', {
label: this.#descriptor.label,
}),
));
return;
}
@ -80,7 +83,9 @@ export class TokenBotController {
} catch (error) {
this.#errors.set(config.botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接未就绪,插件会自动重试。`,
t('{label}连接未就绪,插件会自动重试。', {
label: this.#descriptor.label,
}),
));
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${config.botId} failed to initialize:`,
@ -129,7 +134,9 @@ export class TokenBotController {
} catch (error) {
this.#errors.set(identity.botId, safeError(
'connection-failed',
`${this.#descriptor.label}机器人已接入,消息连接暂未就绪。`,
t('{label}机器人已接入,消息连接暂未就绪。', {
label: this.#descriptor.label,
}),
));
this.#logger.warn?.(
`[dsh-im:${this.#descriptor.key}] bot ${identity.botId} credential connection failed:`,
@ -153,7 +160,9 @@ export class TokenBotController {
} catch (error) {
this.#errors.set(botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接仍未就绪,请稍后重试。`,
t('{label}连接仍未就绪,请稍后重试。', {
label: this.#descriptor.label,
}),
));
throw error;
} finally {
@ -181,7 +190,9 @@ export class TokenBotController {
} catch (error) {
this.#errors.set(botId, safeError(
'connection-failed',
`${this.#descriptor.label}连接仍未就绪,请稍后重试。`,
t('{label}连接仍未就绪,请稍后重试。', {
label: this.#descriptor.label,
}),
));
throw error;
} finally {
@ -197,14 +208,19 @@ export class TokenBotController {
return this.#withBotTransition(botId, async () => {
const runtime = this.#runtimes.get(botId);
if (!runtime?.status?.ready || typeof runtime.sendConnectionTest !== 'function') {
const error = new Error(`${this.#descriptor.label}机器人尚未连接`);
const error = new Error(t('{label}机器人尚未连接', {
label: this.#descriptor.label,
}));
error.code = 'test-target-unavailable';
throw error;
}
const cardLabel = `${config.name}(${this.#maskPlatformId(config.platformId)})`;
const cardLabel = t('{name}({id})', {
name: config.name,
id: this.#maskPlatformId(config.platformId),
});
await runtime.sendConnectionTest(connectionTestMessage(
cardLabel,
`${this.#descriptor.label}机器人`,
t('{label}机器人', { label: this.#descriptor.label }),
));
return { sent: true };
});
@ -260,9 +276,14 @@ export class TokenBotController {
},
health: {
status: connected ? 'healthy' : state === 'error' ? 'error' : 'offline',
summary: connected ? `${this.#descriptor.label}${this.#descriptor.connectionLabel}运行正常`
: state === 'error' ? `${this.#descriptor.label}连接未就绪,插件会自动重试`
: `${this.#descriptor.label}连接当前离线`,
summary: connected ? t('{label}{connectionLabel}运行正常', {
label: this.#descriptor.label,
connectionLabel: t(this.#descriptor.connectionLabel),
})
: state === 'error' ? t('{label}连接未就绪,插件会自动重试', {
label: this.#descriptor.label,
})
: t('{label}连接当前离线', { label: this.#descriptor.label }),
lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
lastConnectedAt: runtimeStatus?.lastConnectedAt ?? null,
},

View file

@ -136,8 +136,18 @@ export function normalizeSlackEvent(payload, botUserId, {
};
}
function isToolProgress(text) {
return typeof text === 'string' && /^正在使用.+…$/.test(text.trim());
export function isSlackToolProgress(text) {
if (typeof text !== 'string') return false;
const marker = '__DSH_IM_TOOL_NAME__';
const template = t('正在使用{name}…', { name: marker });
const markerIndex = template.indexOf(marker);
if (markerIndex < 0) return false;
const prefix = template.slice(0, markerIndex);
const suffix = template.slice(markerIndex + marker.length);
const source = text.trim();
return source.startsWith(prefix)
&& source.endsWith(suffix)
&& source.length > prefix.length + suffix.length;
}
async function appendInChunks(api, target, ts, text, signal) {
@ -205,7 +215,8 @@ async function createSlackMessageStream({ api, target, signal, logger }) {
return [...providerMessageIds];
},
update(text) {
if (closed || broken || typeof text !== 'string' || !text.trim() || isToolProgress(text)) return;
if (closed || broken || typeof text !== 'string' || !text.trim()
|| isSlackToolProgress(text)) return;
pending = text;
schedule();
},

View file

@ -16,22 +16,29 @@ import {
} from './config-store.mjs';
export const TELEGRAM_COMMAND_MENU = Object.freeze([
{ command: 'new', description: t('开启一个全新会话') },
{ command: 'compact', description: t('压缩当前会话的较早上下文') },
{ command: 'workspace', description: t('切换工作区') },
{ command: 'workspacelist', description: t('列出工作区绝对路径') },
{ command: 'sessionlist', description: t('列出会话 ID 和标题') },
{ command: 'session', description: t('将当前聊天绑定到指定会话') },
{ command: 'models', description: t('按序号列出所有可用模型') },
{ command: 'model', description: t('查看或切换当前会话模型') },
{ command: 'presetlist', description: t('列出可用 Agent Preset') },
{ command: 'preset', description: t('查看或设置新会话 Agent Preset') },
{ command: 'stop', description: t('停止当前任务') },
{ command: 'steer', description: t('纠偏当前任务') },
{ command: 'status', description: t('检查连接状态') },
{ command: 'help', description: t('显示帮助') },
{ command: 'new', description: '开启一个全新会话' },
{ command: 'compact', description: '压缩当前会话的较早上下文' },
{ command: 'workspace', description: '切换工作区' },
{ command: 'workspacelist', description: '列出工作区绝对路径' },
{ command: 'sessionlist', description: '列出会话 ID 和标题' },
{ command: 'session', description: '将当前聊天绑定到指定会话' },
{ command: 'models', description: '按序号列出所有可用模型' },
{ command: 'model', description: '查看或切换当前会话模型' },
{ command: 'presetlist', description: '列出可用 Agent Preset' },
{ command: 'preset', description: '查看或设置新会话 Agent Preset' },
{ command: 'stop', description: '停止当前任务' },
{ command: 'steer', description: '纠偏当前任务' },
{ command: 'status', description: '检查连接状态' },
{ command: 'help', description: '显示帮助' },
]);
export function telegramCommandMenu() {
return TELEGRAM_COMMAND_MENU.map((item) => ({
...item,
description: t(item.description),
}));
}
function escaped(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
@ -709,7 +716,7 @@ export class TelegramRuntime {
throw error;
}
try {
await api.setMyCommands({ commands: TELEGRAM_COMMAND_MENU, signal: controller.signal });
await api.setMyCommands({ commands: telegramCommandMenu(), signal: controller.signal });
await api.setChatMenuButton({ menuButton: COMMANDS_MENU_BUTTON, signal: controller.signal });
} catch (error) {
this.#logger.warn?.(

View file

@ -280,7 +280,8 @@ function progressText(update) {
}
function artifactFailureText(fileName, error) {
const name = String(fileName ?? '结果文件').replace(/[\r\n]+/g, ' ').trim() || '结果文件';
const name = String(fileName ?? t('结果文件')).replace(/[\r\n]+/g, ' ').trim()
|| t('结果文件');
switch (error?.code) {
case 'artifact-delivery-uncertain':
return t('结果文件「{name}」的发送结果未能确认,请先检查聊天内是否已收到,不要立即重试。', { name });