@deepseek-ai/dsh-experimental-client-ui-cot-translation 0.2.2-alpha.3 → 0.2.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/lib/client.js +1 -1272
  2. package/lib/client.js.map +1 -0
  3. package/lib/typert.remote-client.d.ts.map +1 -0
  4. package/lib/types/client/TranslationBody.d.ts.map +1 -0
  5. package/lib/types/client/TranslationBody.js.map +1 -0
  6. package/lib/types/client/TranslationSettings.d.ts.map +1 -0
  7. package/lib/types/client/TranslationSettings.js.map +1 -0
  8. package/lib/types/client/index.d.ts.map +1 -0
  9. package/lib/types/client/index.js.map +1 -0
  10. package/lib/types/client/locales.d.ts.map +1 -0
  11. package/lib/types/client/locales.js.map +1 -0
  12. package/lib/types/client/mount.d.ts.map +1 -0
  13. package/lib/types/client/mount.js.map +1 -0
  14. package/lib/types/client/preferences-form.d.ts.map +1 -0
  15. package/lib/types/client/preferences-form.js.map +1 -0
  16. package/lib/types/client/translation.d.ts.map +1 -0
  17. package/lib/types/client/translation.js.map +1 -0
  18. package/lib/types/index.d.ts.map +1 -0
  19. package/lib/types/index.js.map +1 -0
  20. package/lib/types/preferences.d.ts.map +1 -0
  21. package/lib/types/preferences.js.map +1 -0
  22. package/lib/types/types.d.ts.map +1 -0
  23. package/lib/types/types.js.map +1 -0
  24. package/package.json +31 -27
  25. package/src/client/Translation.module.css +20 -0
  26. package/src/client/TranslationBody.tsx +61 -0
  27. package/src/client/TranslationSettings.tsx +67 -0
  28. package/src/client/index.ts +21 -0
  29. package/src/client/locales.ts +179 -0
  30. package/src/client/mount.ts +129 -0
  31. package/src/client/preferences-form.ts +48 -0
  32. package/src/client/translation.ts +114 -0
  33. package/src/css-modules.d.ts +5 -0
  34. package/src/index.ts +102 -0
  35. package/src/preferences.ts +12 -0
  36. package/src/types.ts +28 -0
