@lynn123411/dsh-chat-translate 3.9.5 → 3.9.7

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.
package/lib/client.js CHANGED
@@ -38,7 +38,6 @@ __export(index_exports, {
38
38
  chatTranslate: () => chatTranslate,
39
39
  createChatPresentation: () => createChatPresentation,
40
40
  createTranslateStore: () => createTranslateStore,
41
- ensureAssistantStyles: () => ensureAssistantStyles,
42
41
  inject: () => inject,
43
42
  name: () => name,
44
43
  planAssistantRow: () => planAssistantRow,
@@ -763,15 +762,6 @@ async function testServerChannel(channel) {
763
762
 
764
763
  // src/client/settings/ui.tsx
765
764
  var import_jsx_runtime = require("react/jsx-runtime");
766
- var stylesInjected = false;
767
- function ensureSettingsStyles() {
768
- if (stylesInjected || typeof document === "undefined") return;
769
- const el = document.createElement("style");
770
- el.dataset.tidySettings = "true";
771
- el.textContent = SETTINGS_CSS;
772
- document.head.appendChild(el);
773
- stylesInjected = true;
774
- }
775
765
  var CREDENTIALS_PATH = "~/.dsh/.credentials.yaml";
776
766
  function withSamples(text, samples) {
777
767
  return text.split(/(\{\w+\})/g).map((part, index) => {
@@ -782,7 +772,6 @@ function withSamples(text, samples) {
782
772
  }
783
773
  function TidySettingsPanel(props) {
784
774
  const { t } = props;
785
- ensureSettingsStyles();
786
775
  const [state, setState] = (0, import_react.useState)(() => settingsStore.getState());
787
776
  const [testing, setTesting] = (0, import_react.useState)(null);
788
777
  const [editingPrompt, setEditingPrompt] = (0, import_react.useState)(false);
@@ -811,6 +800,7 @@ function TidySettingsPanel(props) {
811
800
  });
812
801
  };
813
802
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "dsh-tidy-settings", children: [
803
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { "data-tidy-settings": "true", children: SETTINGS_CSS }),
814
804
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "dsh-tidy-card", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "dsh-tidy-title", children: [
815
805
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: t("masterTitle") }),
816
806
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
@@ -1324,15 +1314,14 @@ var RETRY_CLASS = "dsh-ct-retry";
1324
1314
  var RETRY_BUSY_ATTR = "data-busy";
1325
1315
  var RETRY_UNCONFIGURED_ATTR = "data-unconfigured";
1326
1316
  var RETRY_SPIN_CLASS = "dsh-ct-retry-spin";
1327
- function ensureAssistantStyles() {
1317
+ function mountAssistantStyles() {
1328
1318
  if (typeof document === "undefined") return;
1329
- const selector = `style[data-plugin-css=${JSON.stringify(STYLE_TAG_ID)}]`;
1330
- if (document.querySelector(selector) !== null) return;
1331
1319
  const tag = document.createElement("style");
1332
1320
  tag.dataset.plugin = "@lynn123411/dsh-chat-translate";
1333
1321
  tag.dataset.pluginCss = STYLE_TAG_ID;
1334
1322
  tag.textContent = ASSISTANT_CSS;
1335
1323
  document.head.appendChild(tag);
1324
+ return () => tag.remove();
1336
1325
  }
1337
1326
 
1338
1327
  // src/server/pipeline/blocks.ts
@@ -1385,6 +1374,7 @@ var ChatTranslateStore = class {
1385
1374
  rows = /* @__PURE__ */ new Map();
1386
1375
  listeners = /* @__PURE__ */ new Set();
1387
1376
  version = 0;
1377
+ generation = 0;
1388
1378
  fetch;
1389
1379
  /** 已送达的译文,按原文内容寻址:跨行、跨代复用同一段文本的结果。 */
1390
1380
  translated = /* @__PURE__ */ new Map();
@@ -1400,21 +1390,26 @@ var ChatTranslateStore = class {
1400
1390
  getVersion() {
1401
1391
  return this.version;
1402
1392
  }
1403
- /**
1404
- * 丢弃池里全部已送达的译文,让下一轮按现在的提示词重新翻。
1405
- *
1406
- * 提示词换了措辞,池里那些译文是旧措辞的产物:留着它们,读者改了提示词却看不到
1407
- * 任何变化——已经翻过的段落照旧是旧调子,一个请求都不发。宿主半边的磁盘池按提示词
1408
- * 世代作废,这里跟着作废,两边的「换一代」说的是同一件事。
1409
- *
1410
- * 已经显示在屏幕上的译文不动(行状态里那份还在),下一轮需要新译文时才重发。
1411
- * @returns 池里原本是否有东西可丢。
1412
- */
1393
+ getGeneration() {
1394
+ return this.generation;
1395
+ }
1396
+ /** 配置变更只作废可复用的译文与在途请求,行内已经落下的结果继续显示。 */
1413
1397
  dropTranslations() {
1414
- if (this.translated.size === 0) return false;
1398
+ this.generation += 1;
1415
1399
  this.translated.clear();
1400
+ for (const [rowKey, request] of this.pending) {
1401
+ const row = this.rows.get(rowKey);
1402
+ if (row === void 0) continue;
1403
+ const retrying = [...request.texts].filter(([index, text]) => row.texts[index] === text && row.outcomes[index]?.ok === false);
1404
+ this.rows.set(rowKey, { ...row, retrying: retrying.map(([index]) => index) });
1405
+ }
1406
+ this.pending.clear();
1416
1407
  this.bump();
1417
- return true;
1408
+ }
1409
+ /** Client 卸载时同时清掉行内结果。 */
1410
+ reset() {
1411
+ this.rows.clear();
1412
+ this.dropTranslations();
1418
1413
  }
1419
1414
  subscribe = (listener) => {
1420
1415
  this.listeners.add(listener);
@@ -1438,22 +1433,27 @@ var ChatTranslateStore = class {
1438
1433
  * @returns 是否发出了新的请求。
1439
1434
  */
1440
1435
  ensure(rowKey, texts, options = {}) {
1436
+ const generation = this.generation;
1441
1437
  const next = [...texts];
1442
1438
  const frozen = clampFrozen(options.frozen ?? next.length, next.length);
1443
- const retries = normalizeRetries(options.retries);
1444
1439
  const current = this.rows.get(rowKey);
1445
- const settledThrough = current?.settledThrough ?? 0;
1440
+ const inflight = this.pending.get(rowKey);
1441
+ let retries = normalizeRetries(options.retries);
1446
1442
  let seed = null;
1447
1443
  let previousFrozen = 0;
1444
+ let resuming = false;
1448
1445
  const sameGeneration = current !== void 0 && sameTexts(current.texts, next);
1449
- if (current !== void 0 && (sameGeneration || isAppendOnly(current.texts, next))) {
1450
- if (sameGeneration && current.status === "pending") return false;
1451
- if (retries.length === 0 && frozen <= settledThrough && sameGeneration) return false;
1452
- seed = current.outcomes.map((outcome) => outcome === null ? null : { ...outcome });
1446
+ if (current !== void 0 && (sameGeneration || isAppendOnly(current.texts.slice(0, current.settledThrough), next))) {
1447
+ resuming = current.status === "pending" && inflight === void 0;
1448
+ if (resuming) retries = normalizeRetries([...retries, ...current.retrying]);
1449
+ else {
1450
+ if (sameGeneration && current.status === "pending") return false;
1451
+ if (retries.length === 0 && frozen <= current.settledThrough && sameGeneration) return false;
1452
+ }
1453
1453
  previousFrozen = Math.min(current.settledThrough, next.length);
1454
+ seed = current.outcomes.map((outcome) => outcome === null ? null : { ...outcome });
1454
1455
  }
1455
- const inflight = this.pending.get(rowKey);
1456
- const plan = this.planFor(next, frozen, retries, previousFrozen, seed, current?.texts, inflight);
1456
+ const plan = this.planFor(next, frozen, retries, resuming ? 0 : previousFrozen, seed, inflight);
1457
1457
  if (plan.indexes.length > 0) {
1458
1458
  const entry = inflight ?? { texts: /* @__PURE__ */ new Map() };
1459
1459
  for (let i = 0; i < plan.indexes.length; i++) {
@@ -1467,13 +1467,13 @@ var ChatTranslateStore = class {
1467
1467
  status: work || inflight !== void 0 && inflight.texts.size > 0 ? "pending" : "settled",
1468
1468
  texts: next,
1469
1469
  outcomes: plan.outcomes,
1470
- settledThrough: settleThrough(settledThrough, frozen),
1470
+ settledThrough: settleThrough(previousFrozen, frozen),
1471
1471
  retrying: work ? plan.retrying : []
1472
1472
  });
1473
1473
  this.prune();
1474
1474
  this.bump();
1475
- if (!work) return false;
1476
- void this.run(rowKey, next, frozen, plan.indexes, plan.sending);
1475
+ if (!work || generation !== this.generation) return false;
1476
+ void this.run(generation, rowKey, next, frozen, plan.indexes, plan.sending);
1477
1477
  return true;
1478
1478
  }
1479
1479
  /**
@@ -1482,7 +1482,7 @@ var ChatTranslateStore = class {
1482
1482
  * 只对**已经写定、而且内容还没命中**的块发请求。自动首跑里先前写定的下标一律
1483
1483
  * 跳过(它们要么已经成功,要么在等手点补跑);`retries` 只对点名的块解禁一次。
1484
1484
  */
1485
- planFor(texts, frozen, retries, previousFrozen, seed, seedTexts, inflight) {
1485
+ planFor(texts, frozen, retries, previousFrozen, seed, inflight) {
1486
1486
  const outcomes = texts.map((_, index) => seed?.[index] ?? null);
1487
1487
  const retrySet = new Set(retries);
1488
1488
  const indexes = [];
@@ -1493,7 +1493,9 @@ var ChatTranslateStore = class {
1493
1493
  outcomes[index] = null;
1494
1494
  continue;
1495
1495
  }
1496
- const cached = this.translated.get(cacheKey(text));
1496
+ const kept = seed?.[index];
1497
+ if (kept?.ok === true) continue;
1498
+ const cached = this.translated.get(text);
1497
1499
  if (cached !== void 0) {
1498
1500
  outcomes[index] = { translated: cached, ok: true };
1499
1501
  continue;
@@ -1509,11 +1511,7 @@ var ChatTranslateStore = class {
1509
1511
  sending.push(text);
1510
1512
  continue;
1511
1513
  }
1512
- const kept = seed?.[index];
1513
- if (kept !== null && kept !== void 0 && seedTexts?.[index] === text) {
1514
- outcomes[index] = { ...kept };
1515
- continue;
1516
- }
1514
+ if (kept !== null && kept !== void 0) continue;
1517
1515
  if (index < previousFrozen) continue;
1518
1516
  if (outcomes[index] === null) {
1519
1517
  indexes.push(index);
@@ -1523,18 +1521,20 @@ var ChatTranslateStore = class {
1523
1521
  }
1524
1522
  return { indexes, sending, outcomes, retrying: indexes };
1525
1523
  }
1526
- async run(rowKey, body, frozen, indexes, sending) {
1524
+ async run(generation, rowKey, body, frozen, indexes, sending) {
1527
1525
  const collected = /* @__PURE__ */ new Map();
1528
1526
  const sent = /* @__PURE__ */ new Map();
1529
1527
  for (let i = 0; i < indexes.length; i++) sent.set(indexes[i], sending[i] ?? "");
1530
1528
  let cursor = 0;
1531
1529
  for (const batch of chunkTexts(sending)) {
1530
+ if (generation !== this.generation) return;
1532
1531
  let results = [];
1533
1532
  try {
1534
1533
  results = await this.fetch(batch);
1535
1534
  } catch {
1536
1535
  results = [];
1537
1536
  }
1537
+ if (generation !== this.generation) return;
1538
1538
  for (let i = 0; i < batch.length; i++) {
1539
1539
  const index = indexes[cursor + i];
1540
1540
  if (index === void 0) break;
@@ -1542,7 +1542,7 @@ var ChatTranslateStore = class {
1542
1542
  const result = results[i];
1543
1543
  if (result !== void 0 && result.ok && result.translated && result.translated.trim()) {
1544
1544
  collected.set(index, { translated: result.translated, ok: true });
1545
- this.translated.set(cacheKey(text), result.translated);
1545
+ this.translated.set(text, result.translated);
1546
1546
  } else {
1547
1547
  const detail = typeof result?.detail === "string" && result.detail !== "" ? result.detail : void 0;
1548
1548
  collected.set(index, {
@@ -1556,7 +1556,7 @@ var ChatTranslateStore = class {
1556
1556
  cursor += batch.length;
1557
1557
  this.commit(rowKey, frozen, indexes, sent, collected);
1558
1558
  }
1559
- this.commit(rowKey, frozen, indexes, sent, collected, true);
1559
+ if (generation === this.generation) this.commit(rowKey, frozen, indexes, sent, collected, true);
1560
1560
  }
1561
1561
  /**
1562
1562
  * 把这一次请求已经拿到的结果写回行。
@@ -1609,9 +1609,6 @@ var ChatTranslateStore = class {
1609
1609
  }
1610
1610
  }
1611
1611
  };
1612
- function cacheKey(text) {
1613
- return text.trim().toLowerCase();
1614
- }
1615
1612
  function settleThrough(current, frozen) {
1616
1613
  return Math.max(current, frozen);
1617
1614
  }
@@ -1912,7 +1909,6 @@ function ProseBlock({
1912
1909
  );
1913
1910
  }
1914
1911
  var AssistantStepView = (0, import_react3.memo)(function AssistantStepView2(props) {
1915
- ensureAssistantStyles();
1916
1912
  const { store, node, groupPart, useDisclosure, useTurnData, turnProcess, openFile, renderFactorySlot, loadImage, fileMentions, usePresentation, useGroupAction, t } = props;
1917
1913
  const groupAction = typeof useGroupAction === "function" ? useGroupAction : useFallbackGroupAction;
1918
1914
  const data = node.data;
@@ -1929,8 +1925,10 @@ var AssistantStepView = (0, import_react3.memo)(function AssistantStepView2(prop
1929
1925
  () => settingsStore.getState().committed.aiConfigured
1930
1926
  );
1931
1927
  (0, import_react3.useSyncExternalStore)(subscribeStore, () => translate.getVersion());
1928
+ const generation = translate.getGeneration();
1932
1929
  const channel = !enabled ? "off" : aiConfigured ? "ready" : "unconfigured";
1933
- const rowKey = `a${node.anchorSeq ?? `t${data.turn}:s${data.step}`}`;
1930
+ const anchor = `a${node.anchorSeq ?? `t${data.turn}:s${data.step}`}`;
1931
+ const rowKey = props.sessionId === void 0 ? anchor : JSON.stringify([props.sessionId, anchor]);
1934
1932
  const labels = (0, import_react3.useMemo)(() => markdownLabels(t), [t]);
1935
1933
  const pathImages = (0, import_react3.useMemo)(
1936
1934
  () => ({ resolve: (value) => localPathMediaUrl(document.baseURI, value) }),
@@ -1978,7 +1976,7 @@ var AssistantStepView = (0, import_react3.memo)(function AssistantStepView2(prop
1978
1976
  (0, import_react3.useEffect)(() => {
1979
1977
  if (!canTranslate || !inView || plan.entries === null || frozenCount === 0) return;
1980
1978
  translate.ensure(rowKey, plan.texts, { frozen: frozenCount });
1981
- }, [canTranslate, inView, rowKey, plan, frozenCount, translate]);
1979
+ }, [canTranslate, inView, rowKey, plan, frozenCount, translate, generation]);
1982
1980
  const [originalKeys, setOriginalKeys] = (0, import_react3.useState)(() => /* @__PURE__ */ new Set());
1983
1981
  const registered = translate.getState(rowKey);
1984
1982
  const rowState = registered !== void 0 && sameTexts(registered.texts, plan.texts) ? registered : void 0;
@@ -2177,11 +2175,16 @@ function createChatPresentation() {
2177
2175
  }
2178
2176
  var chatPresentation = createChatPresentation();
2179
2177
 
2178
+ // src/translation-config.ts
2179
+ function translationConfigKey(config) {
2180
+ return JSON.stringify([resolvePrompt(config.prompt), config.baseUrl?.trim() ?? "", config.model?.trim() ?? ""]);
2181
+ }
2182
+
2180
2183
  // src/client/index.ts
2181
2184
  var name = "dsh-chat-translate";
2182
2185
  var inject = ["slots", "configForms", "remote", "remote.credentials", "locale"];
2183
2186
  function apply(ctx) {
2184
- ensureAssistantStyles();
2187
+ ctx.effect(mountAssistantStyles, "dsh-chat-translate: assistant styles");
2185
2188
  let fileMentions;
2186
2189
  ctx.inject(["chatFileMentions"], (scope) => {
2187
2190
  const service = scope.chatFileMentions;
@@ -2211,6 +2214,7 @@ function apply(ctx) {
2211
2214
  // fileMentions 由这条注册项自己提供(0.2.2 起不再走 owner props),
2212
2215
  // 服务缺席时返回 undefined,正文里的提及链接随之停用。
2213
2216
  inject: (sessionId) => ({
2217
+ sessionId,
2214
2218
  hooks: { presentation: chatPresentation },
2215
2219
  fileMentions: (owner) => fileMentions?.forClosing(owner, sessionId)
2216
2220
  })
@@ -2231,16 +2235,19 @@ function apply(ctx) {
2231
2235
  }, "dsh-chat-translate: chat presentation source");
2232
2236
  ctx.effect(() => setupSettingsUi(ctx), "dsh-chat-translate: plugins page config");
2233
2237
  ctx.effect(() => setupComposerToggle(ctx), "dsh-chat-translate: composer dock toggle");
2234
- let lastPrompt = settingsStore.getState().committed.prompt;
2235
- ctx.effect(
2236
- () => settingsStore.subscribe(() => {
2237
- const next = settingsStore.getState().committed.prompt;
2238
- if (next === lastPrompt) return;
2239
- lastPrompt = next;
2238
+ ctx.effect(() => {
2239
+ let current = translationConfigKey(settingsStore.getState().committed);
2240
+ const unsubscribe = settingsStore.subscribe(() => {
2241
+ const next = translationConfigKey(settingsStore.getState().committed);
2242
+ if (next === current) return;
2243
+ current = next;
2240
2244
  chatTranslate.dropTranslations();
2241
- }),
2242
- "dsh-chat-translate: relay pool follows the prompt"
2243
- );
2245
+ });
2246
+ return () => {
2247
+ unsubscribe();
2248
+ chatTranslate.reset();
2249
+ };
2250
+ }, "dsh-chat-translate: cache generation");
2244
2251
  bindRowCopy(ctx.locale);
2245
2252
  }
2246
2253
  return module.exports; } });