@@ -0,0 +1,67 @@
1
+ /** Provider, language, and external-service disclosure on the Plugins page. */
2
+ import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
3
+ import { useEffect, useId } from 'react'
4
+ import type { TranslationProvider } from '@deepseek-ai/dsh-experimental-translator/types'
5
+ import { Button, SettingsForm, SettingsValueField, Tag } from '@deepseek-ai/dsh-client-ui-primitives'
6
+ import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
7
+ import { NS, formLabels } from './locales.ts'
8
+ import type { TranslationFormInjected } from './preferences-form.ts'
9
+ import css from './Translation.module.css'
10
+
11
+ /** Settings snapshots and explicit refresh callback supplied by the Host mirror. */
12
+ export interface TranslationSettingsInjected extends TranslationFormInjected {
13
+ hooks: TranslationFormInjected['hooks'] & { availableProviders: HostObservable<readonly TranslationProvider[]> }
14
+ /** Refresh native route eligibility without sending reasoning or starting inference. */
15
+ refreshProviders: () => void
16
+ }
17
+
18
+ export type TranslationSettingsProps = PropsRuntime<'plugins.bundle.config'> & PropsLocale<typeof NS> & InjectFace<TranslationSettingsInjected>
19
+
20
+ function providerLabel(provider: string, t: TranslationSettingsProps['t']): string {
21
+ switch (provider) {
22
+ case 'bing': return t('bing')
23
+ case 'google': return t('google')
24
+ case 'deepseek-account': return t('deepseekAccount')
25
+ case 'deepseek-official': return t('deepseekOfficial')
26
+ default: return provider
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Render staged translation preferences and name which text leaves the Host.
32
+ * @param props - current draft fields, accepted-value metadata, and save actions.
33
+ * @returns the bundle's translation preferences.
34
+ */
35
+ export function TranslationSettings(props: TranslationSettingsProps) {
36
+ const { t } = props
37
+ const providerId = useId(), languageId = useId()
38
+ const state = props.useTranslationForm(value => value)
39
+ const availableProviders = props.useAvailableProviders(value => value)
40
+ useEffect(() => { props.refreshProviders() }, [props.refreshProviders])
41
+ const missingProvider = state.provider.text !== '' && !availableProviders.some(provider => provider === state.provider.text)
42
+ const paid = state.provider.text === 'deepseek-account' || state.provider.text === 'deepseek-official'
43
+ const disabled = !state.writable || state.saving
44
+ return <SettingsForm labels={formLabels(t)} state={state} onSave={props.save} onDiscard={props.discard}>
45
+ <p className={css.notice}>{t('privacy')}</p>
46
+ <p className={css.notice}>{t(paid ? 'paidNotice' : 'anonymousNotice')}</p>
47
+ <div className={css.field}>
48
+ <div className={css.toolbar}>
49
+ <label htmlFor={providerId}>{t('provider')}</label>
50
+ {state.provider.overridden && <><Tag tone="neutral">{t('overridden')}</Tag>
51
+ <Button size="sm" disabled={disabled} onClick={() => { props.resetField('provider') }}>{t('reset')}</Button></>}
52
+ </div>
53
+ <select id={providerId} value={state.provider.text} disabled={disabled} aria-invalid={state.provider.invalid || undefined}
54
+ onChange={(event) => { props.edit('provider', event.target.value) }}>
55
+ {missingProvider && <option value={state.provider.text} disabled>{t('providerUnavailableOption', {
56
+ provider: providerLabel(state.provider.text, t),
57
+ })}</option>}
58
+ {availableProviders.map(provider => <option key={provider} value={provider}>{providerLabel(provider, t)}</option>)}
59
+ </select>
60
+ {state.provider.invalid && <p role="status">{t('invalidProvider')}</p>}
61
+ {missingProvider && !state.provider.invalid && <p role="status" className={css.notice}>{t('providerUnavailable')}</p>}
62
+ </div>
63
+ <SettingsValueField id={languageId} label={t('targetLanguage')} hint={t('targetLanguageHint')}
64
+ {...state.targetLanguage} overriddenLabel={t('overridden')} resetLabel={t('reset')} invalidLabel={t('invalidLanguage')}
65
+ disabled={disabled} onEdit={(value) => { props.edit('targetLanguage', value) }} onReset={() => { props.resetField('targetLanguage') }} />
66
+ </SettingsForm>
67
+ }
@@ -0,0 +1,21 @@
1
+ /** Browser entry for optional translation of expanded reasoning. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import remote from '@deepseek-ai/dsh-experimental-client-ui-cot-translation/remote'
4
+ import { mountTranslation } from './mount.ts'
5
+
6
+ export { inject } from './mount.ts'
7
+ export type { CotTranslationPreferences } from '../preferences.ts'
8
+ export type { CotTranslationKey } from './locales.ts'
9
+ export type { TranslationBodyInjected, TranslationBodyProps } from './TranslationBody.tsx'
10
+ export type { TranslationFormInjected, TranslationFormState } from './preferences-form.ts'
11
+
12
+ declare module '@deepseek-ai/dsh-client-ui-slots' {
13
+ interface LocaleNamespaceMap { cotTranslation: import('./locales.ts').CotTranslationKey }
14
+ }
15
+
16
+ /**
17
+ * Mount the experimental reasoning presentation and its Remote methods.
18
+ * @param ctx - browser plugin context.
19
+ * @returns disposer joining UI and Remote withdrawal.
20
+ */
21
+ export async function apply(ctx: Context): Promise<() => Promise<void>> { return await mountTranslation(ctx, remote) }
@@ -0,0 +1,179 @@
1
+ /** Locale-owned copy for reasoning translation and its preferences. */
2
+ import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives'
3
+
4
+ /** Dictionary namespace for this plugin. */
5
+ export const NS = 'cotTranslation'
6
+
7
+ /** English copy and key source. */
8
+ export const en = {
9
+ provider: 'Translation service', google: 'Google', bing: 'Bing',
10
+ deepseekAccount: 'DeepSeek Flash — account (paid)', deepseekOfficial: 'DeepSeek Flash — official API (paid)',
11
+ providerUnavailableOption: '{provider} — unavailable',
12
+ providerUnavailable: 'This provider is unavailable. Configure your DeepSeek account or official API provider, or choose an available service.',
13
+ paidNotice: 'Each uncached fragment sends a separate paid DeepSeek Flash request through the selected account or official API credentials. Reopening reasoning reuses saved results; changing the provider, language, source text, or request settings may send a new paid request.',
14
+ anonymousNotice: 'Bing and Google need no translation login or API key. Their anonymous endpoints may reject or limit requests.', targetLanguage: 'Target language',
15
+ targetLanguageHint: 'auto follows the UI language; language codes such as zh, en, and ja also work.',
16
+ privacy: 'Expanded reasoning is sent to the selected service. It may contain private code or conversation details.',
17
+ translation: 'View translation', original: 'View original', retry: 'Retry', failed: 'Translation failed. Showing the original.',
18
+ translating: 'Translating reasoning', invalidProvider: 'Choose a translation service.', invalidLanguage: 'Enter auto or a language code, such as zh, en, or ja.',
19
+ overridden: 'Overridden', reset: 'Reset to default',
20
+ unavailable: 'Translation preferences are unavailable.', readOnly: 'This deployment stores settings read-only.',
21
+ saveFailed: 'The deployment did not accept these values; they were left for you to correct.', save: 'Save', saving: 'Saving…',
22
+ copy: 'Copy', copied: 'Copied', codeTitle: 'Code block', wrap: 'Wrap lines', unwrap: 'Unwrap lines', footnotes: 'Footnotes',
23
+ }
24
+
25
+ /** Locale dictionary key union. */
26
+ export type CotTranslationKey = keyof typeof en
27
+
28
+ /** Chinese copy. */
29
+ export const zh: Record<CotTranslationKey, string> = {
30
+ provider: '翻译服务', google: 'Google', bing: 'Bing',
31
+ deepseekAccount: 'DeepSeek Flash · 账号(付费)', deepseekOfficial: 'DeepSeek Flash · 官方 API(付费)',
32
+ providerUnavailableOption: '{provider} — 不可用',
33
+ providerUnavailable: '此服务暂不可用,请配置 DeepSeek 账号或官方 API 服务,或选择可用的翻译服务',
34
+ paidNotice: '每个未缓存片段都会通过所选账号或官方 API 凭据单独发送一次付费的 DeepSeek Flash 请求;重新展开会复用已保存的译文,更改服务、语言、原文或请求设置可能发送新的付费请求',
35
+ anonymousNotice: 'Bing 和 Google 翻译无需额外登录或 API key,但匿名接口可能拒绝或限制请求', targetLanguage: '目标语言',
36
+ targetLanguageHint: 'auto 使用界面语言;也可填写语言代码,例如 zh、en、ja',
37
+ privacy: '展开的思考内容会发送给所选翻译服务,可能包含私有代码或对话细节。',
38
+ translation: '查看译文', original: '查看原文', retry: '重试', failed: '翻译暂不可用,已显示原文',
39
+ translating: '正在翻译思考内容', invalidProvider: '请选择翻译服务', invalidLanguage: '请填写 auto 或语言代码,例如 zh、en、ja',
40
+ overridden: '已覆盖', reset: '恢复默认',
41
+ unavailable: '翻译设置暂不可用', readOnly: '本部署的设置为只读',
42
+ saveFailed: '本部署没有接受这些值,已保留供你修改', save: '保存', saving: '保存中…',
43
+ copy: '复制', copied: '已复制', codeTitle: '代码块', wrap: '自动换行', unwrap: '不换行', footnotes: '脚注',
44
+ }
45
+
46
+ /**
47
+ * Read shared form chrome from the plugin dictionary.
48
+ * @param t - current locale reader.
49
+ * @returns localized form labels.
50
+ */
51
+ export function formLabels(t: (key: CotTranslationKey) => string): SettingsFormLabels {
52
+ return { unavailable: t('unavailable'), readOnly: t('readOnly'), saveFailed: t('saveFailed'), save: t('save'), saving: t('saving') }
53
+ }
54
+
55
+ /** Japanese copy, checked against the English keys. */
56
+ export const ja = {
57
+ 'provider': '翻訳サービス',
58
+ 'google': 'Google',
59
+ 'bing': 'Bing',
60
+ 'deepseekAccount': 'DeepSeek Flash — アカウント (有料)',
61
+ 'deepseekOfficial': 'DeepSeek Flash — 公式 API (有料)',
62
+ 'providerUnavailableOption': '{provider} — 利用不可',
63
+ 'providerUnavailable': 'このプロバイダーは利用できません。DeepSeek アカウントまたは公式 API プロバイダーを設定するか、利用可能なサービスを選択してください。',
64
+ 'paidNotice': 'キャッシュされていないフラグメントごとに、選択したアカウントまたは公式 API の認証情報を通じて、個別の有料 DeepSeek Flash リクエストが送信されます。推論を再度開くと保存済みの結果が再利用されますが、プロバイダー、言語、ソーステキスト、またはリクエスト設定を変更すると、新たな有料リクエストが送信される場合があります。',
65
+ 'anonymousNotice': 'Bing と Google は翻訳のログインや API キーが不要です。これらの匿名エンドポイントはリクエストを拒否したり制限したりする場合があります。',
66
+ 'targetLanguage': '翻訳先の言語',
67
+ 'targetLanguageHint': 'auto は UI の言語に従います。zh、en、ja などの言語コードも使用できます。',
68
+ 'privacy': '展開された推論は選択したサービスに送信されます。非公開のコードや会話の詳細が含まれている可能性があります。',
69
+ 'translation': '翻訳を表示',
70
+ 'original': '原文を表示',
71
+ 'retry': '再試行',
72
+ 'failed': '翻訳に失敗しました。原文を表示しています。',
73
+ 'translating': '推論を翻訳中',
74
+ 'invalidProvider': '翻訳サービスを選択してください。',
75
+ 'invalidLanguage': 'auto または zh、en、ja などの言語コードを入力してください。',
76
+ 'overridden': '上書き済み',
77
+ 'reset': 'デフォルトに戻す',
78
+ 'unavailable': '翻訳設定を利用できません。',
79
+ 'readOnly': 'このデプロイでは設定は読み取り専用で保存されます。',
80
+ 'saveFailed': 'このデプロイでは値が受け入れられませんでした。修正のために値はそのまま残されています。',
81
+ 'save': '保存',
82
+ 'saving': '保存中…',
83
+ 'copy': 'コピー',
84
+ 'copied': 'コピーしました',
85
+ 'codeTitle': 'コードブロック',
86
+ 'wrap': '折り返し',
87
+ 'unwrap': '折り返しを解除',
88
+ 'footnotes': '脚注',
89
+ } satisfies Record<keyof typeof en, string>
90
+
91
+ /** Spanish dictionary, checked against the English keys. */
92
+ export const es = {
93
+ provider: 'Servicio de traducción', google: 'google', bing: 'Bing',
94
+ deepseekAccount: 'DeepSeek Flash — cuenta (pago)', deepseekOfficial: 'Flash DeepSeek: API oficial (de pago)',
95
+ providerUnavailableOption: '{provider} — no disponible',
96
+ providerUnavailable: 'Este proveedor no está disponible. Configura tu cuenta DeepSeek o proveedor oficial de API, o elige un servicio disponible.',
97
+ paidNotice: 'Cada fragmento no almacenado en caché envía una solicitud Flash DeepSeek paga por separado a través de la cuenta seleccionada o las credenciales oficiales de API. El razonamiento de reapertura reutiliza los resultados guardados; cambiar el proveedor, el idioma, el texto fuente o la configuración de la solicitud puede enviar una nueva solicitud paga.',
98
+ anonymousNotice: 'Bing y Google no necesitan inicio de sesión de traducción ni clave API. Sus puntos finales anónimos pueden rechazar o limitar solicitudes.', targetLanguage: 'Idioma de destino',
99
+ targetLanguageHint: 'auto sigue el idioma de la interfaz de usuario; Los códigos de idioma como zh, en y ja también funcionan.',
100
+ privacy: 'Se envía el razonamiento ampliado al servicio seleccionado. Puede contener código privado o detalles de la conversación.',
101
+ translation: 'Ver traducción', original: 'Ver original', retry: 'Reintentar', failed: 'La traducción falló. Mostrando el original.',
102
+ translating: 'Traducir razonamiento', invalidProvider: 'Elija un servicio de traducción.', invalidLanguage: 'Ingrese auto o un código de idioma, como zh, en o ja.',
103
+ overridden: 'Anulado', reset: 'Restablecer los valores predeterminados',
104
+ unavailable: 'Las preferencias de traducción no están disponibles.', readOnly: 'Esta implementación almacena configuraciones de solo lectura.',
105
+ saveFailed: 'El despliegue no aceptó estos valores; quedaron para que usted los corrigiera.', save: 'Guardar', saving: 'Guardando…',
106
+ copy: 'Copiar', copied: 'Copiado', codeTitle: 'Bloque de código', wrap: 'Ajustar líneas', unwrap: 'Desenvolver líneas', footnotes: 'Notas a pie de página',
107
+ } satisfies Record<keyof typeof en, string>
108
+
109
+ /** French dictionary, checked against the English keys. */
110
+ export const fr = {
111
+ provider: 'Service de traduction', google: 'Google', bing: 'Bing',
112
+ deepseekAccount: 'DeepSeek Flash — compte (payant)', deepseekOfficial: 'DeepSeek Flash — API officiel (payant)',
113
+ providerUnavailableOption: '{provider} — indisponible',
114
+ providerUnavailable: "Ce fournisseur n'est pas disponible. Configurez votre compte DeepSeek ou votre fournisseur officiel API, ou choisissez un service disponible.",
115
+ paidNotice: "Chaque fragment non mis en cache envoie une demande Flash DeepSeek payante distincte via le compte sélectionné ou les informations d'identification officielles API. La réouverture du raisonnement réutilise les résultats enregistrés ; la modification du fournisseur, de la langue, du texte source ou des paramètres de la demande peut envoyer une nouvelle demande payante.",
116
+ anonymousNotice: "Bing et Google n'ont pas besoin de connexion de traduction ni de clé API. Leurs points de terminaison anonymes peuvent rejeter ou limiter les demandes.", targetLanguage: 'Langue cible',
117
+ targetLanguageHint: "auto suit la langue de l'interface utilisateur ; les codes de langue tels que zh, en et ja fonctionnent également.",
118
+ privacy: 'Le raisonnement étendu est envoyé au service sélectionné. Il peut contenir du code privé ou des détails de conversation.',
119
+ translation: 'Voir la traduction', original: "Voir l'original", retry: 'Réessayer', failed: "La traduction a échoué. Montrant l'original.",
120
+ translating: 'Traduire le raisonnement', invalidProvider: 'Choisissez un service de traduction.', invalidLanguage: 'Saisissez auto ou un code de langue, tel que zh, en ou ja.',
121
+ overridden: 'Remplacé', reset: 'Réinitialiser aux valeurs par défaut',
122
+ unavailable: 'Les préférences de traduction ne sont pas disponibles.', readOnly: 'Ce déploiement stocke les paramètres en lecture seule.',
123
+ saveFailed: "Le déploiement n'a pas accepté ces valeurs ; ils vous ont été laissés à corriger.", save: 'Enregistrer', saving: 'Sauvegarde…',
124
+ copy: 'Copier', copied: 'Copié', codeTitle: 'Bloc de code', wrap: 'Activer le retour à la ligne', unwrap: 'Dérouler les lignes', footnotes: 'Notes de bas de page',
125
+ } satisfies Record<keyof typeof en, string>
126
+
127
+ /** German dictionary, checked against the English keys. */
128
+ export const de = {
129
+ provider: 'Übersetzungsdienst', google: 'Google', bing: 'Bing',
130
+ deepseekAccount: 'DeepSeek Flash – Konto (kostenpflichtig)', deepseekOfficial: 'DeepSeek Flash – offizieller API (kostenpflichtig)',
131
+ providerUnavailableOption: '{provider} – nicht verfügbar',
132
+ providerUnavailable: 'Dieser Anbieter ist nicht verfügbar. Konfigurieren Sie Ihr DeepSeek-Konto oder Ihren offiziellen API-Anbieter oder wählen Sie einen verfügbaren Dienst.',
133
+ paidNotice: 'Jedes nicht zwischengespeicherte Fragment sendet eine separate kostenpflichtige DeepSeek-Flash-Anfrage über das ausgewählte Konto oder die offiziellen API-Anmeldeinformationen. Beim erneuten Öffnen der Argumentation werden gespeicherte Ergebnisse wiederverwendet. Wenn Sie den Anbieter, die Sprache, den Quelltext oder die Anfrageeinstellungen ändern, wird möglicherweise eine neue kostenpflichtige Anfrage gesendet.',
134
+ anonymousNotice: 'Für Bing und Google ist weder ein Übersetzungs-Login noch ein API-Schlüssel erforderlich. Ihre anonymen Endpunkte können Anfragen ablehnen oder einschränken.', targetLanguage: 'Zielsprache',
135
+ targetLanguageHint: 'folgt automatisch der UI-Sprache; Sprachcodes wie zh, en und ja funktionieren ebenfalls.',
136
+ privacy: 'Die erweiterte Begründung wird an den ausgewählten Dienst gesendet. Es kann private Code- oder Konversationsdetails enthalten.',
137
+ translation: 'Übersetzung ansehen', original: 'Original ansehen', retry: 'Erneut versuchen', failed: 'Die Übersetzung ist fehlgeschlagen. Zeigt das Original.',
138
+ translating: 'Argumentation übersetzen', invalidProvider: 'Wählen Sie einen Übersetzungsdienst.', invalidLanguage: 'Geben Sie auto oder einen Sprachcode ein, z. B. zh, en oder ja.',
139
+ overridden: 'Überschrieben', reset: 'Auf Standard zurücksetzen',
140
+ unavailable: 'Übersetzungseinstellungen sind nicht verfügbar.', readOnly: 'Diese Bereitstellung speichert Einstellungen schreibgeschützt.',
141
+ saveFailed: 'Die Bereitstellung hat diese Werte nicht akzeptiert. Sie mussten sie korrigieren.', save: 'Speichern', saving: 'Speichern…',
142
+ copy: 'Kopieren', copied: 'Kopiert', codeTitle: 'Codeblock', wrap: 'Zeilen umbrechen', unwrap: 'Zeilen abwickeln', footnotes: 'Fußnoten',
143
+ } satisfies Record<keyof typeof en, string>
144
+
145
+ /** Russian dictionary, checked against the English keys. */
146
+ export const ru = {
147
+ provider: 'Услуги перевода', google: 'Гугл', bing: 'Бинг',
148
+ deepseekAccount: 'DeepSeek Flash — аккаунт (платный)', deepseekOfficial: 'DeepSeek Flash — официальный API (платный)',
149
+ providerUnavailableOption: '{provider} — недоступен',
150
+ providerUnavailable: 'Этот провайдер недоступен. Настройте свою учетную запись DeepSeek или официального провайдера API или выберите доступную услугу.',
151
+ paidNotice: 'Каждый некэшированный фрагмент отправляет отдельный платный запрос DeepSeek Flash через выбранную учетную запись или официальные учетные данные API. При повторном открытии рассуждений повторно используются сохраненные результаты; изменение провайдера, языка, исходного текста или настроек запроса может привести к отправке нового платного запроса.',
152
+ anonymousNotice: 'Bing и Google не требуют входа в систему для перевода или ключа API. Их анонимные конечные точки могут отклонять или ограничивать запросы.', targetLanguage: 'Целевой язык',
153
+ targetLanguageHint: 'автоматически следует языку пользовательского интерфейса; коды языков, такие как zh, en и ja, также работают.',
154
+ privacy: 'Развернутое обоснование отправляется в выбранную службу. Он может содержать личный код или детали разговора.',
155
+ translation: 'Посмотреть перевод', original: 'Посмотреть оригинал', retry: 'Повторить', failed: 'Перевод не удался. Показываю оригинал.',
156
+ translating: 'Перевод рассуждений', invalidProvider: 'Выберите услугу перевода.', invalidLanguage: 'Введите auto или код языка, например zh, en или ja.',
157
+ overridden: 'Переопределено', reset: 'Сбросить настройки по умолчанию',
158
+ unavailable: 'Настройки перевода недоступны.', readOnly: 'В этом развертывании параметры сохраняются только для чтения.',
159
+ saveFailed: 'Развертывание не приняло эти значения; их оставили вам на исправление.', save: 'Сохранить', saving: 'Сохранение…',
160
+ copy: 'Копировать', copied: 'Скопировано', codeTitle: 'Блок кода', wrap: 'Переносить строки', unwrap: 'Развернуть линии', footnotes: 'Сноски',
161
+ } satisfies Record<keyof typeof en, string>
162
+
163
+ /** Portuguese dictionary, checked against the English keys. */
164
+ export const pt = {
165
+ provider: 'Serviço de tradução', google: 'Google', bing: 'Google',
166
+ deepseekAccount: 'DeepSeek Flash — conta (paga)', deepseekOfficial: 'DeepSeek Flash — oficial API (pago)',
167
+ providerUnavailableOption: '{provider} — indisponível',
168
+ providerUnavailable: 'Este provedor não está disponível. Configure sua conta DeepSeek ou provedor API oficial ou escolha um serviço disponível.',
169
+ paidNotice: 'Cada fragmento não armazenado em cache envia uma solicitação Flash DeepSeek paga separada por meio da conta selecionada ou das credenciais API oficiais. A reabertura do raciocínio reutiliza resultados salvos; alterar o provedor, o idioma, o texto fonte ou as configurações da solicitação pode enviar uma nova solicitação paga.',
170
+ anonymousNotice: 'O Bing e o Google não precisam de login de tradução ou chave API. Seus endpoints anônimos podem rejeitar ou limitar solicitações.', targetLanguage: 'Idioma alvo',
171
+ targetLanguageHint: 'auto segue o idioma da UI; códigos de idioma como zh, en e ja também funcionam.',
172
+ privacy: 'O raciocínio expandido é enviado ao serviço selecionado. Pode conter código privado ou detalhes da conversa.',
173
+ translation: 'Ver tradução', original: 'Ver original', retry: 'Tentar novamente', failed: 'A tradução falhou. Mostrando o original.',
174
+ translating: 'Traduzindo o raciocínio', invalidProvider: 'Escolha um serviço de tradução.', invalidLanguage: 'Insira auto ou um código de idioma, como zh, en ou ja.',
175
+ overridden: 'Substituído', reset: 'Redefinir para o padrão',
176
+ unavailable: 'As preferências de tradução não estão disponíveis.', readOnly: 'Esta implantação armazena configurações somente leitura.',
177
+ saveFailed: 'A implantação não aceitou esses valores; eles foram deixados para você corrigir.', save: 'Salvar', saving: 'Salvando…',
178
+ copy: 'Copiar', copied: 'Copiado', codeTitle: 'Bloco de código', wrap: 'Quebrar linhas', unwrap: 'Desembrulhar linhas', footnotes: 'Notas de rodapé',
179
+ } satisfies Record<keyof typeof en, string>
@@ -0,0 +1,129 @@
1
+ /** Optional Remote contribution and reasoning-slot registration lifecycle. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import type { SessionId } from '@deepseek-ai/dsh-session/types'
4
+ import type {} from '@deepseek-ai/dsh-api-remotes/client'
5
+ import type {} from '@deepseek-ai/dsh-client-locale/client'
6
+ import type {} from '@deepseek-ai/dsh-client-ui-chat/client'
7
+ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
8
+ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
9
+ import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
10
+ import type {} from '@deepseek-ai/dsh-experimental-client-ui-cot-translation/remote'
11
+ import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'
12
+ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
13
+ import type { CotTranslationPreferences, CotTranslationSnapshot } from '../preferences.ts'
14
+ import { TranslationBody, type TranslationBodyInjected } from './TranslationBody.tsx'
15
+ import { TranslationSettings } from './TranslationSettings.tsx'
16
+ import { TranslationPreferencesForm } from './preferences-form.ts'
17
+ import { en, ja, es, fr, de, ru, pt, NS, zh } from './locales.ts'
18
+
19
+ /** Services required to mount the optional Remote and UI contributions. */
20
+ export const inject = ['remote', 'slots', 'locale', 'configForms']
21
+
22
+ async function registerUi(ctx: Context, lifetime: AbortController): Promise<void> {
23
+ let readTask: Promise<RemoteResult<CotTranslationSnapshot>> | undefined
24
+ let updating: Promise<void> | undefined
25
+ let revision = 0, lastReadRevision = -1, acceptedRevision = -1
26
+ const isDisposed = (): boolean => lifetime.signal.aborted || ctx.fiber.uid === null
27
+ ctx.effect(() => async () => {
28
+ lifetime.abort()
29
+ await Promise.allSettled([readTask, updating])
30
+ }, 'cot-translation: metadata queries')
31
+ const invalidate = (): void => { revision += 1; refresh() }
32
+ ctx.effect(() => [
33
+ ctx.remote.$on('settings/document-updated', invalidate),
34
+ ctx.remote.$on('llm/adapters-updated', invalidate),
35
+ ctx.remote.$on('deepseek-account/session-expired', invalidate),
36
+ ctx.remote.$on('deepseek-account/model-sign-in-required', invalidate),
37
+ ctx.remote.$on('credentials/record-updated', invalidate),
38
+ ctx.remote.$on('credentials/reference-updated', invalidate),
39
+ ])
40
+ ctx.on('connection/reset', invalidate)
41
+ const read = async (): Promise<RemoteResult<CotTranslationSnapshot> | undefined> => {
42
+ while (true) {
43
+ const observed = revision
44
+ lastReadRevision = observed
45
+ readTask = ctx.remote.cotTranslation.limits(lifetime.signal)
46
+ const result = await readTask
47
+ if (isDisposed()) return undefined
48
+ if (observed === revision) return result
49
+ }
50
+ }
51
+ let initial: RemoteResult<CotTranslationSnapshot> | undefined
52
+ try { initial = await read() } catch (error) {
53
+ if (isDisposed()) return
54
+ throw error
55
+ }
56
+ if (initial === undefined) return
57
+ if (!initial.ok) throw initial.error
58
+ const preferences = createSnapshotStore(initial.value.preferences)
59
+ const translationLimit = createSnapshotStore(initial.value.maxTextChars)
60
+ const availableProviders = createSnapshotStore(initial.value.availableProviders)
61
+ acceptedRevision = lastReadRevision
62
+ function refresh(): void {
63
+ if (updating !== undefined || acceptedRevision < 0 || isDisposed()) return
64
+ updating = (async () => {
65
+ try {
66
+ const result = await read()
67
+ if (result?.ok) {
68
+ preferences.set(result.value.preferences)
69
+ translationLimit.set(result.value.maxTextChars)
70
+ availableProviders.set(result.value.availableProviders)
71
+ acceptedRevision = lastReadRevision
72
+ }
73
+ } catch (_error) {
74
+ if (!isDisposed()) ctx.logger.warn('cot-translation: could not refresh Host preferences and request limits')
75
+ }
76
+ })().finally(() => {
77
+ updating = undefined
78
+ if (revision !== lastReadRevision && !isDisposed()) refresh()
79
+ })
80
+ }
81
+ const scope = ctx.configForms.get<CotTranslationPreferences>('cot-translation')
82
+ ctx.effect(() => scope.subscribe(invalidate))
83
+ ctx.effect(() => ctx.locale.register(NS, { en, zh, ja, es, fr, de, ru, pt }))
84
+ const form = new TranslationPreferencesForm(scope)
85
+ ctx.effect(() => () => { form.dispose() })
86
+ const injected = (sessionId: SessionId): TranslationBodyInjected => ({
87
+ hooks: { preferences, translationLocale: ctx.locale, translationLimit },
88
+ translate: async (request, signal) => {
89
+ if (acceptedRevision !== revision) refresh()
90
+ while (updating !== undefined) await updating
91
+ signal.throwIfAborted()
92
+ const accepted = preferences.getSnapshot()
93
+ if (isDisposed() || acceptedRevision !== revision || request.provider !== accepted.provider
94
+ || (accepted.targetLanguage !== 'auto' && request.targetLanguage !== accepted.targetLanguage)
95
+ || request.text.length > translationLimit.getSnapshot()) throw new Error('Translation preferences or limits changed')
96
+ const result = await ctx.remote.cotTranslation.translate({ ...request, sessionId }, signal)
97
+ if (!result.ok) throw result.error
98
+ return result.value
99
+ },
100
+ })
101
+ ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register({
102
+ name: 'conversation.chat.reasoning.body', locale: NS,
103
+ inject: injected,
104
+ }, TranslationBody))
105
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
106
+ name: 'plugins.bundle.config', key: '@deepseek-ai/dsh-experimental-cot-translation-bundle', locale: NS,
107
+ inject: () => {
108
+ const face = form.inject()
109
+ return { ...face, hooks: { ...face.hooks, availableProviders }, refreshProviders: invalidate }
110
+ },
111
+ }, TranslationSettings))
112
+ }
113
+
114
+ /**
115
+ * Mount Session-bound translation and withdraw UI before its generated Remote.
116
+ * @param ctx - Client plugin lifetime.
117
+ * @param contribution - generated controller Remote definitions.
118
+ * @returns disposer that removes both contributions.
119
+ */
120
+ export async function mountTranslation(ctx: Context, contribution: TypertRemoteContribution): Promise<() => Promise<void>> {
121
+ const lifetime = new AbortController()
122
+ // Effect cleanup waits for pending setup; uid clearance cancels its query first.
123
+ ctx.on('internal/plugin', (fiber) => { if (fiber === ctx.fiber && fiber.uid === null) lifetime.abort() })
124
+ ctx.effect(() => () => { lifetime.abort() }, 'cot-translation: query cancellation')
125
+ const unmountRemote = await ctx.remote.$mount(contribution)
126
+ const ui = ctx.inject(['remote.cotTranslation', ...inject.slice(1)], child => registerUi(child, lifetime))
127
+ try { await ui } catch (error) { await ui.dispose(); await unmountRemote(); throw error }
128
+ return async () => { await ui.dispose(); await unmountRemote() }
129
+ }
@@ -0,0 +1,48 @@
1
+ /** Staged translation preferences using the shared Plugins form model. */
2
+ import { SettingsFormModel, settingsTextField, type SettingsFieldState, type SettingsFormActions,
3
+ type SettingsFormScope, type SettingsFormShell } from '@deepseek-ai/dsh-client-ui-primitives'
4
+ import type { SnapshotStore } from '@deepseek-ai/dsh-client-store'
5
+ import { LANGUAGE_PREFERENCE_PATTERN, PROVIDER_PREFERENCES, type CotTranslationPreferences } from '../preferences.ts'
6
+
7
+ /** Current drafts and the shared form status. */
8
+ export interface TranslationFormState extends SettingsFormShell {
9
+ provider: SettingsFieldState
10
+ targetLanguage: SettingsFieldState
11
+ }
12
+
13
+ /** Registration-side form observable and edit callbacks. */
14
+ export interface TranslationFormInjected extends SettingsFormActions {
15
+ hooks: { translationForm: SnapshotStore<TranslationFormState> }
16
+ }
17
+
18
+ /** Stages provider and language edits until the reader saves them. */
19
+ export class TranslationPreferencesForm {
20
+ private readonly form: SettingsFormModel<CotTranslationPreferences>
21
+ private readonly state: SnapshotStore<TranslationFormState>
22
+
23
+ /** @param scope - Host-backed configuration form for this plugin. */
24
+ constructor(scope: SettingsFormScope<CotTranslationPreferences>) {
25
+ this.form = new SettingsFormModel(scope, [{
26
+ ...settingsTextField('provider'),
27
+ parse: (text) => {
28
+ const provider = text.trim()
29
+ return provider === '' ? { kind: 'clear' }
30
+ : PROVIDER_PREFERENCES.some(choice => choice === provider) ? { kind: 'set', value: provider } : undefined
31
+ },
32
+ }, {
33
+ ...settingsTextField('targetLanguage'),
34
+ parse: text => LANGUAGE_PREFERENCE_PATTERN.test(text.trim())
35
+ ? { kind: 'set', value: text.trim() } : undefined,
36
+ }])
37
+ this.state = this.form.bind(() => ({ ...this.form.shell(), provider: this.form.field('provider'),
38
+ targetLanguage: this.form.field('targetLanguage') }))
39
+ }
40
+
41
+ /**
42
+ * Build the registration face for the preferences form.
43
+ * @returns draft observable and shared edit/save actions.
44
+ */
45
+ inject(): TranslationFormInjected { return { hooks: { translationForm: this.state }, ...this.form.actions() } }
46
+ /** Release the accepted-preference subscription. */
47
+ dispose(): void { this.form.dispose() }
48
+ }
@@ -0,0 +1,114 @@
1
+ /** Sequential paragraph translation for one expanded reasoning disclosure. */
2
+ import type { TranslationRequest } from '@deepseek-ai/dsh-experimental-translator/types'
3
+
4
+ /** One source fragment and its untranslated separator. */
5
+ interface Fragment { text: string; suffix: string; complete: boolean }
6
+
7
+ /** Display-only result retained while this reasoning disclosure is mounted. */
8
+ export interface TranslationState { text: string; pending: boolean; failed: boolean }
9
+
10
+ /** Cancellation-aware callback supplied by the Remote consumer. */
11
+ export type TranslateText = (request: TranslationRequest, signal: AbortSignal) => Promise<string>
12
+
13
+ /**
14
+ * Split reasoning into completed paragraphs and request-sized fragments.
15
+ * @param text - original reasoning, including its exact whitespace.
16
+ * @param running - whether the final paragraph may still grow.
17
+ * @param maxTextChars - translator's configured UTF-16 request limit.
18
+ * @returns whitespace-preserving fragments with completion flags for translation eligibility.
19
+ */
20
+ export function reasoningFragments(text: string, running: boolean, maxTextChars: number): Fragment[] {
21
+ const result: Fragment[] = []
22
+ const separator = /\r?\n(?:[\t ]*\r?\n)+/g
23
+ let start = 0
24
+ while (true) {
25
+ const match = separator.exec(text)
26
+ let remaining = text.slice(start, match?.index ?? text.length)
27
+ while (remaining.length > maxTextChars) {
28
+ let cut = maxTextChars
29
+ if (/[\uD800-\uDBFF]/.test(remaining.charAt(cut - 1))) cut -= 1
30
+ const whitespace = remaining.slice(0, cut).search(/\s+\S*$/)
31
+ if (whitespace > 0) cut = whitespace
32
+ const source = remaining.slice(0, cut)
33
+ remaining = remaining.slice(cut)
34
+ const suffix = remaining.match(/^\s+/)?.[0] ?? ''
35
+ remaining = remaining.slice(suffix.length)
36
+ result.push({ text: source, suffix, complete: true })
37
+ }
38
+ result.push({ text: remaining, suffix: match?.[0] ?? '', complete: match !== null || !running })
39
+ if (match === null) return result
40
+ start = match.index + match[0].length
41
+ }
42
+ }
43
+
44
+ /** One lifecycle controller owns cancellation, request ordering, and stale-result exclusion. */
45
+ export class ReasoningTranslation {
46
+ private readonly controller = new AbortController()
47
+ private readonly cache = new Map<string, string>()
48
+ private fragments: Fragment[] = []
49
+ private pending = false
50
+ private failed = false
51
+
52
+ /**
53
+ * @param selection - explicit provider and resolved target language.
54
+ * @param maxTextChars - configured translator request limit.
55
+ * @param translate - one cancellation-aware Remote request.
56
+ * @param publish - component-local display state update.
57
+ */
58
+ constructor(
59
+ private readonly selection: Pick<TranslationRequest, 'provider' | 'targetLanguage'>,
60
+ private readonly maxTextChars: number,
61
+ private readonly translate: TranslateText,
62
+ private readonly publish: (state: TranslationState) => void,
63
+ ) {}
64
+
65
+ /**
66
+ * Adopt the current source and enqueue newly completed fragments.
67
+ * @param text - current original reasoning.
68
+ * @param running - whether its tail is still streaming.
69
+ */
70
+ update(text: string, running: boolean): void {
71
+ this.fragments = reasoningFragments(text, running, this.maxTextChars)
72
+ this.emit()
73
+ void this.run()
74
+ }
75
+
76
+ /** Retry untranslated fragments after a failed request. */
77
+ retry(): void { this.failed = false; void this.run() }
78
+
79
+ /** Abort the disclosure's requests and suppress all later publications. */
80
+ dispose(): void { this.controller.abort() }
81
+
82
+ private isDisposed(): boolean { return this.controller.signal.aborted }
83
+
84
+ private emit(): void {
85
+ if (this.isDisposed()) return
86
+ const text = this.fragments.map((fragment) => {
87
+ const content = fragment.complete ? this.cache.get(fragment.text) ?? fragment.text : fragment.text
88
+ return content + fragment.suffix
89
+ }).join('')
90
+ this.publish({ text, pending: this.pending, failed: this.failed })
91
+ }
92
+
93
+ private async run(): Promise<void> {
94
+ if (this.pending || this.failed || this.isDisposed()) return
95
+ let next = this.fragments.find(fragment => fragment.complete && fragment.text.trim() !== '' && !this.cache.has(fragment.text))
96
+ if (next === undefined) return
97
+ this.pending = true
98
+ this.emit()
99
+ try {
100
+ while (next !== undefined) {
101
+ const translated = await this.translate({ ...this.selection, text: next.text }, this.controller.signal)
102
+ if (this.isDisposed()) return
103
+ this.cache.set(next.text, translated)
104
+ this.emit()
105
+ next = this.fragments.find(fragment => fragment.complete && fragment.text.trim() !== '' && !this.cache.has(fragment.text))
106
+ }
107
+ } catch (_error) {
108
+ if (!this.isDisposed()) this.failed = true
109
+ } finally {
110
+ this.pending = false
111
+ this.emit()
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,5 @@
1
+ /** CSS module names emitted by the browser bundle. */
2
+ declare module '*.module.css' {
3
+ const classes: Record<string, string>
4
+ export default classes
5
+ }